Skip to content

Instantly share code, notes, and snippets.

@sjoerd-dijkstra
Last active August 22, 2019 07:34
Show Gist options
  • Save sjoerd-dijkstra/a30e2087c162bcdda8a2fc4996d85b96 to your computer and use it in GitHub Desktop.
Save sjoerd-dijkstra/a30e2087c162bcdda8a2fc4996d85b96 to your computer and use it in GitHub Desktop.
Script to automatically clone gitlab projects. It will create a folder structure in --dir similar to the group tree in gitlab.
import argparse
import gitlab
import os
import subprocess
import getpass
# parse args
parser = argparse.ArgumentParser(description='Gitlab Clone Tree 🌲')
parser.add_argument('-U', '--url', required=False, default='https://gitlab.com/', help='gitlab url')
parser.add_argument('-P', '--prefix', required=True, help='ssh gitlab prefix')
parser.add_argument('-D', '--dir', required=True, help='target directory')
args = parser.parse_args()
# prompt secret
private_token = getpass.getpass('\nGitlab token?> ')
# init gitlab api
gl = gitlab.Gitlab(args.url, private_token=private_token)
# get projects
projects = gl.projects.list(owned=True, all=True)
# loop projects
for project in projects:
if project.ssh_url_to_repo.startswith(args.prefix):
# remote origin
ssh_url_to_repo = project.ssh_url_to_repo
# compose path
tokens = ssh_url_to_repo.split('/')
project_directory = '{}/{}'.format(args.dir, '/'.join(tokens[1:])[:-4])
# clone repository
if not os.path.exists(project_directory):
os.makedirs(project_directory, exist_ok=True)
subprocess.call(['git', 'clone', '--recursive', ssh_url_to_repo, project_directory])
@miguelaferreira
Copy link

$ python gitlab_clone.py ...
gitlab_clone.py: error: argument -D/--dir is required

@sjoerd-dijkstra
Copy link
Author

Thanks @miguelaferreira, have updated the instructions

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment