summaryrefslogtreecommitdiff
path: root/scripts/gitea.py
blob: 7c63e07b477b35da19d0ca3036237eac8a363be5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import os
import sys
import requests

from github import Github
from github import Auth

def read_token(var: str) -> str:
    path = os.getenv(var)
    if path is None:
        print(f"Missing env var: {var}", file=sys.stderr)
        sys.exit(1)
    return open(path).read().strip()

GITHUB_TOKEN: str = read_token("GITHUB_TOKEN_FILE")
GITHUB_USERNAME = "Kyren223"
GITEA_URL = "https://git.kyren.codes"
GITEA_TOKEN: str = read_token("GITEA_TOKEN_FILE")
GITEA_USER = "Kyren223"

success = 0
skipped = 0
failed = 0

def repo_exists(repo_name: str) -> bool:
    headers = {'Authorization': f'token {GITEA_TOKEN}'}
    r = requests.get(f'{GITEA_URL}/api/v1/repos/{GITEA_USER}/{repo_name}', headers=headers)
    return r.status_code == 200

def mirror(addr: str, repo_name: str):
    if repo_exists(repo_name):
        print(f"Skipping existing repo: {repo_name}")
        global skipped; skipped += 1
        return

    json = {
        'auth_token': GITHUB_TOKEN or '',
        'auth_username': GITHUB_USERNAME or '',
        'clone_addr': addr,
        'issues': True,
        'milestones': True,
        'mirror': True,
        'private': True,
        'pull_requests': True,
        'releases': True,
        'repo_name': repo_name,
        'repo_owner': GITEA_USER or '',
        'service': 'git',
        'uid': 0,
        'wiki': True
    }

    payload = { 'access_token': GITEA_TOKEN or '' }

    try:
        r = requests.post(f'{GITEA_URL}/api/v1/repos/migrate',
                      json=json, params=payload)
        r.raise_for_status()

        global success; success += 1
        print(f'Mirrored {repo_name}')
    except requests.exceptions.HTTPError as e:
        global failed; failed += 1
        print(f"Failed to mirror {repo_name}: {e}")

# using an access token
auth = Auth.Token(GITHUB_TOKEN or '')

# First create a Github instance:

# Public Web Github
g = Github(auth=auth)

# Then play with your Github objects:
for repo in g.get_user().get_repos():
    mirror(repo.clone_url, repo.name)

# To close connections after use
g.close()

print(f"\nSummary: {success} mirrored, {skipped} skipped, {failed} failed.")