简体   繁体   中英

In GitLab how to change file contents automatically when doing a push to a feature branch and then undo that change when merge into master?

I use GitLab on-premise and need to change the contents of a file automatically when I push into my feature branch so when tests run and code is executed, one of the files called from within the repo itself has modified content. When I merge that branch into master, I need to undo that change.

It's not enough to override the file contents just when the test runs, because of how the application works. It will end up pulling the repo from GitLab on it's own and execute one of the files contained within.

I have been looking into hooks a little bit, but I can't find any references or examples on how to accomplish something like this.

Currently I am changing the file manually so my CI tests run accurately. If the tests then pass, I can manually change the file back and skip the CI tests on the final push, and then merge into master.

There's not really a default way to automatically change, commit and push back into Gitlab from a pipeline, as the pipeline does not have authorization to write into the repo.

However, you can provide a "Personal Access Token" (PAT) for one of Gitlab's users (or even a special service-account created for that purpose) - either commit that to your repo (which is quite unsafe) or provide it through the "CI/CD Variables" setting from within Gitlab.

Your pipeline will then need to do something like:

# change file.txt

# add the remote with credentials authorized to commit; do not fail if the remote already exists
git remote remove pushorigin || true
git remote add pushorigin https://commituser:${PAT}@gitlab.local/path/to/project.git

# add and commit the file
git add file.txt
git commit -m "Commit Message"

# move the remote's branch tip:
git push pushorigin "HEAD:${CI_COMMIT_REF_NAME}"

I don't have a clue how to revert that automatically when/before finally merging the branch. Don't you mind those testing commits being merged back into main, possibly creating conflicts on those files?

I guess overall, the application should be modified to better support testing on those branches.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM