dump-github 0.1.7__py3-none-any.whl → 0.1.8__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
dump_github/__init__.py CHANGED
@@ -1,2 +1,2 @@
1
- # from .lib import *
1
+ # from .lib import *
2
2
  from .main import main
dump_github/lib.py CHANGED
@@ -1,31 +1,63 @@
1
- import requests
2
-
3
-
4
- def get_page_of_repos(username, page, token=""):
5
- url = "https://api.github.com/users/{}/repos?per_page=200&page={}".format(
6
- username, page
7
- )
8
- headers = {"Authorization": token}
9
- if token != "":
10
- response = requests.get(url, headers=headers)
11
- else:
12
- response = requests.get(url)
13
- if response.status_code == 200:
14
- repos = response.json()
15
- return repos
16
- else:
17
- return []
18
-
19
-
20
- def serach_user_repos(username, token=""):
21
- page = 0
22
- res_repos = []
23
-
24
- while True:
25
- page += 1
26
- repos = get_page_of_repos(username, page, token)
27
- if len(repos) == 0:
28
- break
29
- res_repos += repos
30
-
31
- return res_repos
1
+ import requests
2
+
3
+
4
+ def _github_auth_headers(token):
5
+ """GitHub REST API expects Authorization: Bearer <token> (PAT classic / fine-grained)."""
6
+ if not token:
7
+ return {}
8
+ token = token.strip()
9
+ if not token:
10
+ return {}
11
+ if token.lower().startswith(("bearer ", "token ", "basic ")):
12
+ return {"Authorization": token}
13
+ return {"Authorization": "Bearer {}".format(token)}
14
+
15
+
16
+ def get_page_of_repos(username, page, token=""):
17
+ token_header = _github_auth_headers(token)
18
+
19
+ if token_header:
20
+ url = "https://api.github.com/user/repos?per_page=100&page={}".format(page)
21
+ headers = {
22
+ "Accept": "application/vnd.github+json",
23
+ "X-GitHub-Api-Version": "2022-11-28",
24
+ }
25
+ headers.update(token_header)
26
+ response = requests.get(url, headers=headers)
27
+ if response.status_code == 200:
28
+ repos = response.json()
29
+ return repos
30
+ else:
31
+ return []
32
+ else:
33
+ url = "https://api.github.com/users/{}/repos?per_page=100&page={}".format(
34
+ username, page
35
+ )
36
+ headers = {
37
+ "Accept": "application/vnd.github+json",
38
+ "X-GitHub-Api-Version": "2022-11-28",
39
+ }
40
+ response = requests.get(url, headers=headers)
41
+ if response.status_code == 200:
42
+ repos = response.json()
43
+ return repos
44
+ else:
45
+ return []
46
+
47
+
48
+ def search_user_repos(username, token=""):
49
+ page = 0
50
+ res_repos = []
51
+
52
+ while True:
53
+ page += 1
54
+ repos = get_page_of_repos(username, page, token)
55
+ if len(repos) == 0:
56
+ break
57
+ res_repos += repos
58
+
59
+ return res_repos
60
+
61
+
62
+ # Backward-compatible alias for the historical typo
63
+ serach_user_repos = search_user_repos
dump_github/main.py CHANGED
@@ -1,62 +1,109 @@
1
- import argparse
2
- import os
3
- from .lib import *
4
-
5
- parser = argparse.ArgumentParser(
6
- prog="dump-github",
7
- description="Backup users github repo.",
8
- epilog="https://github.com/Core2002/dump_github",
9
- )
10
-
11
- parser.add_argument("username")
12
- parser.add_argument(
13
- "-d", "--download_zip", action="store_true", help="only download zip file"
14
- )
15
- parser.add_argument("-p", "--print", action="store_true", help="only print urls")
16
- parser.add_argument("--token", action="store", default="", help="github token")
17
- parser.add_argument(
18
- "--limit_size",
19
- type=int,
20
- default=100,
21
- help="limit size(MB) of download zip file, if 0 then no limit(default:100).",
22
- )
23
-
24
- args = parser.parse_args()
25
-
26
-
27
- def clone_repo(repo):
28
- name = repo["name"]
29
- url = repo["clone_url"]
30
- size = repo["size"]
31
- print("Clone repo: {}".format(name))
32
- os.system("git clone {}".format(url))
33
-
34
-
35
- def download_zip(user_name, reop):
36
- url = f"https://github.com/{user_name}/{reop['name']}/archive/refs/heads/{reop['default_branch']}.zip"
37
- max_size = args.limit_size * 1000 * 1000
38
- file_name = f"./{user_name}_{reop['name']}.zip"
39
- cmd = "curl -L --connect-timeout 5 --retry 3 --retry-delay 3 --max-filesize {} {} -o {}".format(
40
- max_size, url, file_name
41
- )
42
- print(f"Download {reop['name']} : {url}")
43
- os.system(cmd)
44
- if os.path.exists(file_name) and max_size < os.stat(file_name).st_size:
45
- os.remove(file_name)
46
- print(f"Removed {file_name} because it exceeds the limit size.")
47
-
48
-
49
- def main():
50
- # print(args)
51
- repos = serach_user_repos(args.username, args.token)
52
- for repo in repos:
53
- if args.print == True:
54
- print(repo["clone_url"])
55
- elif args.download_zip == True:
56
- download_zip(args.username, repo)
57
- else:
58
- clone_repo(repo)
59
-
60
-
61
- if __name__ == "__main__":
62
- main()
1
+ import argparse
2
+ import os
3
+ import subprocess
4
+ from urllib.parse import quote
5
+
6
+ from .lib import search_user_repos
7
+
8
+ parser = argparse.ArgumentParser(
9
+ prog="dump-github",
10
+ description="Backup users github repo.",
11
+ epilog="https://github.com/Core2002/dump_github",
12
+ )
13
+
14
+ parser.add_argument("username")
15
+ parser.add_argument(
16
+ "-d", "--download_zip", action="store_true", help="only download zip file"
17
+ )
18
+ parser.add_argument("-p", "--print", action="store_true", help="only print urls")
19
+ parser.add_argument(
20
+ "--token",
21
+ action="store",
22
+ default="",
23
+ help="GitHub personal access token (or set GITHUB_TOKEN). Required for private repos and higher API rate limits.",
24
+ )
25
+ parser.add_argument(
26
+ "--limit_size",
27
+ type=int,
28
+ default=100,
29
+ help="limit size(MB) of download zip file, if 0 then no limit(default:100).",
30
+ )
31
+
32
+ args = parser.parse_args()
33
+
34
+
35
+ def clone_repo(repo, token=""):
36
+ name = repo["name"]
37
+ url = repo["clone_url"]
38
+ if token:
39
+ url = url.replace(
40
+ "https://",
41
+ "https://x-access-token:{}@".format(quote(token, safe="")),
42
+ 1,
43
+ )
44
+ print("Clone repo: {}".format(name))
45
+ subprocess.run(["git", "clone", url], check=False)
46
+
47
+
48
+ def download_zip(user_name, reop, token=""):
49
+ ref = reop.get("default_branch") or "main"
50
+ max_size = args.limit_size * 1000 * 1000
51
+ file_name = "./{}_{}.zip".format(user_name, reop["name"])
52
+ curl_cmd = [
53
+ "curl",
54
+ "-sS",
55
+ "-L",
56
+ "--connect-timeout",
57
+ "5",
58
+ "--retry",
59
+ "3",
60
+ "--retry-delay",
61
+ "3",
62
+ ]
63
+ if max_size > 0:
64
+ curl_cmd.extend(["--max-filesize", str(max_size)])
65
+ if token:
66
+ url = "https://api.github.com/repos/{}/{}/zipball/{}".format(
67
+ user_name, reop["name"], ref
68
+ )
69
+ curl_cmd.extend(
70
+ [
71
+ "-H",
72
+ "Authorization: Bearer {}".format(token),
73
+ "-H",
74
+ "Accept: application/vnd.github+json",
75
+ "-o",
76
+ file_name,
77
+ url,
78
+ ]
79
+ )
80
+ else:
81
+ url = "https://github.com/{}/{}/archive/refs/heads/{}.zip".format(
82
+ user_name, reop["name"], ref
83
+ )
84
+ curl_cmd.extend(["-o", file_name, url])
85
+ print("Download {} : {}".format(reop["name"], url))
86
+ subprocess.run(curl_cmd, check=False)
87
+ if (
88
+ max_size > 0
89
+ and os.path.exists(file_name)
90
+ and os.stat(file_name).st_size > max_size
91
+ ):
92
+ os.remove(file_name)
93
+ print("Removed {} because it exceeds the limit size.".format(file_name))
94
+
95
+
96
+ def main():
97
+ token = (args.token or "").strip() or (os.environ.get("GITHUB_TOKEN") or "").strip()
98
+ repos = search_user_repos(args.username, token)
99
+ for repo in repos:
100
+ if args.print == True:
101
+ print(repo["clone_url"])
102
+ elif args.download_zip == True:
103
+ download_zip(args.username, repo, token)
104
+ else:
105
+ clone_repo(repo, token)
106
+
107
+
108
+ if __name__ == "__main__":
109
+ main()
@@ -0,0 +1,92 @@
1
+ Metadata-Version: 2.4
2
+ Name: dump_github
3
+ Version: 0.1.8
4
+ Summary: This tool can be used to back up users' GitHub repositories in case they need them later.
5
+ Home-page: https://github.com/core2002/dump_github
6
+ Author: core2002
7
+ Author-email: core2002@aliyun.com
8
+ License: MIT
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Operating System :: OS Independent
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: argparse
15
+ Requires-Dist: requests
16
+ Dynamic: author
17
+ Dynamic: author-email
18
+ Dynamic: classifier
19
+ Dynamic: description
20
+ Dynamic: description-content-type
21
+ Dynamic: home-page
22
+ Dynamic: license
23
+ Dynamic: license-file
24
+ Dynamic: requires-dist
25
+ Dynamic: summary
26
+
27
+ ### Github Dumper
28
+
29
+ Github Dumper is a Python program designed to search for users' GitHub repositories and download the repositories. This tool can be used to back up users' GitHub repositories in case they need them later.
30
+
31
+ **Install:**
32
+
33
+ ```
34
+ pip install -U dump-github
35
+ ```
36
+
37
+ **Usage:**
38
+
39
+ ```
40
+ usage: dump-github [-h] [-d] [-p] [--token TOKEN] [--limit_size LIMIT_SIZE] username
41
+
42
+ Backup users github repo.
43
+
44
+ positional arguments:
45
+ username
46
+
47
+ options:
48
+ -h, --help show this help message and exit
49
+ -d, --download_zip only download zip file
50
+ -p, --print only print urls
51
+ --token TOKEN GitHub personal access token (or set GITHUB_TOKEN)
52
+ --limit_size LIMIT_SIZE
53
+ limit size(MB) of download zip file, if 0 then no limit(default:100).
54
+
55
+ https://github.com/Core2002/dump_github
56
+ ```
57
+
58
+ ### Authentication (token)
59
+
60
+ GitHub’s API requires a proper `Authorization: Bearer <token>` header. This tool accepts a **personal access token** in two ways (first match wins):
61
+
62
+ 1. **`--token`** on the command line
63
+ 2. **`GITHUB_TOKEN`** environment variable (if `--token` is empty)
64
+
65
+ **Why use a token?**
66
+
67
+ - **Private repositories**: Without a token, only public repos are listed and can be cloned or archived. With a token that has the right scopes, you can include private repos you are allowed to access (for example when backing up your own account).
68
+ - **Rate limits**: Authenticated API requests get a much higher limit than anonymous requests.
69
+
70
+ **How the token is used**
71
+
72
+ - **Listing repos** (`GET /users/{username}/repos`): sent as `Bearer` on the REST API.
73
+ - **Clone** (default mode): HTTPS clone URL is turned into `https://x-access-token:<token>@github.com/...` so `git clone` can access private repos.
74
+ - **Zip download** (`-d`): uses the [repository archive (zipball)](https://docs.github.com/en/rest/repos/repos#download-a-repository-archive-zip) API with the same `Bearer` header (via `curl`), which works for private repos; without a token, public archive URLs are used instead.
75
+
76
+ Create a token under GitHub → **Settings** → **Developer settings** → **Personal access tokens**. For private repo backup, enable access to **repository contents** (classic PAT: `repo` scope; fine-grained: read access to the repositories you need).
77
+
78
+ **Examples**
79
+
80
+ ```bash
81
+ # Public repos only (no token)
82
+ dump-github Core2002 -p
83
+
84
+ # Token on the command line (private + higher API limits)
85
+ dump-github username --token ghp_xxxxxxxxxxxx
86
+
87
+ # Same, via environment variable (recommended to avoid shell history)
88
+ export GITHUB_TOKEN=ghp_xxxxxxxxxxxx
89
+ dump-github Core2002 -d
90
+ ```
91
+
92
+ **Security note:** Do not commit tokens or paste them into shared logs. Prefer `GITHUB_TOKEN` in a local shell profile or a secret manager, and rotate the token if it leaks.
@@ -0,0 +1,9 @@
1
+ dump_github/__init__.py,sha256=5dzWctgs4c0g7raC2Kzas3wck0zHvXifUnSxy-dCPjg,44
2
+ dump_github/lib.py,sha256=vEpwlJBrRr-g34spJPZmhRC9bdElngaaHCCxCQ86M1A,1843
3
+ dump_github/main.py,sha256=H8QADAbNNbs_zIx5Hk6MzAFLgFfMA7bT06fqRpuyInQ,3150
4
+ dump_github-0.1.8.dist-info/licenses/LICENSE,sha256=ac2hzJN6sGcBrmJXe7CkvzfaYdM5sEo8Ny1BWHML1yk,1084
5
+ dump_github-0.1.8.dist-info/METADATA,sha256=h8x2qKi_OzFpSSunyfHGpSolUrKJGJJZl-YkWDzgfUY,3606
6
+ dump_github-0.1.8.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
7
+ dump_github-0.1.8.dist-info/entry_points.txt,sha256=2OAP2WnA1p54LWyCw3tHe44Pf4aR7Thsxf9uWKWfWl8,49
8
+ dump_github-0.1.8.dist-info/top_level.txt,sha256=6oWfdkP2U1AN9zL6AUIUTxe6hYIeo_Nf8M8SWBxElUw,12
9
+ dump_github-0.1.8.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: bdist_wheel (0.43.0)
2
+ Generator: setuptools (82.0.1)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2024 Core2002
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Core2002
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
21
  SOFTWARE.
dump_github/mylib.py DELETED
@@ -1,31 +0,0 @@
1
- import requests
2
-
3
-
4
- def get_page_of_repos(username, page, token=""):
5
- url = "https://api.github.com/users/{}/repos?per_page=200&page={}".format(
6
- username, page
7
- )
8
- headers = {"Authorization": token}
9
- if token != "":
10
- response = requests.get(url, headers=headers)
11
- else:
12
- response = requests.get(url)
13
- if response.status_code == 200:
14
- repos = response.json()
15
- return repos
16
- else:
17
- raise []
18
-
19
-
20
- def serach_user_repos(username, token=""):
21
- page = 0
22
- res_repos = []
23
-
24
- while True:
25
- page += 1
26
- repos = get_page_of_repos(username, page, token)
27
- if len(repos) == 0:
28
- break
29
- res_repos += repos
30
-
31
- return res_repos
@@ -1,44 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: dump-github
3
- Version: 0.1.7
4
- Summary: This tool can be used to back up users' GitHub repositories in case they need them later.
5
- Home-page: https://github.com/core2002/dump_github
6
- Author: core2002
7
- Author-email: core2002@aliyun.com
8
- License: MIT
9
- Classifier: Programming Language :: Python :: 3
10
- Classifier: License :: OSI Approved :: MIT License
11
- Classifier: Operating System :: OS Independent
12
- Description-Content-Type: text/markdown
13
- License-File: LICENSE
14
- Requires-Dist: argparse
15
- Requires-Dist: requests
16
-
17
- ### Github Dumper
18
-
19
- Github Dumper is a Python program designed to search for users' GitHub repositories and download the repositories. This tool can be used to back up users' GitHub repositories in case they need them later.
20
-
21
- **Install:**
22
- ```
23
- pip install -U dump-github
24
- ```
25
-
26
- **Usage:**
27
- ```
28
- usage: dump-github [-h] [-d] [-p] [--token TOKEN] [--limit_size LIMIT_SIZE] username
29
-
30
- Backup users github repo.
31
-
32
- positional arguments:
33
- username
34
-
35
- options:
36
- -h, --help show this help message and exit
37
- -d, --download_zip only download zip file
38
- -p, --print only print urls
39
- --token TOKEN github token
40
- --limit_size LIMIT_SIZE
41
- limit size(MB) of download zip file, if 0 then no limit(default:100).
42
-
43
- https://github.com/Core2002/dump_github
44
- ```
@@ -1,10 +0,0 @@
1
- dump_github/__init__.py,sha256=3XLRrchVn7g3TYWiQpv3u2lKdTO-jDqg4_0-lpmRuRs,43
2
- dump_github/lib.py,sha256=hE8ZXBB2BKHlPld0ufUgRaAr2hGouLeQ7jdZuqXX6Q8,716
3
- dump_github/main.py,sha256=uTPdcVwg0mkmOAGJXpVeBn3m3f7SyNOracyqAnR-KuA,1842
4
- dump_github/mylib.py,sha256=pHONzAjGbXkmAUvCGn8HkHWS7fyY2qu9R17to6jD1TU,715
5
- dump_github-0.1.7.dist-info/LICENSE,sha256=5tQa-lQLqvLhjTuELEk4bm70I5hcdjUeOn4qf3MK84E,1064
6
- dump_github-0.1.7.dist-info/METADATA,sha256=ZwZtZYP6H4p0NrK0La9C7lOeB4frgC2i3lwLPLH2D-Q,1316
7
- dump_github-0.1.7.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
8
- dump_github-0.1.7.dist-info/entry_points.txt,sha256=2OAP2WnA1p54LWyCw3tHe44Pf4aR7Thsxf9uWKWfWl8,49
9
- dump_github-0.1.7.dist-info/top_level.txt,sha256=6oWfdkP2U1AN9zL6AUIUTxe6hYIeo_Nf8M8SWBxElUw,12
10
- dump_github-0.1.7.dist-info/RECORD,,