├── .github └── workflows │ └── docker-image.yml ├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md ├── conf ├── crontab │ └── cron.example ├── logrotate │ └── gitlab-sync.conf └── ssh │ └── config ├── docker-compose.yml ├── entrypoint.sh ├── env.sample ├── requirements.txt ├── scripts └── period_task.sh └── src ├── change-gitlab-branch.py ├── common ├── __init__.py ├── git_repo.py ├── gitlab_wrapper.py ├── init_argparse.py └── init_logging.py └── gitlab-sync /.github/workflows/docker-image.yml: -------------------------------------------------------------------------------- 1 | name: Docker Build 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | build: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - name: Build the Docker image 10 | uses: actions/checkout@v2 11 | 12 | - name: Run docker build 13 | run: docker build . --file Dockerfile --tag registry.cn-shanghai.aliyuncs.com/ray-dockers/gitlab-sync:latest 14 | 15 | - name: Login Aliyun dockerhub 16 | run: docker login -u ${{ secrets.ALIYUN_DOCKERHUB_USERNAME }} -p ${{ secrets.ALIYUN_DOCKERHUB_PASSWORD }} registry.cn-shanghai.aliyuncs.com 17 | 18 | - name: Push to aliyun dockerhub 19 | run: docker push registry.cn-shanghai.aliyuncs.com/ray-dockers/gitlab-sync:latest 20 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .env 2 | conf/crontab/cron 3 | conf/ssh/id_rsa* 4 | 5 | # Byte-compiled / optimized / DLL files 6 | __pycache__/ 7 | *.py[cod] 8 | *$py.class 9 | 10 | # C extensions 11 | *.so 12 | 13 | # Distribution / packaging 14 | .Python 15 | build/ 16 | develop-eggs/ 17 | dist/ 18 | downloads/ 19 | eggs/ 20 | .eggs/ 21 | lib/ 22 | lib64/ 23 | parts/ 24 | sdist/ 25 | var/ 26 | wheels/ 27 | share/python-wheels/ 28 | *.egg-info/ 29 | .installed.cfg 30 | *.egg 31 | MANIFEST 32 | 33 | # PyInstaller 34 | # Usually these files are written by a python script from a template 35 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 36 | *.manifest 37 | *.spec 38 | 39 | # Installer logs 40 | pip-log.txt 41 | pip-delete-this-directory.txt 42 | 43 | # Unit test / coverage reports 44 | htmlcov/ 45 | .tox/ 46 | .nox/ 47 | .coverage 48 | .coverage.* 49 | .cache 50 | nosetests.xml 51 | coverage.xml 52 | *.cover 53 | *.py,cover 54 | .hypothesis/ 55 | .pytest_cache/ 56 | cover/ 57 | 58 | # Translations 59 | *.mo 60 | *.pot 61 | 62 | # Django stuff: 63 | *.log 64 | local_settings.py 65 | db.sqlite3 66 | db.sqlite3-journal 67 | 68 | # Flask stuff: 69 | instance/ 70 | .webassets-cache 71 | 72 | # Scrapy stuff: 73 | .scrapy 74 | 75 | # Sphinx documentation 76 | docs/_build/ 77 | 78 | # PyBuilder 79 | .pybuilder/ 80 | target/ 81 | 82 | # Jupyter Notebook 83 | .ipynb_checkpoints 84 | 85 | # IPython 86 | profile_default/ 87 | ipython_config.py 88 | 89 | # pyenv 90 | # For a library or package, you might want to ignore these files since the code is 91 | # intended to run in multiple environments; otherwise, check them in: 92 | # .python-version 93 | 94 | # pipenv 95 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 96 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 97 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 98 | # install all needed dependencies. 99 | #Pipfile.lock 100 | 101 | # poetry 102 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 103 | # This is especially recommended for binary packages to ensure reproducibility, and is more 104 | # commonly ignored for libraries. 105 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 106 | #poetry.lock 107 | 108 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 109 | __pypackages__/ 110 | 111 | # Celery stuff 112 | celerybeat-schedule 113 | celerybeat.pid 114 | 115 | # SageMath parsed files 116 | *.sage.py 117 | 118 | # Environments 119 | .env 120 | .venv 121 | env/ 122 | venv/ 123 | ENV/ 124 | env.bak/ 125 | venv.bak/ 126 | 127 | # Spyder project settings 128 | .spyderproject 129 | .spyproject 130 | 131 | # Rope project settings 132 | .ropeproject 133 | 134 | # mkdocs documentation 135 | /site 136 | 137 | # mypy 138 | .mypy_cache/ 139 | .dmypy.json 140 | dmypy.json 141 | 142 | # Pyre type checker 143 | .pyre/ 144 | 145 | # pytype static type analyzer 146 | .pytype/ 147 | 148 | # Cython debug symbols 149 | cython_debug/ 150 | 151 | # PyCharm 152 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 153 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 154 | # and can be added to the global gitignore or merged into this file. For a more nuclear 155 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 156 | #.idea/ 157 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM centos:7 2 | 3 | MAINTAINER Ray Sun 4 | 5 | ENV LANG en_US.UTF-8 6 | 7 | COPY ./src /opt/gitlab-sync 8 | COPY ./requirements.txt /opt/gitlab-sync 9 | COPY ./entrypoint.sh / 10 | COPY ./conf/logrotate/gitlab-sync.conf /etc/logrotate.d/gitlab-sync.conf 11 | WORKDIR /opt/gitlab-sync 12 | 13 | RUN yum -y install epel-release && \ 14 | yum clean all && yum makecache && \ 15 | yum -y install cronie logrotate && \ 16 | yum -y install python3 python3-pip git && \ 17 | pip3 install -r requirements.txt && \ 18 | chmod a+x /opt/gitlab-sync/gitlab-sync && \ 19 | chmod a+x /entrypoint.sh 20 | 21 | ENTRYPOINT ["/entrypoint.sh"] 22 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # About 2 | 3 | This script is used to sync between gitlab in group level, including all subgroups and projects. 4 | 5 | Use the default docker, you can run a schedule job to sync between gitlab. 6 | 7 | 2023-04-04 UPDATE: By default, sync all local groups to remote and you can save all groups under a remote parent group 8 | UPDATE: Support multiple groups sync and no need to pre-create remote groups. 9 | 10 | # How to use script? 11 | 12 | ## (Recommendation)Run in Docker 13 | 14 | If you want to run a schedule job to sync between gitlabs, you can use this docker. By default, the docker use Linux crontab to run period task. Here's the detailed: 15 | 16 | ### Get code 17 | 18 | ``` 19 | git clone https://github.com/xiaoquqi/gitlab-sync 20 | ``` 21 | 22 | ### SSH Keys 23 | 24 | By default, ssh key mount dir is under gitlab-sync/conf/ssh, you can copy your existing keys here or generate a new one. 25 | 26 | ``` 27 | cd gitlab-sync 28 | ssh-keygen -t rsa -b 2048 -f conf/ssh/id_rsa -q -N "" 29 | ``` 30 | 31 | Make sure your own key or generated key already uploaded to local and remote gitlab. By default, we will use ssh url to get local code for private repositories. 32 | 33 | ``` 34 | cat conf/ssh/id_rsa.pub 35 | ``` 36 | 37 | * Login your gitlab 38 | * Right Corner and click icon 39 | * Click [Preferences] 40 | * Select [SSH Keys] on the left menu 41 | * Copy and Paste your public key 42 | * Click [Add Keys] 43 | 44 | ### Modify Environment 45 | 46 | Prepare to copy samples to runtime env and configs 47 | 48 | ``` 49 | cp env.sample .env 50 | cp conf/crontab/cron.exmaple crontab/cron 51 | ``` 52 | 53 | Modify your .env and use your gitlab local and remote configurations. 54 | 55 | * LOCAL_GTILAB_URL: The gitlab you want set as source 56 | * LOCAL_GITLAB_TOKEN: Token to access your gitlab, we need find out all your groups and projects, all the actions are read 57 | * LOCAL_GITLAB_GROUP: Local gitlab groups you sync to remote, use comma to seperate 58 | * REMOTE_GTILAB_URL: Remote gitlab as target 59 | * REMOTE_GTILAB_TOKEN: Token to access your remote gitlab, we need to read and create groups and projects if not exists 60 | * REMOTE_GTILAB_GROUP: Remote root groups you set as target, use comma to seperate, the total nubmers of groups should equal to local groups 61 | * REMOTE_GTILAB_PUSH_URL: Remote push base url, ex: ssh://git@remote.gitlab.com:ssh_port 62 | * IGNORE_BRANCHES: Branches not sync 63 | * ALLOW_BRANCHES: Branches need to sync, ignore branches's priority is higher than ignore branches 64 | * FORCE_PUSH: If add force when push 65 | * REMOTE_PARENT_GROUP: Sync all projects under this parent group 66 | 67 | ### Schedule Settings 68 | 69 | Modify scheduler settings in the conf/crontab/cron file, this file will mount inside docker after running, here's an exmaple: 70 | 71 | You just need to change the crontab scheduler, and ignore the command part. We use flock to lock the task to avoid duplicate running. 72 | 73 | ``` 74 | 0 23 * * * /usr/bin/flock -n /tmp/crontab.lockfile bash /period_task.sh >> /var/log/gitlab-sync.log 75 | ``` 76 | 77 | ### Volume Mounts 78 | 79 | * SSH Keys: By default, we need to use your ssh key to access your gitlab projects. By default, I mount your $HOME/.ssh to /root/.ssh in docker. 80 | * Logs setting: By default, we write the stdout and stderr logs to /var/log/gitlab-sync/gitlab-sync.log and already mount your OS /var/log/gitlab-sync to your host, you can check log from there 81 | 82 | ### Run as Daemon 83 | 84 | ``` 85 | docker-compuse up -d 86 | ``` 87 | 88 | ## CLI Help 89 | 90 | You can also use the script in your own environment, Python 3.6+ and virtualenv are recommended. 91 | 92 | ``` 93 | virtualenv-3 venv3 94 | source venve3/bin/activate 95 | pip install -r src/requirements.txt 96 | ``` 97 | 98 | ``` 99 | usage: gitlab-sync [-h] --local LOCAL --local-token LOCAL_TOKEN [--local-group LOCAL_GROUP] --remote REMOTE --remote-token REMOTE_TOKEN 100 | [--remote-group REMOTE_GROUP] [--remote-parent-group REMOTE_PARENT_GROUP] --push-url PUSH_URL [--force-push] 101 | [--ignore-branches IGNORE_BRANCHES] [--allow-branches ALLOW_BRANCHES] [-d] [-v] 102 | 103 | Gitlab backup tool in group level 104 | 105 | optional arguments: 106 | -h, --help show this help message and exit 107 | --local LOCAL Local gitlab http url, ex: https://local.gitlab.com 108 | --local-token LOCAL_TOKEN 109 | Local gitlab private token. 110 | --local-group LOCAL_GROUP 111 | Local github group for syncing, Leave this as blank when you want to sync all groups 112 | --remote REMOTE Remote gitlab http url, ex: https://remote.gitlab.com 113 | --remote-token REMOTE_TOKEN 114 | Remote gitlab private token 115 | --remote-group REMOTE_GROUP 116 | Target group of remote github for backup, Leave this as blank if you want to keep the same name as remote 117 | --remote-parent-group REMOTE_PARENT_GROUP 118 | Parent group to save all local groups 119 | --push-url PUSH_URL Remote push url for backup target 120 | --force-push Force push to remote by default 121 | --ignore-branches IGNORE_BRANCHES 122 | Not sync for ignore branches, ex: cherry-pick,dev,temp 123 | --allow-branches ALLOW_BRANCHES 124 | Only sync for allow branches, ex: master,main,qa. if not given, sync all branches. If ignore branches is given, 125 | thepriority is higher than this argument 126 | -d, --debug Enable debug message. 127 | -v, --verbose Show message in standard output. 128 | ``` 129 | 130 | # Gitlab Tips 131 | 132 | ## Create a personal access token 133 | 134 | You can create as many personal access tokens as you like. 135 | 136 | 1. In the top-right corner, select your avatar. 137 | 2. Select Edit profile. 138 | 3. On the left sidebar, select Access Tokens. 139 | 4. Enter a name and optional expiry date for the token. 140 | 5. Select the desired scopes. 141 | 6. Select Create personal access token. 142 | 7. Save the personal access token somewhere safe. After you leave the page, you no longer have access to the token. 143 | -------------------------------------------------------------------------------- /conf/crontab/cron.example: -------------------------------------------------------------------------------- 1 | # Use flock to avoid duplicate task running 2 | 0 23 * * * /usr/bin/flock -n /tmp/crontab.lockfile bash /period_task.sh >> /var/log/gitlab-sync/gitlab-sync.log 2>&1 3 | -------------------------------------------------------------------------------- /conf/logrotate/gitlab-sync.conf: -------------------------------------------------------------------------------- 1 | /var/log/gitlab-sync/*.log { 2 | weekly 3 | rotate 4 4 | missingok 5 | compress 6 | copytruncate 7 | minsize 100k 8 | } 9 | -------------------------------------------------------------------------------- /conf/ssh/config: -------------------------------------------------------------------------------- 1 | StrictHostKeyChecking no 2 | UserKnownHostsFile /dev/null 3 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3.3' 2 | services: 3 | gitlab-sync: 4 | build: . 5 | image: 'registry.cn-shanghai.aliyuncs.com/ray-dockers/gitlab-sync:latest' 6 | restart: always 7 | environment: 8 | TZ: "${TZ}" 9 | LOCAL_GTILAB_URL: "${LOCAL_GTILAB_URL}" 10 | LOCAL_GITLAB_TOKEN: "${LOCAL_GITLAB_TOKEN}" 11 | LOCAL_GITLAB_GROUP: "${LOCAL_GITLAB_GROUP}" 12 | REMOTE_GTILAB_URL: "${REMOTE_GTILAB_URL}" 13 | REMOTE_GTILAB_TOKEN: "${REMOTE_GTILAB_TOKEN}" 14 | REMOTE_GTILAB_GROUP: "${REMOTE_GTILAB_GROUP}" 15 | REMOTE_GTILAB_PUSH_URL: "${REMOTE_GTILAB_PUSH_URL}" 16 | IGNORE_BRANCHES: "${IGNORE_BRANCHES}" 17 | ALLOW_BRANCHES: "${ALLOW_BRANCHES}" 18 | FORCE_PUSH: "${FORCE_PUSH}" 19 | REMOTE_PARENT_GROUP: "${REMOTE_PARENT_GROUP}" 20 | volumes: 21 | - './conf/ssh:/root/.ssh' 22 | - './conf/crontab/cron:/var/spool/cron/root' 23 | - './scripts/period_task.sh:/period_task.sh' 24 | - '/var/log/gitlab-sync:/var/log/gitlab-sync' 25 | -------------------------------------------------------------------------------- /entrypoint.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Save current env to crontab_env and crontab job can access docker env 4 | CRONTAB_ENV=/crontab_env 5 | printenv | sed 's/^\(.*\)$/export \1/g' > $CRONTAB_ENV 6 | 7 | /usr/sbin/crond -n 8 | -------------------------------------------------------------------------------- /env.sample: -------------------------------------------------------------------------------- 1 | TZ=Asia/Shanghai 2 | LOCAL_GTILAB_URL=http://local.gitlab.com 3 | LOCAL_GITLAB_TOKEN=your_local_gitlab_token 4 | #LOCAL_GITLAB_GROUP=local_existing_group_to_be_synced 5 | REMOTE_GTILAB_URL=http://remote.gitlab.com 6 | REMOTE_GTILAB_TOKEN=your_remote_gitlab_token 7 | #REMOTE_GTILAB_GROUP=remote_existing_group 8 | REMOTE_GTILAB_PUSH_URL=ssh://git@remote.gitlab.com:ssh_port 9 | IGNORE_BRANCHES=cherry-pick,temp,tmp 10 | ALLOW_BRANCHES=master,qa,production,release 11 | FORCE_PUSH=True 12 | #REMOTE_PARENT_GROUP=remote_parent_group_name 13 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | python-gitlab 2 | GitPython 3 | retrying 4 | -------------------------------------------------------------------------------- /scripts/period_task.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Load crontab env from dump file 4 | source /crontab_env 5 | 6 | echo "/opt/gitlab-sync/gitlab-sync \ 7 | --local $LOCAL_GTILAB_URL \ 8 | --local-token $LOCAL_GITLAB_TOKEN \ 9 | --local-group $LOCAL_GITLAB_GROUP \ 10 | --remote $REMOTE_GTILAB_URL \ 11 | --remote-token $REMOTE_GTILAB_TOKEN \ 12 | --remote-parent-group $REMOTE_PARENT_GROUP \ 13 | --push-url $REMOTE_GTILAB_PUSH_URL \ 14 | --ignore-branches $IGNORE_BRANCHES \ 15 | --allow-branches $ALLOW_BRANCHES \ 16 | --force-push" 17 | 18 | /opt/gitlab-sync/gitlab-sync \ 19 | --debug \ 20 | --verbose \ 21 | --local $LOCAL_GTILAB_URL \ 22 | --local-token $LOCAL_GITLAB_TOKEN \ 23 | --local-group $LOCAL_GITLAB_GROUP \ 24 | --remote $REMOTE_GTILAB_URL \ 25 | --remote-token $REMOTE_GTILAB_TOKEN \ 26 | --remote-parent-group $REMOTE_PARENT_GROUP \ 27 | --push-url $REMOTE_GTILAB_PUSH_URL \ 28 | --ignore-branches $IGNORE_BRANCHES \ 29 | --allow-branches $ALLOW_BRANCHES \ 30 | --force-push 31 | -------------------------------------------------------------------------------- /src/change-gitlab-branch.py: -------------------------------------------------------------------------------- 1 | import gitlab 2 | 3 | # GitLab实例URL和访问令牌 4 | GITLAB_URL = 'https://your.gitlab.instance.com' 5 | GITLAB_TOKEN = 'your-gitlab-access-token' 6 | 7 | # 要修改的组ID和保护分支设置 8 | GROUP_ID = 123 9 | PROTECTED_BRANCH_SETTINGS = { 10 | 'name': 'master', 11 | 'push_access_level': gitlab.DEVELOPER_ACCESS, 12 | 'merge_access_level': gitlab.DEVELOPER_ACCESS, 13 | 'unprotect_access_level': gitlab.DEVELOPER_ACCESS, 14 | } 15 | 16 | # 连接到GitLab API 17 | gl = gitlab.Gitlab(GITLAB_URL, private_token=GITLAB_TOKEN) 18 | 19 | # 获取指定组下的所有项目 20 | group = gl.groups.get(GROUP_ID) 21 | projects = group.projects.list(all=True) 22 | 23 | # 针对每个项目,修改其保护分支设置 24 | for project in projects: 25 | print(f'Modifying protected branch settings for project "{project.name}"...') 26 | try: 27 | branch = project.protectedbranches.get(PROTECTED_BRANCH_SETTINGS['name']) 28 | branch.push_access_level = PROTECTED_BRANCH_SETTINGS['push_access_level'] 29 | branch.merge_access_level = PROTECTED_BRANCH_SETTINGS['merge_access_level'] 30 | branch.unprotect_access_level = PROTECTED_BRANCH_SETTINGS['unprotect_access_level'] 31 | branch.save() 32 | print(f'Successfully modified protected branch settings for project "{project.name}".') 33 | except gitlab.exceptions.GitlabGetError: 34 | print(f'Protected branch "{PROTECTED_BRANCH_SETTINGS["name"]}" does not exist in project "{project.name}".') 35 | except gitlab.exceptions.GitlabUpdateError as e: 36 | print(f'Failed to modify protected branch settings for project "{project.name}": {e}.') 37 | -------------------------------------------------------------------------------- /src/common/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiaoquqi/gitlab-sync/0b6a11234f6bf1243136e2a318352a5ea28195d1/src/common/__init__.py -------------------------------------------------------------------------------- /src/common/git_repo.py: -------------------------------------------------------------------------------- 1 | import urllib.parse 2 | 3 | import git 4 | 5 | # Default ssh options 6 | SSH_CMD = "ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null" 7 | 8 | # Ignore remote refs to get real branches 9 | IGNORE_REFS = ["HEAD"] 10 | 11 | class GitRepo(object): 12 | 13 | def __init__(self, git_url, src_path): 14 | self.git_url = urllib.parse.quote(git_url, safe=':/') 15 | self.src_path = src_path 16 | self._repo = None 17 | 18 | @property 19 | def repo(self): 20 | if not self._repo: 21 | self._repo = git.Repo(self.src_path) 22 | 23 | return self._repo 24 | 25 | @property 26 | def branches(self): 27 | branches = [] 28 | for r in self.repo.remote().refs: 29 | ref = r.remote_head 30 | if ref not in IGNORE_REFS: 31 | branches.append(ref) 32 | 33 | return branches 34 | 35 | @property 36 | def current_branch(self): 37 | return self.repo.active_branch.name 38 | 39 | def clone(self): 40 | git.Repo.clone_from(self.git_url, to_path=self.src_path, 41 | env={'GIT_SSH_COMMAND': SSH_CMD}) 42 | 43 | def pull_branch(self, remote_branch, local_branch=None): 44 | if not local_branch: 45 | local_branch = remote_branch 46 | self.repo.git.fetch(self.git_url, "%s:%s" % ( 47 | remote_branch, local_branch)) 48 | 49 | def push_all_branches(self, force=False): 50 | self.repo.git.push(self.git_url, "--all", force=force) 51 | 52 | def push_all_tags(self, force=False): 53 | self.repo.git.push(self.git_url, "--tags", force=force) 54 | -------------------------------------------------------------------------------- /src/common/gitlab_wrapper.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | import gitlab 4 | import requests 5 | from retrying import retry 6 | 7 | 8 | def retry_if_timeout(exception): 9 | return isinstance(exception, requests.exceptions.ReadTimeout) 10 | 11 | 12 | class GitlabWrapper(object): 13 | 14 | def __init__(self, api_url, private_token): 15 | self.gl = gitlab.Gitlab( 16 | url=api_url, private_token=private_token) 17 | self._groups = [] 18 | 19 | @property 20 | def groups(self): 21 | if not self._groups: 22 | self._groups = self.gl.groups.list(all=True) 23 | 24 | return self._groups 25 | 26 | def group_names(self): 27 | return [g.full_path for g in self.groups] 28 | 29 | def is_group_exists(self, name): 30 | logging.debug("Try to find group %s in group " 31 | "names: %s" % (name, self.group_names())) 32 | return name in self.group_names() 33 | 34 | def is_project_exists(self, name): 35 | pass 36 | 37 | def get_group_id_by_name(self, name): 38 | for g in self.groups: 39 | if g.full_path == name: 40 | logging.debug("Found group id by name %s, " 41 | "group detailed: %s" % (name, g)) 42 | return g.id 43 | 44 | return None 45 | 46 | def group_projects(self, name): 47 | group_id = self.get_group_id_by_name(name) 48 | return self.group_projects_by_id(group_id) 49 | 50 | def group_projects_by_id(self, group_id): 51 | return self.gl.groups.get(group_id).projects.list( 52 | all=True, include_subgroups=True) 53 | 54 | def group_project_names(self, name): 55 | projects = self.group_projects(name) 56 | return [p.name for p in projects] 57 | 58 | def group_project_names_by_id(self, group_id): 59 | projects = self.group_projects_by_id(group_id) 60 | return [p.name for p in projects] 61 | 62 | def create_group(self, namespace): 63 | logging.info("Create group for %s" % namespace) 64 | groups = namespace.split("/") 65 | parent_group_id = None 66 | for index, g in enumerate(groups): 67 | current_namespace = "/".join(groups[0:index + 1]) 68 | logging.debug("Current namespace is %s" % current_namespace) 69 | if not self.is_group_exists(current_namespace): 70 | logging.debug("Group %s is not exists, " 71 | "create it" % current_namespace) 72 | create_group_info = None 73 | if not parent_group_id: 74 | logging.info("Create root group %s" % g) 75 | create_group_info = self.gl.groups.create({ 76 | "name": g, 77 | "path": g 78 | }) 79 | else: 80 | logging.info("Create sub group %s" % current_namespace) 81 | create_group_info = self.gl.groups.create({ 82 | "name": g, 83 | "path": g, 84 | "parent_id": parent_group_id 85 | }) 86 | 87 | parent_group_id = create_group_info.id 88 | # NOTE(Ray): After create group we need to save into 89 | # self._group for next loop 90 | self._groups.append(create_group_info) 91 | else: 92 | parent_group_id = self.get_group_id_by_name(current_namespace) 93 | logging.debug("Group %s is exists, " 94 | "group id is %s" % (g, parent_group_id)) 95 | 96 | return parent_group_id 97 | 98 | @retry(stop_max_attempt_number=3, 99 | wait_fixed=60000, 100 | retry_on_exception=retry_if_timeout) 101 | def ensure_project_exists(self, namespace, project_name): 102 | """Create project with namespace""" 103 | project_url = "%s/%s" % (namespace, project_name) 104 | logging.info("Ensure project %s " 105 | "is exists" % project_url) 106 | project_group_id = None 107 | if not self.is_group_exists(namespace): 108 | logging.info("Can NOT find namespace %s, " 109 | "create a new group." % namespace) 110 | project_group_id = self.create_group(namespace) 111 | else: 112 | logging.info("Found namespace %s " 113 | "in gitlab" % namespace) 114 | project_group_id = self.get_group_id_by_name( 115 | namespace) 116 | 117 | try: 118 | logging.info("Trying to find project %s" % project_url) 119 | project = self.gl.projects.get(project_url) 120 | except requests.exceptions.ReadTimeout as err: 121 | logging.error("Find project failed due to connection" 122 | " timeout by url %s" % project_url) 123 | raise requests.exceptions.ReadTimeout() 124 | except gitlab.exceptions.GitlabConnectionError as err: 125 | logging.error("Find project failed due to connection" 126 | " error by url %s" % project_url) 127 | raise gitlab.exceptions.GitlabConnectionError() 128 | except Exception as e: 129 | logging.warn(e) 130 | logging.info("Project %s CAN NOT be found." % project_url) 131 | project = None 132 | 133 | if not project: 134 | logging.info("Creating project %s, namespace_id " 135 | "is %s..." % (project_name, project_group_id)) 136 | self.gl.projects.create({ 137 | "name": project_name, 138 | "namespace_id": project_group_id 139 | }) 140 | -------------------------------------------------------------------------------- /src/common/init_argparse.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """Common modules for parse script arguments""" 5 | 6 | import argparse 7 | import logging 8 | import sys 9 | 10 | 11 | def parse_sys_args(argv): 12 | """Parses commaond-line arguments""" 13 | parser = argparse.ArgumentParser( 14 | description="Gitlab backup tool in group level") 15 | parser.add_argument( 16 | "--local", action="store", dest="local", 17 | required=True, help="Local gitlab http url, " 18 | "ex: https://local.gitlab.com") 19 | parser.add_argument( 20 | "--local-token", action="store", dest="local_token", 21 | required=True, help="Local gitlab private token.") 22 | parser.add_argument( 23 | "--local-group", action="store", dest="local_group", 24 | required=False, help="Local github group for syncing, " 25 | "Leave this as blank when you want to sync all groups") 26 | parser.add_argument( 27 | "--remote", action="store", dest="remote", 28 | required=True, help="Remote gitlab http url, " 29 | "ex: https://remote.gitlab.com") 30 | parser.add_argument( 31 | "--remote-token", action="store", dest="remote_token", 32 | required=True, help="Remote gitlab private token") 33 | parser.add_argument( 34 | "--remote-group", action="store", dest="remote_group", 35 | required=False, help="Target group of remote github for backup, " 36 | "Leave this as blank if you want to keep the " 37 | "same name as remote") 38 | parser.add_argument( 39 | "--remote-parent-group", action="store", dest="remote_parent_group", 40 | required=False, help="Parent group to save all local groups") 41 | parser.add_argument( 42 | "--push-url", action="store", dest="push_url", 43 | required=True, help="Remote push url for backup target") 44 | parser.add_argument( 45 | "--force-push", action="store_true", 46 | dest="force_push", default=True, 47 | required=False, help="Force push to remote by default") 48 | parser.add_argument( 49 | "--ignore-branches", action="store", dest="ignore_branches", 50 | required=False, help="Not sync for ignore branches, " 51 | "ex: cherry-pick,dev,temp") 52 | parser.add_argument( 53 | "--allow-branches", action="store", dest="allow_branches", 54 | required=False, help="Only sync for allow branches, " 55 | "ex: master,main,qa. " 56 | "if not given, sync all branches. " 57 | "If ignore branches is given, the" 58 | "priority is higher than this argument") 59 | parser.add_argument( 60 | "-d", "--debug", action="store_true", dest="debug", 61 | default=False, help="Enable debug message.") 62 | parser.add_argument( 63 | "-v", "--verbose", action="store_true", dest="verbose", 64 | default=True, help="Show message in standard output.") 65 | 66 | if len(sys.argv) == 1: 67 | parser.print_help(sys.stderr) 68 | sys.exit(1) 69 | else: 70 | return parser.parse_args(argv[1:]) 71 | -------------------------------------------------------------------------------- /src/common/init_logging.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import logging 4 | import os 5 | import sys 6 | 7 | DEFAULT_PATH = "logs" 8 | 9 | LOG_FORMAT = "%(asctime)s %(process)s %(levelname)s [-] %(message)s" 10 | 11 | def init_logging(debug=False, verbose=True, 12 | log_file=None, log_path=None): 13 | """Initilize logging for common usage 14 | 15 | By default, log will save at logs dir under current running path. 16 | """ 17 | 18 | logger = logging.getLogger() 19 | log_level = logging.DEBUG if debug else logging.INFO 20 | logger.setLevel(log_level) 21 | 22 | # Set console handler 23 | if verbose: 24 | console = logging.StreamHandler() 25 | console.setLevel(log_level) 26 | console.setFormatter(logging.Formatter(fmt=LOG_FORMAT)) 27 | logger.addHandler(console) 28 | else: 29 | logger.disabled = True 30 | 31 | if log_file: 32 | if not log_path: 33 | log_path = DEFAULT_PATH 34 | 35 | if not os.path.exists(log_path): 36 | os.makedirs(log_path) 37 | 38 | log_path = os.path.join(log_path, log_file) 39 | 40 | fileout = logging.FileHandler(log_path, "a") 41 | fileout.setLevel(log_level) 42 | fileout.setFormatter(logging.Formatter(fmt=LOG_FORMAT)) 43 | logger.addHandler(fileout) 44 | -------------------------------------------------------------------------------- /src/gitlab-sync: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | """This script is used to sync gitlab group to another gitlab""" 4 | 5 | import logging 6 | import os 7 | import sys 8 | 9 | import git 10 | import tempfile 11 | 12 | from common.init_argparse import parse_sys_args 13 | from common.init_logging import init_logging 14 | from common.git_repo import GitRepo 15 | from common.gitlab_wrapper import GitlabWrapper 16 | 17 | 18 | def sync(args): 19 | local_group = args.local_group 20 | local_gl = GitlabWrapper(args.local, args.local_token) 21 | 22 | remote_group = args.remote_group 23 | remote_gl = GitlabWrapper(args.remote, args.remote_token) 24 | 25 | # force push 26 | force_push = args.force_push 27 | push_url = args.push_url 28 | 29 | # Get branches arguments 30 | ignore_branches = [] 31 | if args.ignore_branches: 32 | ignore_branches = args.ignore_branches.split(",") 33 | 34 | allow_branches = [] 35 | if args.allow_branches: 36 | allow_branches = args.allow_branches.split(",") 37 | 38 | # NOTE(Ray): Support multiple groups sync, you can specify different sync 39 | # group target, but need to keep the same numbers in remote group, or just 40 | # leave as blank, we will use the same name as the local group name 41 | # UPDATE(2023-04-03): We will sync all local groups to remote if local group 42 | # is empty 43 | if local_group: 44 | local_groups = local_group.split(",") 45 | else: 46 | local_groups = [g.full_path for g in local_gl.groups] 47 | 48 | if not remote_group: 49 | remote_groups = local_groups 50 | else: 51 | remote_groups = remote_group.split(",") 52 | 53 | if not len(remote_groups) == len(local_groups): 54 | raise Exception("Not enough remote groups given, " 55 | "local groups: %s, remote_groups: %s" % ( 56 | local_groups, remote_groups)) 57 | 58 | for index, lg in enumerate(local_groups): 59 | logging.debug("Working on local grooup %s..." % lg) 60 | 61 | rg = remote_groups[index] 62 | 63 | if not local_gl.is_group_exists(lg): 64 | raise Exception( 65 | "Can not find local group name %s, " 66 | "avaliabe group names are: %s" % ( 67 | lg, local_gl.group_names())) 68 | 69 | local_projects = local_gl.group_projects(lg) 70 | 71 | # NOTE(Ray): Add parent group for syncing, all remote groups will be saved 72 | # into this namespace 73 | parent_group = args.remote_parent_group 74 | 75 | _sync_group_projects(local_projects, 76 | remote_gl, 77 | rg, 78 | push_url, 79 | ignore_branches, 80 | allow_branches, 81 | force_push, 82 | parent_group) 83 | 84 | 85 | def _sync_group_projects(local_projects, 86 | remote_gl, 87 | remote_group, 88 | push_url, 89 | ignore_branches, 90 | allow_branches, 91 | force_push, 92 | parent_group=None): 93 | with tempfile.TemporaryDirectory() as tmpdirname: 94 | # Get all local projects in group, pull code from 95 | # all branches, then push to remote 96 | for p in local_projects: 97 | logging.debug("Local project info: %s" % p) 98 | project_path = p.path 99 | git_url = p.ssh_url_to_repo 100 | local_namespace = p.namespace["full_path"] 101 | remote_namespace = _get_remote_namespace( 102 | local_namespace, remote_group, parent_group) 103 | remote_url = os.path.join( 104 | push_url, remote_namespace, project_path) 105 | src_path = os.path.join( 106 | tmpdirname, local_namespace, project_path) 107 | 108 | if not os.path.exists(src_path): 109 | os.makedirs(src_path) 110 | 111 | # Download specific repo with all branches 112 | logging.info("Run git clone %s to %s" % ( 113 | git_url, src_path)) 114 | local_repo = GitRepo(git_url, src_path) 115 | local_repo.clone() 116 | for branch in local_repo.branches: 117 | if not _is_sync_branch(ignore_branches, 118 | allow_branches, 119 | branch): 120 | logging.info("Found ignore branch %s, skip to pull" % branch) 121 | continue 122 | if not branch == local_repo.current_branch: 123 | logging.info("Pulling branch %s..." % branch) 124 | local_repo.pull_branch(branch) 125 | 126 | # Make sure groups and projects are created in remote gitlab 127 | remote_gl.ensure_project_exists( 128 | remote_namespace, project_path) 129 | 130 | # Push all branches and tags to remote 131 | logging.info("Run git push to %s..." % remote_url) 132 | remote_repo = GitRepo(remote_url, src_path) 133 | remote_repo.push_all_branches(force=force_push) 134 | remote_repo.push_all_tags(force=force_push) 135 | 136 | 137 | def _is_sync_branch(ignore_branches, allow_branches, branch_name): 138 | """Return True if branch need to be sync 139 | 140 | Ignore branch priority is higher than allow branch, loop all ignore 141 | branch first than find allow branches 142 | """ 143 | for ib in ignore_branches: 144 | if ib in branch_name: 145 | return True 146 | 147 | # if allow branches is empty, by default, we will sync all branches 148 | if allow_branches: 149 | for ab in allow_branches: 150 | if ab in branch_name: 151 | return True 152 | 153 | # Return false if we can't find name in allow branches 154 | return False 155 | else: 156 | return True 157 | 158 | 159 | def _get_remote_namespace(local_namespace, remote_group, parent_group=None): 160 | """Replace the first group name with remote group""" 161 | namespaces = local_namespace.split("/") 162 | namespaces[0] = remote_group 163 | 164 | # Add parent group before sycing if remote-parent-group is given 165 | if parent_group: 166 | namespaces.insert(0, parent_group) 167 | 168 | return "/".join(namespaces) 169 | 170 | 171 | def main(): 172 | args = parse_sys_args(sys.argv) 173 | init_logging(verbose=args.verbose, debug=args.debug) 174 | 175 | sync(args) 176 | 177 | 178 | if __name__ == "__main__": 179 | main() 180 | --------------------------------------------------------------------------------