Добавить обзор решений Aurora и скрипты сбора снимков
This commit is contained in:
185
scripts/export_gitlab_repos.py
Normal file
185
scripts/export_gitlab_repos.py
Normal file
@@ -0,0 +1,185 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Download repository ZIP snapshots through the GitLab API."""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from urllib.parse import unquote, urlsplit
|
||||
from zipfile import BadZipFile, ZipFile
|
||||
|
||||
import gitlab
|
||||
from gitlab.exceptions import GitlabAuthenticationError, GitlabError
|
||||
from requests.exceptions import RequestException
|
||||
|
||||
|
||||
DEFAULT_OUTPUT = Path(__file__).resolve().parents[1] / "gitlab_exports"
|
||||
PATH_COMPONENT = re.compile(r"[A-Za-z0-9_][A-Za-z0-9_.-]*")
|
||||
|
||||
|
||||
def https_origin(url):
|
||||
if url.scheme != "https" or not url.hostname or url.username is not None:
|
||||
raise ValueError("use an HTTPS URL without embedded credentials")
|
||||
return url.hostname, url.port or 443
|
||||
|
||||
|
||||
def resource_id(value, base_url, *, group=False):
|
||||
if value.isascii() and value.isdecimal():
|
||||
return int(value)
|
||||
url = urlsplit(value)
|
||||
path = unquote(url.path).strip("/")
|
||||
if url.scheme or url.netloc:
|
||||
if https_origin(url) != https_origin(base_url):
|
||||
raise ValueError("the URL must belong to GITLAB_URL")
|
||||
base_path = unquote(base_url.path).strip("/")
|
||||
if base_path:
|
||||
if not path.startswith(base_path + "/"):
|
||||
raise ValueError("the URL must be under the path in GITLAB_URL")
|
||||
path = path[len(base_path) + 1 :]
|
||||
if group:
|
||||
path = path.removeprefix("groups/")
|
||||
path = path.split("/-/", 1)[0].removesuffix("/-")
|
||||
if not group:
|
||||
path = path.removesuffix(".git")
|
||||
parts = path.split("/")
|
||||
if (not group and len(parts) < 2) or not all(
|
||||
PATH_COMPONENT.fullmatch(part) for part in parts
|
||||
):
|
||||
raise ValueError("use a GitLab URL, namespace path, or numeric ID")
|
||||
return path
|
||||
|
||||
|
||||
def parse_args():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
source = parser.add_mutually_exclusive_group(required=True)
|
||||
source.add_argument("--group", help="Group URL, namespace path, or numeric ID")
|
||||
source.add_argument("--project", action="append", help="Project URL, path, or ID; repeatable")
|
||||
source.add_argument("--projects-file", type=Path, help="One project URL, path, or ID per line")
|
||||
parser.add_argument("--include-subgroups", action="store_true", help="Include nested groups")
|
||||
parser.add_argument("--list", action="store_true", help="List projects without downloading")
|
||||
parser.add_argument("--ref", help="Branch, tag, or commit SHA; defaults to each default branch")
|
||||
parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT, help="Parent for run directories")
|
||||
args = parser.parse_args()
|
||||
if args.include_subgroups and args.group is None:
|
||||
parser.error("--include-subgroups requires --group")
|
||||
|
||||
server = os.environ.get("GITLAB_URL", "").strip().rstrip("/")
|
||||
token = os.environ.get("GITLAB_TOKEN", "").strip()
|
||||
if not server or not token:
|
||||
parser.error("set GITLAB_URL and GITLAB_TOKEN")
|
||||
try:
|
||||
base_url = urlsplit(server)
|
||||
https_origin(base_url)
|
||||
if base_url.query or base_url.fragment:
|
||||
raise ValueError("GITLAB_URL must be the instance base URL")
|
||||
if args.group is not None:
|
||||
selection = resource_id(args.group, base_url, group=True)
|
||||
else:
|
||||
values = args.project
|
||||
if args.projects_file is not None:
|
||||
lines = args.projects_file.read_text(encoding="utf-8-sig").splitlines()
|
||||
values = [line.strip() for line in lines if line.strip() and not line.lstrip().startswith("#")]
|
||||
if not values:
|
||||
raise ValueError("the project list is empty")
|
||||
selection = list(dict.fromkeys(resource_id(value, base_url) for value in values))
|
||||
except (OSError, ValueError) as error:
|
||||
parser.error(str(error))
|
||||
return args, server, token, selection
|
||||
|
||||
|
||||
def download(project, output, ref):
|
||||
slug = re.sub(r"[^A-Za-z0-9_.-]+", "-", project.path_with_namespace)[:160]
|
||||
destination = output / f"{project.id}-{slug}.zip"
|
||||
partial = destination.with_suffix(".zip.part")
|
||||
try:
|
||||
with partial.open("xb") as file:
|
||||
project.repository_archive(
|
||||
sha=ref, format="zip", streamed=True, action=file.write, chunk_size=1024 * 1024
|
||||
)
|
||||
with ZipFile(partial) as archive:
|
||||
bad_member = archive.testzip()
|
||||
if bad_member is not None:
|
||||
raise ValueError("invalid ZIP member checksum")
|
||||
partial.replace(destination)
|
||||
finally:
|
||||
partial.unlink(missing_ok=True)
|
||||
return destination
|
||||
|
||||
|
||||
def report_error(target, error):
|
||||
status = getattr(error, "response_code", None)
|
||||
detail = f"HTTP {status}" if status else f"{type(error).__name__}: {error}"
|
||||
print(f"ERROR {target}: {detail}", file=sys.stderr)
|
||||
|
||||
|
||||
def run(client, args, selection):
|
||||
output = None
|
||||
completed = set()
|
||||
failed = 0
|
||||
|
||||
if args.group is not None:
|
||||
print(f"Loading group {selection}...", file=sys.stderr, flush=True)
|
||||
group = client.groups.get(selection)
|
||||
print("Loading project list...", file=sys.stderr, flush=True)
|
||||
candidates = (
|
||||
project.id for project in group.projects.list(
|
||||
iterator=True, include_subgroups=args.include_subgroups, with_shared=False
|
||||
)
|
||||
)
|
||||
else:
|
||||
candidates = iter(selection)
|
||||
|
||||
for candidate in candidates:
|
||||
try:
|
||||
print(f"Loading project {candidate}...", file=sys.stderr, flush=True)
|
||||
project = client.projects.get(candidate)
|
||||
if project.id in completed:
|
||||
continue
|
||||
if args.list:
|
||||
print(project.path_with_namespace)
|
||||
else:
|
||||
if output is None:
|
||||
args.output.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
output = Path(tempfile.mkdtemp(prefix="run-", dir=args.output))
|
||||
print(download(project, output, args.ref), flush=True)
|
||||
completed.add(project.id)
|
||||
except GitlabAuthenticationError:
|
||||
raise
|
||||
except (GitlabError, RequestException, OSError, BadZipFile, ValueError) as error:
|
||||
report_error(candidate, error)
|
||||
failed += 1
|
||||
print(f"{'Listed' if args.list else 'Saved'}: {len(completed)}; failed: {failed}")
|
||||
if not completed and not failed:
|
||||
print("No visible projects found.", file=sys.stderr)
|
||||
return int(bool(failed) or not completed)
|
||||
|
||||
|
||||
def main():
|
||||
args, server, token, selection = parse_args()
|
||||
ssl_verify = os.environ.get("GITLAB_SSL_VERIFY", "true").strip().lower() not in {
|
||||
"false", "0", "no", "off"
|
||||
}
|
||||
try:
|
||||
print(f"Connecting to GitLab at {server}...", file=sys.stderr, flush=True)
|
||||
if not ssl_verify:
|
||||
print("WARNING: TLS certificate verification is disabled.", file=sys.stderr, flush=True)
|
||||
with gitlab.Gitlab(
|
||||
server,
|
||||
private_token=token,
|
||||
ssl_verify=ssl_verify,
|
||||
timeout=120,
|
||||
retry_transient_errors=True,
|
||||
) as client:
|
||||
print("Authenticating...", file=sys.stderr, flush=True)
|
||||
client.auth()
|
||||
print("Authentication succeeded.", file=sys.stderr, flush=True)
|
||||
return run(client, args, selection)
|
||||
except (GitlabError, RequestException) as error:
|
||||
report_error("GitLab API", error)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user