github-backup 0.67.0__py3-none-any.whl → 0.69.0__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.
github_backup/__init__.py CHANGED
@@ -1 +1 @@
1
- __version__ = "0.67.0"
1
+ __version__ = "0.69.0"
@@ -5,13 +5,13 @@ from __future__ import print_function
5
5
  import argparse
6
6
  import base64
7
7
  import calendar
8
- import codecs
9
8
  import json
10
9
  import logging
11
10
  import os
12
11
  import platform
13
12
  import random
14
13
  import re
14
+ import shutil
15
15
  import socket
16
16
  import ssl
17
17
  import subprocess
@@ -41,10 +41,13 @@ from .graphql_queries import (
41
41
  DISCUSSION_PAGE_SIZE,
42
42
  DISCUSSION_REPLIES_QUERY,
43
43
  ISSUE_CROSS_REFERENCE_COUNT_QUERY,
44
+ PULL_COMMENTS_QUERY,
44
45
  PULL_CROSS_REFERENCE_COUNT_QUERY,
46
+ PULL_PAGE_SIZE,
45
47
  )
46
48
 
47
49
  FILE_URI_PREFIX = "file://"
50
+ APP_TOKEN_REFRESH_MARGIN = 10 * 60 # seconds
48
51
  logger = logging.getLogger(__name__)
49
52
 
50
53
 
@@ -195,6 +198,21 @@ def parse_args(args=None):
195
198
  dest="as_app",
196
199
  help="authenticate as github app instead of as a user.",
197
200
  )
201
+ parser.add_argument(
202
+ "--app-id",
203
+ dest="app_id",
204
+ help="github app id or client id; creates and refreshes installation tokens (implies --as-app)",
205
+ )
206
+ parser.add_argument(
207
+ "--app-private-key",
208
+ dest="app_private_key",
209
+ help="path to the github app private key (.pem), optionally as file://...",
210
+ )
211
+ parser.add_argument(
212
+ "--app-installation-id",
213
+ dest="app_installation_id",
214
+ help="id of the github app installation to back up (default: looked up from the user or organization)",
215
+ )
198
216
  parser.add_argument(
199
217
  "-o",
200
218
  "--output-directory",
@@ -522,12 +540,39 @@ def parse_args(args=None):
522
540
  default=5,
523
541
  help="maximum number of retries for API calls (default: 5)",
524
542
  )
525
- return parser.parse_args(args)
543
+ args = parser.parse_args(args)
544
+
545
+ if args.app_id or args.app_private_key or args.app_installation_id:
546
+ if not (args.app_id and args.app_private_key):
547
+ parser.error("--app-id and --app-private-key must be used together")
548
+ if (
549
+ args.token_classic
550
+ or args.token_fine
551
+ or args.token_from_gh
552
+ or args.osx_keychain_item_name
553
+ or args.osx_keychain_item_account
554
+ ):
555
+ parser.error(
556
+ "--app-id cannot be combined with -t, -f, --token-from-gh or keychain options"
557
+ )
558
+ args.app_private_key = args.app_private_key.removeprefix(FILE_URI_PREFIX)
559
+ if not os.path.isfile(args.app_private_key):
560
+ parser.error(
561
+ "--app-private-key file not found: {0}".format(args.app_private_key)
562
+ )
563
+ if not shutil.which("openssl"):
564
+ parser.error("--app-private-key requires the 'openssl' command on PATH")
565
+ args.as_app = True
566
+
567
+ return args
526
568
 
527
569
 
528
570
  def get_auth(args, encode=True, for_git_cli=False):
529
571
  auth = None
530
572
 
573
+ if args.app_id:
574
+ args.token_classic = get_app_installation_token(args)
575
+
531
576
  if args.osx_keychain_item_name:
532
577
  if not args.osx_keychain_item_account:
533
578
  raise Exception(
@@ -676,6 +721,110 @@ def read_token_from_gh_cli(args):
676
721
  return token
677
722
 
678
723
 
724
+ def build_app_jwt(private_key_path, claims):
725
+ """Build an RS256 JWT for authenticating as a GitHub App.
726
+
727
+ Signs with the openssl CLI so the project keeps no runtime dependencies.
728
+ """
729
+
730
+ def b64url(data):
731
+ return base64.urlsafe_b64encode(data).rstrip(b"=")
732
+
733
+ header = b64url(json.dumps({"alg": "RS256", "typ": "JWT"}).encode("ascii"))
734
+ signing_input = header + b"." + b64url(json.dumps(claims).encode("ascii"))
735
+
736
+ try:
737
+ signature = subprocess.run(
738
+ ["openssl", "dgst", "-sha256", "-sign", private_key_path],
739
+ input=signing_input,
740
+ capture_output=True,
741
+ check=True,
742
+ ).stdout
743
+ except subprocess.CalledProcessError as e:
744
+ stderr = e.stderr.decode("utf-8", errors="replace").strip()
745
+ raise Exception("Unable to sign GitHub App JWT: {0}".format(stderr))
746
+
747
+ return (signing_input + b"." + b64url(signature)).decode("ascii")
748
+
749
+
750
+ def get_app_installation_token(args):
751
+ """Return a GitHub App installation token, creating a new one when needed.
752
+
753
+ Installation tokens expire after an hour, so a new one is created once the
754
+ cached token is within APP_TOKEN_REFRESH_MARGIN seconds of expiring.
755
+ """
756
+ cached_token = getattr(args, "_app_token_value", None)
757
+ if cached_token and time.time() < (
758
+ args._app_token_expires_at - APP_TOKEN_REFRESH_MARGIN
759
+ ):
760
+ return cached_token
761
+
762
+ # GitHub rejects an exp more than 10 minutes out; backdate iat to tolerate
763
+ # clock drift.
764
+ now = int(time.time())
765
+ app_jwt = build_app_jwt(
766
+ args.app_private_key, {"iat": now - 60, "exp": now + 540, "iss": args.app_id}
767
+ )
768
+
769
+ if not args.app_installation_id:
770
+ owner_type = "orgs" if args.organization else "users"
771
+ installation = request_as_app(
772
+ args,
773
+ app_jwt,
774
+ "/{0}/{1}/installation".format(owner_type, args.user),
775
+ "Unable to find the GitHub App installation for {0}".format(args.user),
776
+ )
777
+ args.app_installation_id = str(installation["id"])
778
+ logger.info(
779
+ "Using GitHub App installation {0} for {1}".format(
780
+ args.app_installation_id, args.user
781
+ )
782
+ )
783
+
784
+ response = request_as_app(
785
+ args,
786
+ app_jwt,
787
+ "/app/installations/{0}/access_tokens".format(args.app_installation_id),
788
+ "Unable to create GitHub App installation token",
789
+ method="POST",
790
+ )
791
+
792
+ args._app_token_value = response["token"]
793
+ args._app_token_expires_at = calendar.timegm(
794
+ time.strptime(response["expires_at"], "%Y-%m-%dT%H:%M:%SZ")
795
+ )
796
+ logger.info(
797
+ "Created GitHub App installation token (expires {0})".format(
798
+ response["expires_at"]
799
+ )
800
+ )
801
+ return args._app_token_value
802
+
803
+
804
+ def request_as_app(args, app_jwt, path, error_message, method="GET"):
805
+ """Call the GitHub API authenticated as the app itself, with its JWT."""
806
+ request = Request(
807
+ "https://{0}{1}".format(get_github_api_host(args), path),
808
+ data=b"" if method == "POST" else None,
809
+ method=method,
810
+ )
811
+ request.add_header("Accept", "application/vnd.github+json")
812
+ request.add_header("Authorization", "Bearer " + app_jwt)
813
+
814
+ try:
815
+ http_response = make_request_with_retry(request, app_jwt, args.max_retries)
816
+ except HTTPError as exc:
817
+ raise Exception(
818
+ "{0}: HTTP {1} {2}: {3}".format(
819
+ error_message,
820
+ exc.code,
821
+ exc.reason,
822
+ exc.read().decode("utf-8", errors="replace"),
823
+ )
824
+ )
825
+ return json.loads(http_response.read().decode("utf-8"))
826
+
827
+
679
828
  def get_github_repo_url(args, repository):
680
829
  if repository.get("is_gist"):
681
830
  if args.prefer_ssh:
@@ -734,7 +883,6 @@ def retrieve_data(args, template, query_args=None, paginated=True, lazy=False):
734
883
  Handles throttling, retries, read errors, and DMCA takedowns.
735
884
  """
736
885
  query_args = query_args or {}
737
- auth = get_auth(args, encode=not args.as_app)
738
886
  per_page = 100
739
887
 
740
888
  def _extract_next_page_url(link_header):
@@ -754,21 +902,31 @@ def retrieve_data(args, template, query_args=None, paginated=True, lazy=False):
754
902
 
755
903
  next_url = None
756
904
 
905
+ def build_request(auth):
906
+ return _construct_request(
907
+ per_page=per_page if paginated else None,
908
+ query_args=query_args,
909
+ template=next_url or template,
910
+ auth=auth,
911
+ as_app=args.as_app,
912
+ fine=args.token_fine is not None,
913
+ )
914
+
757
915
  while True:
758
916
  # FIRST: Fetch response
759
917
 
760
918
  for attempt in range(args.max_retries + 1):
761
- request = _construct_request(
762
- per_page=per_page if paginated else None,
763
- query_args=query_args,
764
- template=next_url or template,
765
- auth=auth,
766
- as_app=args.as_app,
767
- fine=args.token_fine is not None,
768
- )
919
+ # Resolved per request (and again before each retry) so long
920
+ # runs pick up refreshed app tokens
921
+ auth = get_auth(args, encode=not args.as_app)
769
922
  try:
770
923
  http_response = make_request_with_retry(
771
- request, auth, args.max_retries
924
+ build_request(auth),
925
+ auth,
926
+ args.max_retries,
927
+ rebuild_request=lambda: build_request(
928
+ get_auth(args, encode=not args.as_app)
929
+ ),
772
930
  )
773
931
  except HTTPError as exc:
774
932
  if exc.code == 451:
@@ -879,17 +1037,29 @@ def retrieve_graphql_data(args, query, variables=None, log_context=None):
879
1037
  ).encode("utf-8")
880
1038
  endpoint = get_github_graphql_url(args)
881
1039
 
882
- for attempt in range(args.max_retries + 1):
1040
+ def build_request(auth):
883
1041
  request = Request(endpoint, data=payload, method="POST")
884
1042
  request.add_header("Accept", "application/json")
885
1043
  request.add_header("Content-Type", "application/json")
886
1044
  request.add_header("Authorization", "bearer " + auth)
1045
+ return request
1046
+
1047
+ for attempt in range(args.max_retries + 1):
1048
+ if attempt:
1049
+ # Resolved again after a retry wait so long runs pick up refreshed
1050
+ # app tokens
1051
+ auth = get_graphql_auth(args)
887
1052
  log_url = endpoint
888
1053
  if log_context:
889
1054
  log_url = "{0} ({1})".format(log_url, log_context)
890
1055
  logger.info("Requesting {0}".format(log_url))
891
1056
 
892
- http_response = make_request_with_retry(request, auth, args.max_retries)
1057
+ http_response = make_request_with_retry(
1058
+ build_request(auth),
1059
+ auth,
1060
+ args.max_retries,
1061
+ rebuild_request=lambda: build_request(get_graphql_auth(args)),
1062
+ )
893
1063
 
894
1064
  status = http_response.getcode()
895
1065
  if status != 200:
@@ -948,8 +1118,14 @@ def retrieve_graphql_data(args, query, variables=None, log_context=None):
948
1118
  ) # pragma: no cover
949
1119
 
950
1120
 
951
- def make_request_with_retry(request, auth, max_retries=5):
952
- """Make HTTP request with automatic retry for transient errors."""
1121
+ def make_request_with_retry(request, auth, max_retries=5, rebuild_request=None):
1122
+ """Make HTTP request with automatic retry for transient errors.
1123
+
1124
+ If given, rebuild_request is called to build the request again before each
1125
+ retry. A rate-limit wait can last longer than a GitHub App installation
1126
+ token, so callers that resolve credentials per request use it to resend
1127
+ with the token that is current after the wait.
1128
+ """
953
1129
 
954
1130
  def is_retryable_status(status_code, headers):
955
1131
  # Server errors are always retryable
@@ -961,6 +1137,8 @@ def make_request_with_retry(request, auth, max_retries=5):
961
1137
  return False
962
1138
 
963
1139
  for attempt in range(max_retries + 1):
1140
+ if attempt and rebuild_request is not None:
1141
+ request = rebuild_request()
964
1142
  try:
965
1143
  return urlopen(request, context=https_ctx)
966
1144
 
@@ -1271,6 +1449,25 @@ def download_attachment_file(url, path, auth, as_app=False, fine=False):
1271
1449
  return metadata
1272
1450
 
1273
1451
 
1452
+ def needs_jwt_workaround(args, repository, url):
1453
+ """Whether an attachment must be fetched through a JWT-signed URL.
1454
+
1455
+ Fine-grained PATs (#477) and GitHub App installation tokens get a 404 when
1456
+ downloading attachments from private repositories directly, while classic
1457
+ tokens do not. Image attachments, in both the modern
1458
+ github.com/user-attachments/assets/* and the older
1459
+ github.com/{owner}/{repo}/assets/* format, can be fetched through the
1460
+ JWT-signed URL that the Markdown API renders for them. /files/ URLs cannot.
1461
+ """
1462
+ if args.token_fine is None and not args.as_app:
1463
+ return False
1464
+ if not repository.get("private", False):
1465
+ return False
1466
+ return "github.com/user-attachments/assets/" in url or bool(
1467
+ re.match(r"https://github\.com/[^/]+/[^/]+/assets/\d+/", url)
1468
+ )
1469
+
1470
+
1274
1471
  def get_jwt_signed_url_via_markdown_api(url, token, repo_context):
1275
1472
  """Convert a user-attachments/assets URL to a JWT-signed URL via Markdown API.
1276
1473
 
@@ -1278,8 +1475,9 @@ def get_jwt_signed_url_via_markdown_api(url, token, repo_context):
1278
1475
  JWT-signed private-user-images.githubusercontent.com URLs that work
1279
1476
  without token authentication.
1280
1477
 
1281
- This is a workaround for issue #477 where fine-grained PATs cannot
1282
- download user-attachments URLs from private repos directly.
1478
+ This is a workaround for issue #477 where fine-grained PATs (and GitHub
1479
+ App installation tokens) cannot download attachments from private repos
1480
+ directly.
1283
1481
 
1284
1482
  Limitations:
1285
1483
  - Only works for /assets/ URLs (images)
@@ -1287,8 +1485,8 @@ def get_jwt_signed_url_via_markdown_api(url, token, repo_context):
1287
1485
  - JWT URLs expire after ~5 minutes
1288
1486
 
1289
1487
  Args:
1290
- url: The github.com/user-attachments/assets/UUID URL
1291
- token: Raw fine-grained PAT (github_pat_...)
1488
+ url: The image attachment URL (user-attachments/assets or repo assets)
1489
+ token: Raw fine-grained PAT (github_pat_...) or App installation token
1292
1490
  repo_context: Repository context as "owner/repo"
1293
1491
 
1294
1492
  Returns:
@@ -1683,16 +1881,7 @@ def download_attachments(
1683
1881
  filename = get_attachment_filename(url)
1684
1882
  filepath = os.path.join(attachments_dir, filename)
1685
1883
 
1686
- # Issue #477: Fine-grained PATs cannot download user-attachments/assets
1687
- # from private repos directly (404). Use Markdown API workaround to get
1688
- # a JWT-signed URL. Only works for /assets/ (images), not /files/.
1689
- needs_jwt = (
1690
- args.token_fine is not None
1691
- and repository.get("private", False)
1692
- and "github.com/user-attachments/assets/" in url
1693
- )
1694
-
1695
- if not needs_jwt:
1884
+ if not needs_jwt_workaround(args, repository, url):
1696
1885
  # NORMAL download path
1697
1886
  metadata = download_attachment_file(
1698
1887
  url,
@@ -1702,7 +1891,7 @@ def download_attachments(
1702
1891
  fine=args.token_fine is not None,
1703
1892
  )
1704
1893
  elif jwt_url := get_jwt_signed_url_via_markdown_api(
1705
- url, args.token_fine, repository["full_name"]
1894
+ url, get_auth(args, encode=False), repository["full_name"]
1706
1895
  ):
1707
1896
  # JWT needed and extracted, download via JWT
1708
1897
  metadata = download_attachment_file(
@@ -1716,8 +1905,8 @@ def download_attachments(
1716
1905
  "url": url,
1717
1906
  "success": False,
1718
1907
  "skipped_at": datetime.now(timezone.utc).isoformat(),
1719
- "error": "Fine-grained token cannot download private repo attachments. "
1720
- "Markdown API workaround failed. Use --token-classic instead.",
1908
+ "error": "Fine-grained and GitHub App tokens cannot download private repo "
1909
+ "attachments. Markdown API workaround failed. Use --token-classic instead.",
1721
1910
  }
1722
1911
  logger.warning(
1723
1912
  "Skipping attachment {0}: {1}".format(url, metadata["error"])
@@ -2127,7 +2316,7 @@ def gist_backup_is_current(repository, repo_cwd, repo_dir):
2127
2316
  if not updated_at:
2128
2317
  return False
2129
2318
  try:
2130
- with codecs.open(os.path.join(repo_cwd, "gist.json"), encoding="utf-8") as f:
2319
+ with open(os.path.join(repo_cwd, "gist.json"), encoding="utf-8", newline="") as f:
2131
2320
  stored = json.load(f)
2132
2321
  except (OSError, ValueError):
2133
2322
  return False
@@ -2200,7 +2389,7 @@ def backup_repositories(args, output_directory, repositories):
2200
2389
  # DMCA-blocked or empty gist), so make sure the directory exists
2201
2390
  mkdir_p(repo_cwd)
2202
2391
  output_file = "{0}/gist.json".format(repo_cwd)
2203
- with codecs.open(output_file, "w", encoding="utf-8") as f:
2392
+ with open(output_file, "w", encoding="utf-8", newline="") as f:
2204
2393
  json_dump(repository, f)
2205
2394
 
2206
2395
  continue # don't try to back anything else for a gist; it doesn't exist
@@ -2210,14 +2399,15 @@ def backup_repositories(args, output_directory, repositories):
2210
2399
  if repository["has_wiki"] and download_wiki:
2211
2400
  fetch_repository(
2212
2401
  repository["name"],
2213
- repo_url.replace(".git", ".wiki.git"),
2402
+ # Rebuilt so a long repository clone can't leave it an expired app token
2403
+ get_github_repo_url(args, repository).replace(".git", ".wiki.git"),
2214
2404
  os.path.join(repo_cwd, "wiki"),
2215
2405
  skip_existing=args.skip_existing,
2216
2406
  bare_clone=args.bare_clone,
2217
2407
  lfs_clone=args.lfs_clone,
2218
2408
  no_prune=args.no_prune,
2219
2409
  )
2220
- if args.include_issues or args.include_everything:
2410
+ if repository["has_issues"] and (args.include_issues or args.include_everything):
2221
2411
  incremental_resource_work_attempted = True
2222
2412
  issue_cwd = os.path.join(repo_cwd, "issues")
2223
2413
  args.since = read_resource_last_update(
@@ -2226,7 +2416,7 @@ def backup_repositories(args, output_directory, repositories):
2226
2416
  backup_issues(args, repo_cwd, repository, repos_template)
2227
2417
  write_resource_last_update(args, issue_cwd, repository)
2228
2418
 
2229
- if args.include_pulls or args.include_everything:
2419
+ if repository.get("has_pull_requests", True) and (args.include_pulls or args.include_everything):
2230
2420
  incremental_resource_work_attempted = True
2231
2421
  pulls_cwd = os.path.join(repo_cwd, "pulls")
2232
2422
  args.since = read_resource_last_update(
@@ -2235,7 +2425,7 @@ def backup_repositories(args, output_directory, repositories):
2235
2425
  backup_pulls(args, repo_cwd, repository, repos_template)
2236
2426
  write_resource_last_update(args, pulls_cwd, repository)
2237
2427
 
2238
- if args.include_discussions or args.include_everything:
2428
+ if repository["has_discussions"] and (args.include_discussions or args.include_everything):
2239
2429
  backup_discussions(args, repo_cwd, repository)
2240
2430
 
2241
2431
  if args.include_milestones or args.include_everything:
@@ -2843,7 +3033,7 @@ def backup_issues(args, repo_cwd, repository, repos_template):
2843
3033
  args, issue_cwd, issues[number], number, repository, item_type="issue"
2844
3034
  )
2845
3035
 
2846
- with codecs.open(issue_file + ".temp", "w", encoding="utf-8") as f:
3036
+ with open(issue_file + ".temp", "w", encoding="utf-8", newline="") as f:
2847
3037
  json_dump(issue, f)
2848
3038
  os.replace(issue_file + ".temp", issue_file) # Atomic write
2849
3039
 
@@ -2862,7 +3052,7 @@ def read_json_file_if_exists(path):
2862
3052
  return None
2863
3053
 
2864
3054
  try:
2865
- with codecs.open(path, "r", encoding="utf-8") as f:
3055
+ with open(path, "r", encoding="utf-8", newline="") as f:
2866
3056
  return json.load(f)
2867
3057
  except (OSError, UnicodeDecodeError, json.decoder.JSONDecodeError) as e:
2868
3058
  logger.debug("Error reading existing JSON file {0}: {1}".format(path, e))
@@ -2900,6 +3090,51 @@ def get_pull_reviews_since(args, pulls_cwd):
2900
3090
  return args_since or reviews_since, reviews_since, reviews_last_update_path
2901
3091
 
2902
3092
 
3093
+ def get_pull_comments_with_graphql(args, repository, number):
3094
+ after = None
3095
+ comments_page = 1
3096
+ comments = []
3097
+ comment_total_count = 0
3098
+ owner, name = _repository_owner_name(repository)
3099
+ while True:
3100
+ data = retrieve_graphql_data(
3101
+ args,
3102
+ PULL_COMMENTS_QUERY,
3103
+ {
3104
+ "owner": owner,
3105
+ "name": name,
3106
+ "number": number,
3107
+ "after": after,
3108
+ "pageSize": PULL_PAGE_SIZE,
3109
+ },
3110
+ log_context="pull request {0}#{1} comments page {2}".format(
3111
+ repository["full_name"], number, comments_page
3112
+ ),
3113
+ )
3114
+ repository_data = data.get("repository") or {}
3115
+ pr_data = repository_data.get("pullRequest")
3116
+ if pr_data is None:
3117
+ raise Exception(
3118
+ "Pull request #{0} not found in {1}".format(
3119
+ number, repository["full_name"]
3120
+ )
3121
+ )
3122
+
3123
+ comments_connection = pr_data.get("comments") or {}
3124
+ comment_total_count = comments_connection.get(
3125
+ "totalCount", comment_total_count
3126
+ )
3127
+ comments.extend(_connection_nodes(comments_connection))
3128
+
3129
+ page_info = comments_connection.get("pageInfo") or {}
3130
+ if not page_info.get("hasNextPage"):
3131
+ break
3132
+
3133
+ after = page_info.get("endCursor")
3134
+ comments_page += 1
3135
+ return comments
3136
+
3137
+
2903
3138
  def backup_pulls(args, repo_cwd, repository, repos_template):
2904
3139
  has_pulls_dir = os.path.isdir("{0}/pulls/.git".format(repo_cwd))
2905
3140
  if args.skip_existing and has_pulls_dir:
@@ -3026,7 +3261,61 @@ def backup_pulls(args, repo_cwd, repository, repos_template):
3026
3261
  args.include_pull_comments or args.include_everything
3027
3262
  ) and should_fetch_non_review_data:
3028
3263
  template = comments_regular_template.format(number)
3029
- pulls[number]["comment_regular_data"] = retrieve_data(args, template)
3264
+ try:
3265
+ pulls[number]["comment_regular_data"] = retrieve_data(args, template)
3266
+ except HTTPError as e:
3267
+ # Issue #547: REST API endpoint for regular comments on temporary
3268
+ # private forks returns 404. There's nothing in repo data that would
3269
+ # indicate that repo is private temporary fork so best we can do is
3270
+ # limit this special case a bit more by limiting it to private repos.
3271
+ if not repository.get("private", False) or e.code != 404:
3272
+ raise
3273
+ pulls[number]["comment_regular_data"] = get_pull_comments_with_graphql(
3274
+ args, repository, number
3275
+ )
3276
+ after = None
3277
+ comments_page = 1
3278
+ comments = []
3279
+ comment_total_count = 0
3280
+ owner, name = _repository_owner_name(repository)
3281
+ while True:
3282
+ data = retrieve_graphql_data(
3283
+ args,
3284
+ PULL_COMMENTS_QUERY,
3285
+ {
3286
+ "owner": owner,
3287
+ "name": name,
3288
+ "number": number,
3289
+ "after": after,
3290
+ "pageSize": PULL_PAGE_SIZE,
3291
+ },
3292
+ log_context="pull request {0}#{1} comments page {2}".format(
3293
+ repository["full_name"], number, comments_page
3294
+ ),
3295
+ )
3296
+ repository_data = data.get("repository") or {}
3297
+ pr_data = repository_data.get("pullRequest")
3298
+ if pr_data is None:
3299
+ raise Exception(
3300
+ "Pull request #{0} not found in {1}".format(
3301
+ number, repository["full_name"]
3302
+ )
3303
+ )
3304
+
3305
+ comments_connection = pr_data.get("comments") or {}
3306
+ comment_total_count = comments_connection.get(
3307
+ "totalCount", comment_total_count
3308
+ )
3309
+ comments.extend(_connection_nodes(comments_connection))
3310
+
3311
+ page_info = comments_connection.get("pageInfo") or {}
3312
+ if not page_info.get("hasNextPage"):
3313
+ break
3314
+
3315
+ after = page_info.get("endCursor")
3316
+ comments_page += 1
3317
+ pulls[number]["comment_regular_data"] = comments
3318
+
3030
3319
  template = comments_template.format(number)
3031
3320
  pulls[number]["comment_data"] = retrieve_data(args, template)
3032
3321
  if include_pull_reviews:
@@ -3052,7 +3341,7 @@ def backup_pulls(args, repo_cwd, repository, repos_template):
3052
3341
 
3053
3342
  restore_existing_pull_optional_data(pull, existing_pull)
3054
3343
 
3055
- with codecs.open(pull_file + ".temp", "w", encoding="utf-8") as f:
3344
+ with open(pull_file + ".temp", "w", encoding="utf-8", newline="") as f:
3056
3345
  json_dump(pull, f)
3057
3346
  os.replace(pull_file + ".temp", pull_file) # Atomic write
3058
3347
 
@@ -3074,13 +3363,20 @@ def backup_milestones(args, repo_cwd, repository, repos_template):
3074
3363
  return
3075
3364
 
3076
3365
  logger.info("Retrieving {0} milestones".format(repository["full_name"]))
3077
- mkdir_p(repo_cwd, milestone_cwd)
3078
3366
 
3079
3367
  template = "{0}/{1}/milestones".format(repos_template, repository["full_name"])
3080
3368
 
3081
3369
  query_args = {"state": "all"}
3082
3370
 
3083
- _milestones = retrieve_data(args, template, query_args=query_args)
3371
+ try:
3372
+ _milestones = retrieve_data(args, template, query_args=query_args)
3373
+ except HTTPError as e:
3374
+ if e.code == 404:
3375
+ logger.info("Milestones are not available for this repository, skipping")
3376
+ return
3377
+ raise
3378
+
3379
+ mkdir_p(repo_cwd, milestone_cwd)
3084
3380
 
3085
3381
  milestones = {}
3086
3382
  for milestone in _milestones:
@@ -3153,7 +3449,13 @@ def backup_labels(args, repo_cwd, repository, repos_template):
3153
3449
  label_cwd = os.path.join(repo_cwd, "labels")
3154
3450
  output_file = "{0}/labels.json".format(label_cwd)
3155
3451
  template = "{0}/{1}/labels".format(repos_template, repository["full_name"])
3156
- _backup_data(args, "labels", template, output_file, label_cwd)
3452
+ try:
3453
+ _backup_data(args, "labels", template, output_file, label_cwd)
3454
+ except HTTPError as e:
3455
+ if e.code == 404:
3456
+ logger.info("Labels are not available for this repository, skipping")
3457
+ return
3458
+ raise
3157
3459
 
3158
3460
 
3159
3461
  def backup_hooks(args, repo_cwd, repository, repos_template):
@@ -3190,15 +3492,23 @@ def backup_hooks(args, repo_cwd, repository, repos_template):
3190
3492
  def backup_releases(args, repo_cwd, repository, repos_template, include_assets=False):
3191
3493
  repository_fullname = repository["full_name"]
3192
3494
 
3193
- # give release files somewhere to live & log intent
3194
- release_cwd = os.path.join(repo_cwd, "releases")
3495
+ # log intent
3195
3496
  logger.info("Retrieving {0} releases".format(repository_fullname))
3196
- mkdir_p(repo_cwd, release_cwd)
3197
3497
 
3198
3498
  query_args = {}
3199
3499
 
3200
3500
  release_template = "{0}/{1}/releases".format(repos_template, repository_fullname)
3201
- releases = retrieve_data(args, release_template, query_args=query_args)
3501
+ try:
3502
+ releases = retrieve_data(args, release_template, query_args=query_args)
3503
+ except HTTPError as e:
3504
+ if e.code == 404:
3505
+ logger.info("Releases are not available for this repository, skipping")
3506
+ return
3507
+ raise
3508
+
3509
+ # give release files somewhere to live
3510
+ release_cwd = os.path.join(repo_cwd, "releases")
3511
+ mkdir_p(repo_cwd, release_cwd)
3202
3512
 
3203
3513
  if args.skip_prerelease:
3204
3514
  releases = [r for r in releases if not r["prerelease"] and not r["draft"]]
@@ -3417,9 +3727,9 @@ def _backup_data(args, name, template, output_file, output_directory):
3417
3727
  skip_existing = args.skip_existing
3418
3728
  if not skip_existing or not os.path.exists(output_file):
3419
3729
  logger.info("Retrieving {0} {1}".format(args.user, name))
3420
- mkdir_p(output_directory)
3421
3730
  data = retrieve_data(args, template)
3422
3731
 
3732
+ mkdir_p(output_directory)
3423
3733
  if json_dump_if_changed(data, output_file):
3424
3734
  logger.info("Saved {0} {1} to disk".format(len(data), name))
3425
3735
  else:
@@ -3468,7 +3778,7 @@ def json_dump_if_changed(data, output_file_path):
3468
3778
  # Check if file exists and compare content
3469
3779
  if os.path.exists(output_file_path):
3470
3780
  try:
3471
- with codecs.open(output_file_path, "r", encoding="utf-8") as f:
3781
+ with open(output_file_path, "r", encoding="utf-8", newline="") as f:
3472
3782
  existing_content = f.read()
3473
3783
  if existing_content == new_content:
3474
3784
  logger.debug(
@@ -3485,7 +3795,7 @@ def json_dump_if_changed(data, output_file_path):
3485
3795
 
3486
3796
  # Write the file atomically using temp file + rename
3487
3797
  temp_file = output_file_path + ".temp"
3488
- with codecs.open(temp_file, "w", encoding="utf-8") as f:
3798
+ with open(temp_file, "w", encoding="utf-8", newline="") as f:
3489
3799
  f.write(new_content)
3490
3800
  os.replace(temp_file, output_file_path) # Atomic write
3491
3801
  return True
@@ -1,6 +1,7 @@
1
1
  """GraphQL query templates used by github-backup."""
2
2
 
3
3
  DISCUSSION_PAGE_SIZE = 100
4
+ PULL_PAGE_SIZE = 100
4
5
 
5
6
  CROSS_REFERENCE_PAGE_SIZE = 100
6
7
 
@@ -62,6 +63,72 @@ query($owner: String!, $name: String!, $after: String, $pageSize: Int!,
62
63
  }
63
64
  """
64
65
 
66
+ PULL_COMMENTS_QUERY = """
67
+ query($owner: String!, $name: String!, $number: Int!, $after: String, $pageSize: Int!) {
68
+ repository(owner: $owner, name: $name) {
69
+ pullRequest(number: $number) {
70
+ comments(first: $pageSize, after: $after) {
71
+ totalCount
72
+ nodes {
73
+ ...IssueCommentFields
74
+ }
75
+ pageInfo {
76
+ hasNextPage
77
+ endCursor
78
+ }
79
+ }
80
+ }
81
+ }
82
+ }
83
+
84
+ fragment ActorFields on Actor {
85
+ avatarUrl
86
+ login
87
+ resourcePath
88
+ url
89
+ }
90
+
91
+ fragment ReactionGroupFields on ReactionGroup {
92
+ content
93
+ reactors {
94
+ totalCount
95
+ }
96
+ }
97
+
98
+ fragment IssueCommentFields on IssueComment {
99
+ author {
100
+ ...ActorFields
101
+ }
102
+ authorAssociation
103
+ body
104
+ bodyHTML
105
+ bodyText
106
+ createdAt
107
+ createdViaEmail
108
+ databaseId
109
+ editor {
110
+ ...ActorFields
111
+ }
112
+ id
113
+ includesCreatedEdit
114
+ isMinimized
115
+ isPinned
116
+ lastEditedAt
117
+ minimizedReason
118
+ pinnedAt
119
+ pinnedBy {
120
+ ...ActorFields
121
+ }
122
+ publishedAt
123
+ reactionGroups {
124
+ ...ReactionGroupFields
125
+ }
126
+ resourcePath
127
+ updatedAt
128
+ url
129
+ }
130
+ """
131
+
65
132
  DISCUSSION_LIST_QUERY = """
66
133
  query($owner: String!, $name: String!, $after: String, $pageSize: Int!) {
67
134
  repository(owner: $owner, name: $name) {
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: github-backup
3
- Version: 0.67.0
3
+ Version: 0.69.0
4
4
  Summary: backup a github user or organization
5
5
  Home-page: http://github.com/josegonzalez/python-github-backup
6
6
  Author: Jose Diaz-Gonzalez
@@ -13,6 +13,7 @@ Classifier: Programming Language :: Python :: 3.11
13
13
  Classifier: Programming Language :: Python :: 3.12
14
14
  Classifier: Programming Language :: Python :: 3.13
15
15
  Classifier: Programming Language :: Python :: 3.14
16
+ Classifier: Programming Language :: Python :: 3.15
16
17
  Requires-Python: >=3.11
17
18
  Description-Content-Type: text/x-rst
18
19
  License-File: LICENSE.txt
@@ -66,7 +67,10 @@ Show the CLI help output::
66
67
  CLI Help output::
67
68
 
68
69
  github-backup [-h] [-t TOKEN_CLASSIC] [-f TOKEN_FINE] [--token-from-gh]
69
- [-q] [--as-app] [-o OUTPUT_DIRECTORY] [-l LOG_LEVEL] [-i]
70
+ [-q] [--as-app] [--app-id APP_ID]
71
+ [--app-private-key APP_PRIVATE_KEY]
72
+ [--app-installation-id APP_INSTALLATION_ID]
73
+ [-o OUTPUT_DIRECTORY] [-l LOG_LEVEL] [-i]
70
74
  [--incremental-by-files]
71
75
  [--starred] [--all-starred] [--starred-skip-size-over MB]
72
76
  [--watched] [--followers] [--following] [--all]
@@ -107,6 +111,14 @@ CLI Help output::
107
111
  -q, --quiet supress log messages less severe than warning, e.g.
108
112
  info
109
113
  --as-app authenticate as github app instead of as a user.
114
+ --app-id APP_ID github app id or client id; creates and refreshes
115
+ installation tokens (implies --as-app)
116
+ --app-private-key APP_PRIVATE_KEY
117
+ path to the github app private key (.pem), optionally
118
+ as file://...
119
+ --app-installation-id APP_INSTALLATION_ID
120
+ id of the github app installation to back up
121
+ (default: looked up from the user or organization)
110
122
  -o, --output-directory OUTPUT_DIRECTORY
111
123
  directory at which to backup the repositories
112
124
  -l, --log-level LOG_LEVEL
@@ -241,9 +253,19 @@ For a user account (no ``--organization``), ``--as-app`` lists the repositories
241
253
  7. Go to *Install App* in your app's settings
242
254
  8. Select the account/organization and which repositories to back up
243
255
 
244
- **CI/CD usage with GitHub Actions:**
256
+ **Using the app's private key:**
245
257
 
246
- Store the App ID as a repository variable and the private key contents as a secret, then use ``actions/create-github-app-token``::
258
+ Pass the App ID and private key file, and github-backup creates installation tokens itself, refreshing them before they expire so long-running backups keep working::
259
+
260
+ github-backup myorg --organization --app-id 12345 --app-private-key /path/to/app.private-key.pem -o ./backup --all
261
+
262
+ The app's installation on the user or organization being backed up is looked up automatically. To skip the lookup, pass ``--app-installation-id`` with the number at the end of the installation's settings URL (``.../settings/installations/<id>``).
263
+
264
+ ``--app-id`` implies ``--as-app`` and cannot be combined with ``-t``, ``-f``, ``--token-from-gh`` or the keychain options. The ``iss`` claim of the signed JWT is set to the value of ``--app-id``, so the app's client ID works there too. The JWT is signed by the ``openssl`` command line tool, which must be on your ``PATH`` (the Docker image includes it).
265
+
266
+ **Using an existing installation token:**
267
+
268
+ If something else already creates the installation token, pass it with ``-t`` and ``--as-app``. In GitHub Actions, store the App ID as a repository variable and the private key contents as a secret, then use ``actions/create-github-app-token``::
247
269
 
248
270
  - uses: actions/create-github-app-token@v1
249
271
  id: app-token
@@ -253,7 +275,7 @@ Store the App ID as a repository variable and the private key contents as a secr
253
275
 
254
276
  - run: github-backup myorg -t ${{ steps.app-token.outputs.token }} --as-app -o ./backup --all
255
277
 
256
- Note: Installation tokens expire after 1 hour. For long-running backups, use a fine-grained personal access token instead.
278
+ Note: Installation tokens passed with ``-t`` expire after 1 hour and are not refreshed. For backups that may run longer, use ``--app-private-key`` instead.
257
279
 
258
280
 
259
281
  Prefer SSH
@@ -322,7 +344,7 @@ The tool automatically extracts file extensions from HTTP headers to ensure file
322
344
 
323
345
  **Repository filtering** for repo files/assets handles renamed and transferred repositories gracefully. URLs are included if they either match the current repository name directly, or redirect to it (e.g., ``willmcgugan/rich`` redirects to ``Textualize/rich`` after transfer).
324
346
 
325
- **Fine-grained token limitation:** Due to a GitHub platform limitation, fine-grained personal access tokens (``github_pat_...``) cannot download attachments from private repositories directly. This affects both ``/assets/`` (images) and ``/files/`` (documents) URLs. The tool implements a workaround for image attachments using GitHub's Markdown API, which converts URLs to temporary JWT-signed URLs that can be downloaded. However, this workaround only works for images - document attachments (PDFs, text files, etc.) will fail with 404 errors when using fine-grained tokens on private repos. For full attachment support on private repositories, use a classic token (``-t``) instead of a fine-grained token (``-f``). See `#477 <https://github.com/josegonzalez/python-github-backup/issues/477>`_ for details.
347
+ **Fine-grained and GitHub App token limitation:** Due to a GitHub platform limitation, fine-grained personal access tokens (``github_pat_...``) and GitHub App installation tokens (``--as-app`` or ``--app-id``) cannot download attachments from private repositories directly. This affects ``/assets/`` (images) and ``/files/`` (documents) URLs, in both the ``github.com/user-attachments/`` and the older ``github.com/{owner}/{repo}/`` format. The tool implements a workaround for image attachments using GitHub's Markdown API, which converts URLs to temporary JWT-signed URLs that can be downloaded. The token needs read access to contents for this (included in the permissions above); without it, the Markdown API still responds but does not sign the image URLs. However, this workaround only works for images - document attachments (PDFs, text files, etc.) will fail with 404 errors when using these tokens on private repos. For full attachment support on private repositories, use a classic token (``-t``) instead. See `#477 <https://github.com/josegonzalez/python-github-backup/issues/477>`_ for details.
326
348
 
327
349
 
328
350
  About Discussions
@@ -541,6 +563,8 @@ Development
541
563
 
542
564
  This project is considered feature complete for the primary maintainer @josegonzalez. If you would like a bugfix or enhancement, pull requests are welcome. Feel free to contact the maintainer for consulting estimates if you'd like to sponsor the work instead.
543
565
 
566
+ If you use a coding agent, point it at `AGENTS.md <AGENTS.md>`_, which collects the conventions that reviews of past pull requests have settled on.
567
+
544
568
  Contibuters
545
569
  -----------
546
570
 
@@ -561,7 +585,7 @@ To run the test suite::
561
585
  To run linting::
562
586
 
563
587
  pip install flake8
564
- flake8 --ignore=E501
588
+ flake8 --ignore=E501,E203,W503
565
589
 
566
590
 
567
591
  .. |PyPI| image:: https://img.shields.io/pypi/v/github-backup.svg
@@ -0,0 +1,12 @@
1
+ github_backup/__init__.py,sha256=KqW3RShDvR3XpTHqOOZs4x2eNNCNE3rl8jGUOBXzcw0,23
2
+ github_backup/__main__.py,sha256=3yorCiC63maaxbjdtaeAs-G-yAAxKSO3mprhGfa1Fho,271
3
+ github_backup/cli.py,sha256=JTiXPOvB8id8LopREOEd1W_FLvuf9SOZU5buMRPFd9U,2922
4
+ github_backup/github_backup.py,sha256=8MVNXzpDI-tusQHlrUGXxDn45E2d3byYS7rZGZCiDi8,139502
5
+ github_backup/graphql_queries.py,sha256=TwzMYPVi0vgVCYSPx1-i_KjKKjmpBxNECJkni8WHfVI,7769
6
+ github_backup-0.69.0.dist-info/licenses/LICENSE.txt,sha256=ML-pLyn1qtAKo_DHMcQ8-p7k3f8cp-IR-mf5B49R2rk,1085
7
+ github_backup-0.69.0.dist-info/METADATA,sha256=7W4EdIUVHSho8KOD63_33zc35cB3Ld5PEm0ITP-6BE0,38411
8
+ github_backup-0.69.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
9
+ github_backup-0.69.0.dist-info/entry_points.txt,sha256=cLPKK7MqC77QVb6HnT2mnyL_f-ciavJG_Y9vVHlCF68,57
10
+ github_backup-0.69.0.dist-info/top_level.txt,sha256=Za6fKRAlxZ0b3ZBH_osPqklLe14LetdNAkvAQANT2AA,14
11
+ github_backup-0.69.0.dist-info/zip-safe,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
12
+ github_backup-0.69.0.dist-info/RECORD,,
@@ -1,12 +0,0 @@
1
- github_backup/__init__.py,sha256=DkegR91M-IkILN5EBv-0LVftxIGE60qyryEQ_lYCjdg,23
2
- github_backup/__main__.py,sha256=3yorCiC63maaxbjdtaeAs-G-yAAxKSO3mprhGfa1Fho,271
3
- github_backup/cli.py,sha256=JTiXPOvB8id8LopREOEd1W_FLvuf9SOZU5buMRPFd9U,2922
4
- github_backup/github_backup.py,sha256=5OvANlDQv06qn3awp5rbOzP8ocV88l2o0O-9ng6RywI,127852
5
- github_backup/graphql_queries.py,sha256=XcAQyp9nF7Ip9UzxsrXMkl2pO-W7SK8hhO2oE9HVcmA,6658
6
- github_backup-0.67.0.dist-info/licenses/LICENSE.txt,sha256=ML-pLyn1qtAKo_DHMcQ8-p7k3f8cp-IR-mf5B49R2rk,1085
7
- github_backup-0.67.0.dist-info/METADATA,sha256=redpeZKBK8eOJsG4nM7axcT7pz4v3jBDkeBV509NUfU,36164
8
- github_backup-0.67.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
9
- github_backup-0.67.0.dist-info/entry_points.txt,sha256=cLPKK7MqC77QVb6HnT2mnyL_f-ciavJG_Y9vVHlCF68,57
10
- github_backup-0.67.0.dist-info/top_level.txt,sha256=Za6fKRAlxZ0b3ZBH_osPqklLe14LetdNAkvAQANT2AA,14
11
- github_backup-0.67.0.dist-info/zip-safe,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
12
- github_backup-0.67.0.dist-info/RECORD,,