|
| 1 | +#!/usr/bin/env python3 |
| 2 | +import os |
| 3 | +import re |
| 4 | +import requests |
| 5 | +import posixpath |
| 6 | +import argparse |
| 7 | +from git import Repo |
| 8 | + |
| 9 | +parser = argparse.ArgumentParser('gitlab-clone-group.py') |
| 10 | +parser.add_argument('group_id', help='id of group to clone (including subgroups)') |
| 11 | +parser.add_argument('directory', help='directory to clone repos into') |
| 12 | +parser.add_argument('--token', help='Gitlab private access token with read_api and read_repository rights') |
| 13 | +parser.add_argument('--gitlab-domain', help='Domain of Gitlab instance to use, defaults to: gitlab.com', default='gitlab.com') |
| 14 | + |
| 15 | +args = parser.parse_args() |
| 16 | + |
| 17 | +api_url = 'https://' + posixpath.join(args.gitlab_domain, 'api/v4/groups/', args.group_id, 'projects') + '?per_page=9999&page=1&include_subgroups=true' |
| 18 | + |
| 19 | +headers = {'PRIVATE-TOKEN': args.token} |
| 20 | +res = requests.get(api_url, headers=headers) |
| 21 | +projects = res.json() |
| 22 | + |
| 23 | +base_ns = os.path.commonprefix([p['namespace']['full_path'] for p in projects]) |
| 24 | +print('Found %d projects in: %s' % (len(projects), base_ns)) |
| 25 | + |
| 26 | +abs_dir = os.path.abspath(args.directory) |
| 27 | +os.makedirs(abs_dir,exist_ok=True) |
| 28 | + |
| 29 | +def get_rel_path(path): |
| 30 | + subpath = path[len(base_ns):] |
| 31 | + if (subpath.startswith('/')): |
| 32 | + subpath = subpath[1:] |
| 33 | + return posixpath.join(args.directory, subpath) |
| 34 | + |
| 35 | +for p in projects: |
| 36 | + clone_dir = get_rel_path(p['namespace']['full_path']) |
| 37 | + project_path = get_rel_path(p['path_with_namespace']) |
| 38 | + print('Cloning project: %s' % project_path) |
| 39 | + if os.path.exists(project_path): |
| 40 | + print("\tProject folder already exists, skipping") |
| 41 | + else: |
| 42 | + print("\tGit url: %s" % p['ssh_url_to_repo']) |
| 43 | + os.makedirs(clone_dir, exist_ok=True) |
| 44 | + Repo.clone_from(p['ssh_url_to_repo'], project_path) |
| 45 | + |
0 commit comments