Skip to content

Instantly share code, notes, and snippets.

@nagyv
Created September 14, 2021 07:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nagyv/389cbea7171f1737e30b26cf503d342c to your computer and use it in GitHub Desktop.
Save nagyv/389cbea7171f1737e30b26cf503d342c to your computer and use it in GitHub Desktop.
GitLab CI job for Git push
# Usage
# in .gitlab-ci.yml
# commit packages:
# extends: .git:push
# stage: deploy
# variables:
# COMMIT_MESSAGE: "Hydrated packages"
# script:
# cp -r file-to-commit/* "${CI_COMMIT_SHA}/file-to-commit/"
# dependencies:
# - "files-come-from-another-job"
# Originally from https://www.benjaminrancourt.ca/how-to-push-to-a-git-repository-from-a-gitlab-ci-pipeline
.git:push:
image:
name: alpine/git:v2.30.2
entrypoint: ['']
after_script:
# Go to the new directory
- cd "${CI_COMMIT_SHA}"
# Add all generated files to Git
- git add .
- |-
# Check if we have modifications to commit
CHANGES=$(git status --porcelain | wc -l)
if [ "$CHANGES" -gt "0" ]; then
# Show the status of files that are about to be created, updated or deleted
git status
# Commit all changes
git commit -m "${COMMIT_MESSAGE}"
# Update the repository and make sure to skip the pipeline create for this commit
git push -o ci.skip
else
echo "Nothing to commit"
fi
before_script:
# Clone the repository via HTTPS inside a new directory
- git clone "https://${GITLAB_USER_NAME}:${GITLAB_TOKEN}@${CI_SERVER_HOST}/${CI_PROJECT_PATH}.git" "${CI_COMMIT_SHA}"
- cd "${CI_COMMIT_SHA}"
# Check out branch if it's not master
# TODO: In MR pipelines, use ${CI_MERGE_REQUEST_SOURCE_BRANCH_NAME}
- |
if [[ "${CI_COMMIT_BRANCH}" != "${CI_DEFAULT_BRANCH}" ]]; then
git fetch
git checkout -t "origin/${CI_COMMIT_BRANCH}"
fi
- git branch
# Set the displayed user with the commits that are about to be made
- git config --global user.email "${GIT_USER_EMAIL:-$GITLAB_USER_EMAIL}"
- git config --global user.name "${GIT_USER_NAME:-$GITLAB_USER_NAME}"
- cd "${CI_PROJECT_DIR}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment