Last active
January 25, 2022 04:46
-
-
Save phucngta/d5a29848a59fbe311ac656eb45d551d5 to your computer and use it in GitHub Desktop.
Auto sync current release branch to master
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| import gitlab | |
| import os | |
| CI_SERVER_HOST = os.environ['CI_SERVER_HOST'] | |
| CI_PROJECT_ID = os.environ['CI_PROJECT_ID'] | |
| SERVER_URL = f'https://{CI_SERVER_HOST}' | |
| GITLAB_PERSONAL_TOKEN = os.environ['GITLAB_PERSONAL_TOKEN'] | |
| CI_COMMIT_REF_NAME = os.environ['CI_COMMIT_REF_NAME'] | |
| CURRENT_RELEASE_BRANCH = os.environ['CURRENT_RELEASE_BRANCH'] | |
| gl = gitlab.Gitlab(SERVER_URL, private_token=GITLAB_PERSONAL_TOKEN) | |
| project = gl.projects.get(CI_PROJECT_ID) | |
| TARGET_BRANCH = 'master' | |
| def sync_release_branch_to_master_branch(): | |
| if CURRENT_RELEASE_BRANCH == CI_COMMIT_REF_NAME: | |
| mrs = project.mergerequests.list( | |
| query_parameters={ | |
| 'state': 'opened', 'source_branch': CURRENT_RELEASE_BRANCH, 'target_branch': TARGET_BRANCH} | |
| ) | |
| if not mrs: | |
| print(f"Create new Merge Request branch {CURRENT_RELEASE_BRANCH} into {TARGET_BRANCH}") | |
| mr = project.mergerequests.create( | |
| { | |
| 'source_branch': CURRENT_RELEASE_BRANCH, | |
| 'target_branch': TARGET_BRANCH, | |
| 'title': f"Sync Current Release Branch {CURRENT_RELEASE_BRANCH} into Master Branch {TARGET_BRANCH}" | |
| } | |
| ) | |
| else: | |
| mr = mrs[0] | |
| if not mr.changes()['changes']: | |
| print(f"Delete Empty Merge Request ({CURRENT_RELEASE_BRANCH} into {TARGET_BRANCH})") | |
| mr.state_event = 'close' | |
| mr.save() | |
| else: | |
| print(f"Merged Merge Request ({CURRENT_RELEASE_BRANCH} into {TARGET_BRANCH})") | |
| mr.merge() | |
| if __name__ == "__main__": | |
| sync_release_branch_to_master_branch() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment