Is there the technical possibility in Gitlab that a custom adaption of the repository content is Dome during the merge?

Viewed 57

Is there the possibility that I can add e.g. a script which is executed during the merge Step in gitlab which can change some content of the repository?

Standard Workflow which is fully Supported with GitLab

  1. Create Merge Request in GitLab
  2. Add it to merge train to be merged
  3. Gitlab creates merge commit (temporary) if no conflicts are detected
  4. Pipeline runs to do some Integration steps
  5. Merge commit is pushed if pipeline execution was successful

What I Need additional:

I want to execute a Script after step 3 which might change again some files of the repository. These changes should be integrated in the merge commit. Something like executing a cleaner Script which is executed after the git merge before the merge commit is done (and this on remote side in Gitlab as part of the merge process).

Does anyone have an idea with a technical Solution? I would really appreciate it

1 Answers

It's possible, but it's not straightforward. What you are building is basically a bot, which will have to assume some kind of personality in order to modify the code, commit and push it to the repository (ideally - via a MR).

We're using such an approach for cases like:

  • automated bumping of VERSION files
  • automating merge requests in repo B, based on changes in repo A
  • etc.

Solution

The solution is maybe a bit more generic than what you actually need, so you might need to simplify, but it works quite well.

You will need:

  1. A separate repo, where you will store the automation, let's call it bot repo
  2. An Access Token created in the target repo, with api, write_repository scopes, let's call it AUTO_MR_TOKEN
  3. A secret created in bot repo, with the contents of the AUTO_MR_TOKEN

In the bot repo you would create a gitlab-ci.yml which would have the following step:

add_mr:
  script:
    # SETUP THE ENVIRONMENT HERE
    - TARGET_REPO="https://oauth2:${AUTO_MR_TOKEN}@${CI_SERVER_HOST}/${TARGET_PROJECT}.git"
    # CLONE THE TARGET REPO
    - git clone -b $TARGET_BRANCH --single-branch $TARGET_REPO
    - git config user.email "${GIT_USER_EMAIL:-$GITLAB_USER_EMAIL}"
    - git config user.name "${GIT_USER_NAME:-$GITLAB_USER_NAME}"
    # MAKE CHANGES
    - echo "DO YOUR MAGIC HERE"
    - |
      git commit -m "commit from bot"
      git push origin master $TARGET_BRANCH \
        -o merge_request.create \
        -o merge_request.target=master 

Then, in the target repo - you would trigger this bot job, depending on your workflow, in the appropriate step of your pipeline.

Related