forked from josegonzalez/python-github-backup
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub_backup.py
More file actions
2073 lines (1790 loc) · 73 KB
/
github_backup.py
File metadata and controls
2073 lines (1790 loc) · 73 KB
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
from __future__ import print_function
import argparse
import base64
import calendar
import codecs
import errno
import getpass
import json
import logging
import os
import platform
import re
import select
import socket
import ssl
import subprocess
import sys
import time
from datetime import datetime
from http.client import IncompleteRead
from urllib.error import HTTPError, URLError
from urllib.parse import quote as urlquote
from urllib.parse import urlencode, urlparse
from urllib.request import HTTPRedirectHandler, Request, build_opener, urlopen
try:
from . import __version__
VERSION = __version__
except ImportError:
VERSION = "unknown"
FNULL = open(os.devnull, "w")
FILE_URI_PREFIX = "file://"
logger = logging.getLogger(__name__)
https_ctx = ssl.create_default_context()
if not https_ctx.get_ca_certs():
import warnings
warnings.warn(
"\n\nYOUR DEFAULT CA CERTS ARE EMPTY.\n"
+ "PLEASE POPULATE ANY OF:"
+ "".join(
["\n - " + x for x in ssl.get_default_verify_paths() if type(x) is str]
)
+ "\n",
stacklevel=2,
)
import certifi
https_ctx = ssl.create_default_context(cafile=certifi.where())
def logging_subprocess(
popenargs, stdout_log_level=logging.DEBUG, stderr_log_level=logging.ERROR, **kwargs
):
"""
Variant of subprocess.call that accepts a logger instead of stdout/stderr,
and logs stdout messages via logger.debug and stderr messages via
logger.error.
"""
child = subprocess.Popen(
popenargs, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs
)
if sys.platform == "win32":
logger.info(
"Windows operating system detected - no subprocess logging will be returned"
)
log_level = {child.stdout: stdout_log_level, child.stderr: stderr_log_level}
def check_io():
if sys.platform == "win32":
return
ready_to_read = select.select([child.stdout, child.stderr], [], [], 1000)[0]
for io in ready_to_read:
line = io.readline()
if not logger:
continue
if not (io == child.stderr and not line):
logger.log(log_level[io], line[:-1])
# keep checking stdout/stderr until the child exits
while child.poll() is None:
check_io()
check_io() # check again to catch anything after the process exits
rc = child.wait()
if rc != 0:
print("{} returned {}:".format(popenargs[0], rc), file=sys.stderr)
print("\t", " ".join(popenargs), file=sys.stderr)
return rc
def mkdir_p(*args):
for path in args:
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def mask_password(url, secret="*****"):
parsed = urlparse(url)
if not parsed.password:
return url
elif parsed.password == "x-oauth-basic":
return url.replace(parsed.username, secret)
return url.replace(parsed.password, secret)
def parse_args(args=None):
parser = argparse.ArgumentParser(description="Backup a github account")
parser.add_argument("user", metavar="USER", type=str, help="github username")
parser.add_argument(
"-u", "--username", dest="username", help="username for basic auth"
)
parser.add_argument(
"-p",
"--password",
dest="password",
help="password for basic auth. "
"If a username is given but not a password, the "
"password will be prompted for.",
)
parser.add_argument(
"-t",
"--token",
dest="token_classic",
help="personal access, OAuth, or JSON Web token, or path to token (file://...)",
) # noqa
parser.add_argument(
"-f",
"--token-fine",
dest="token_fine",
help="fine-grained personal access token (github_pat_....), or path to token (file://...)",
) # noqa
parser.add_argument(
"-q",
"--quiet",
action="store_true",
dest="quiet",
help="supress log messages less severe than warning, e.g. info",
)
parser.add_argument(
"--as-app",
action="store_true",
dest="as_app",
help="authenticate as github app instead of as a user.",
)
parser.add_argument(
"-o",
"--output-directory",
default=".",
dest="output_directory",
help="directory at which to backup the repositories",
)
parser.add_argument(
"-l",
"--log-level",
default="info",
dest="log_level",
help="log level to use (default: info, possible levels: debug, info, warning, error, critical)",
)
parser.add_argument(
"-i",
"--incremental",
action="store_true",
dest="incremental",
help="incremental backup",
)
parser.add_argument(
"--incremental-by-files",
action="store_true",
dest="incremental_by_files",
help="incremental backup based on modification date of files",
)
parser.add_argument(
"--starred",
action="store_true",
dest="include_starred",
help="include JSON output of starred repositories in backup",
)
parser.add_argument(
"--all-starred",
action="store_true",
dest="all_starred",
help="include starred repositories in backup [*]",
)
parser.add_argument(
"--watched",
action="store_true",
dest="include_watched",
help="include JSON output of watched repositories in backup",
)
parser.add_argument(
"--followers",
action="store_true",
dest="include_followers",
help="include JSON output of followers in backup",
)
parser.add_argument(
"--following",
action="store_true",
dest="include_following",
help="include JSON output of following users in backup",
)
parser.add_argument(
"--all",
action="store_true",
dest="include_everything",
help="include everything in backup (not including [*])",
)
parser.add_argument(
"--issues",
action="store_true",
dest="include_issues",
help="include issues in backup",
)
parser.add_argument(
"--issue-comments",
action="store_true",
dest="include_issue_comments",
help="include issue comments in backup",
)
parser.add_argument(
"--issue-events",
action="store_true",
dest="include_issue_events",
help="include issue events in backup",
)
parser.add_argument(
"--pulls",
action="store_true",
dest="include_pulls",
help="include pull requests in backup",
)
parser.add_argument(
"--pull-comments",
action="store_true",
dest="include_pull_comments",
help="include pull request review comments in backup",
)
parser.add_argument(
"--pull-commits",
action="store_true",
dest="include_pull_commits",
help="include pull request commits in backup",
)
parser.add_argument(
"--pull-details",
action="store_true",
dest="include_pull_details",
help="include more pull request details in backup [*]",
)
parser.add_argument(
"--labels",
action="store_true",
dest="include_labels",
help="include labels in backup",
)
parser.add_argument(
"--hooks",
action="store_true",
dest="include_hooks",
help="include hooks in backup (works only when authenticated)",
) # noqa
parser.add_argument(
"--milestones",
action="store_true",
dest="include_milestones",
help="include milestones in backup",
)
parser.add_argument(
"--repositories",
action="store_true",
dest="include_repository",
help="include repository clone in backup",
)
parser.add_argument(
"--bare", action="store_true", dest="bare_clone", help="clone bare repositories"
)
parser.add_argument(
"--no-prune",
action="store_true",
dest="no_prune",
help="disable prune option for git fetch",
)
parser.add_argument(
"--lfs",
action="store_true",
dest="lfs_clone",
help="clone LFS repositories (requires Git LFS to be installed, https://git-lfs.github.com) [*]",
)
parser.add_argument(
"--wikis",
action="store_true",
dest="include_wiki",
help="include wiki clone in backup",
)
parser.add_argument(
"--gists",
action="store_true",
dest="include_gists",
help="include gists in backup [*]",
)
parser.add_argument(
"--starred-gists",
action="store_true",
dest="include_starred_gists",
help="include starred gists in backup [*]",
)
parser.add_argument(
"--skip-archived",
action="store_true",
dest="skip_archived",
help="skip project if it is archived",
)
parser.add_argument(
"--skip-existing",
action="store_true",
dest="skip_existing",
help="skip project if a backup directory exists",
)
parser.add_argument(
"-L",
"--languages",
dest="languages",
help="only allow these languages",
nargs="*",
)
parser.add_argument(
"-N",
"--name-regex",
dest="name_regex",
help="python regex to match names against",
)
parser.add_argument(
"-H", "--github-host", dest="github_host", help="GitHub Enterprise hostname"
)
parser.add_argument(
"-O",
"--organization",
action="store_true",
dest="organization",
help="whether or not this is an organization user",
)
parser.add_argument(
"-R",
"--repository",
dest="repository",
help="name of repository to limit backup to",
)
parser.add_argument(
"-P",
"--private",
action="store_true",
dest="private",
help="include private repositories [*]",
)
parser.add_argument(
"-F",
"--fork",
action="store_true",
dest="fork",
help="include forked repositories [*]",
)
parser.add_argument(
"--prefer-ssh",
action="store_true",
help="Clone repositories using SSH instead of HTTPS",
)
parser.add_argument(
"-v", "--version", action="version", version="%(prog)s " + VERSION
)
parser.add_argument(
"--keychain-name",
dest="osx_keychain_item_name",
help="OSX ONLY: name field of password item in OSX keychain that holds the personal access or OAuth token",
)
parser.add_argument(
"--keychain-account",
dest="osx_keychain_item_account",
help="OSX ONLY: account field of password item in OSX keychain that holds the personal access or OAuth token",
)
parser.add_argument(
"--releases",
action="store_true",
dest="include_releases",
help="include release information, not including assets or binaries",
)
parser.add_argument(
"--latest-releases",
type=int,
default=0,
dest="number_of_latest_releases",
help="include certain number of the latest releases; only applies if including releases",
)
parser.add_argument(
"--skip-prerelease",
action="store_true",
dest="skip_prerelease",
help="skip prerelease and draft versions; only applies if including releases",
)
parser.add_argument(
"--assets",
action="store_true",
dest="include_assets",
help="include assets alongside release information; only applies if including releases",
)
parser.add_argument(
"--attachments",
action="store_true",
dest="include_attachments",
help="download user-attachments from issues and pull requests",
)
parser.add_argument(
"--throttle-limit",
dest="throttle_limit",
type=int,
default=0,
help="start throttling of GitHub API requests after this amount of API requests remain",
)
parser.add_argument(
"--throttle-pause",
dest="throttle_pause",
type=float,
default=30.0,
help="wait this amount of seconds when API request throttling is active (default: 30.0, requires --throttle-limit to be set)",
)
parser.add_argument(
"--exclude", dest="exclude", help="names of repositories to exclude", nargs="*"
)
return parser.parse_args(args)
def get_auth(args, encode=True, for_git_cli=False):
auth = None
if args.osx_keychain_item_name:
if not args.osx_keychain_item_account:
raise Exception(
"You must specify both name and account fields for osx keychain password items"
)
else:
if platform.system() != "Darwin":
raise Exception("Keychain arguments are only supported on Mac OSX")
try:
with open(os.devnull, "w") as devnull:
token = subprocess.check_output(
[
"security",
"find-generic-password",
"-s",
args.osx_keychain_item_name,
"-a",
args.osx_keychain_item_account,
"-w",
],
stderr=devnull,
).strip()
token = token.decode("utf-8")
auth = token + ":" + "x-oauth-basic"
except subprocess.SubprocessError:
raise Exception(
"No password item matching the provided name and account could be found in the osx keychain."
)
elif args.osx_keychain_item_account:
raise Exception(
"You must specify both name and account fields for osx keychain password items"
)
elif args.token_fine:
if args.token_fine.startswith(FILE_URI_PREFIX):
args.token_fine = read_file_contents(args.token_fine)
if args.token_fine.startswith("github_pat_"):
auth = args.token_fine
else:
raise Exception(
"Fine-grained token supplied does not look like a GitHub PAT"
)
elif args.token_classic:
if args.token_classic.startswith(FILE_URI_PREFIX):
args.token_classic = read_file_contents(args.token_classic)
if not args.as_app:
auth = args.token_classic + ":" + "x-oauth-basic"
else:
if not for_git_cli:
auth = args.token_classic
else:
auth = "x-access-token:" + args.token_classic
elif args.username:
if not args.password:
args.password = getpass.getpass()
if encode:
password = args.password
else:
password = urlquote(args.password)
auth = args.username + ":" + password
elif args.password:
raise Exception("You must specify a username for basic auth")
if not auth:
return None
if not encode or args.token_fine is not None:
return auth
return base64.b64encode(auth.encode("ascii"))
def get_github_api_host(args):
if args.github_host:
host = args.github_host + "/api/v3"
else:
host = "api.github.com"
return host
def get_github_host(args):
if args.github_host:
host = args.github_host
else:
host = "github.com"
return host
def read_file_contents(file_uri):
return open(file_uri[len(FILE_URI_PREFIX) :], "rt").readline().strip()
def get_github_repo_url(args, repository):
if repository.get("is_gist"):
if args.prefer_ssh:
# The git_pull_url value is always https for gists, so we need to transform it to ssh form
repo_url = re.sub(
r"^https?:\/\/(.+)\/(.+)\.git$",
r"git@\1:\2.git",
repository["git_pull_url"],
)
repo_url = re.sub(
r"^git@gist\.", "git@", repo_url
) # strip gist subdomain for better hostkey compatibility
else:
repo_url = repository["git_pull_url"]
return repo_url
if args.prefer_ssh:
return repository["ssh_url"]
auth = get_auth(args, encode=False, for_git_cli=True)
if auth:
repo_url = "https://{0}@{1}/{2}/{3}.git".format(
auth if args.token_fine is None else "oauth2:" + auth,
get_github_host(args),
repository["owner"]["login"],
repository["name"],
)
else:
repo_url = repository["clone_url"]
return repo_url
def retrieve_data_gen(args, template, query_args=None, single_request=False):
auth = get_auth(args, encode=not args.as_app)
query_args = get_query_args(query_args)
per_page = 100
page = 0
while True:
if single_request:
request_page, request_per_page = None, None
else:
page = page + 1
request_page, request_per_page = page, per_page
request = _construct_request(
request_per_page,
request_page,
query_args,
template,
auth,
as_app=args.as_app,
fine=True if args.token_fine is not None else False,
) # noqa
r, errors = _get_response(request, auth, template)
status_code = int(r.getcode())
# Check if we got correct data
try:
response = json.loads(r.read().decode("utf-8"))
except IncompleteRead:
logger.warning("Incomplete read error detected")
read_error = True
except json.decoder.JSONDecodeError:
logger.warning("JSON decode error detected")
read_error = True
except TimeoutError:
logger.warning("Tiemout error detected")
read_error = True
else:
read_error = False
# be gentle with API request limit and throttle requests if remaining requests getting low
limit_remaining = int(r.headers.get("x-ratelimit-remaining", 0))
if args.throttle_limit and limit_remaining <= args.throttle_limit:
logger.info(
"API request limit hit: {} requests left, pausing further requests for {}s".format(
limit_remaining, args.throttle_pause
)
)
time.sleep(args.throttle_pause)
retries = 0
while retries < 3 and (status_code == 502 or read_error):
logger.warning("API request failed. Retrying in 5 seconds")
retries += 1
time.sleep(5)
request = _construct_request(
per_page,
page,
query_args,
template,
auth,
as_app=args.as_app,
fine=True if args.token_fine is not None else False,
) # noqa
r, errors = _get_response(request, auth, template)
status_code = int(r.getcode())
try:
response = json.loads(r.read().decode("utf-8"))
read_error = False
except IncompleteRead:
logger.warning("Incomplete read error detected")
read_error = True
except json.decoder.JSONDecodeError:
logger.warning("JSON decode error detected")
read_error = True
except TimeoutError:
logger.warning("Tiemout error detected")
read_error = True
if status_code != 200:
template = "API request returned HTTP {0}: {1}"
errors.append(template.format(status_code, r.reason))
raise Exception(", ".join(errors))
if read_error:
template = "API request problem reading response for {0}"
errors.append(template.format(request))
raise Exception(", ".join(errors))
if len(errors) == 0:
if type(response) is list:
for resp in response:
yield resp
if len(response) < per_page:
break
elif type(response) is dict and single_request:
yield response
if len(errors) > 0:
raise Exception(", ".join(errors))
if single_request:
break
def retrieve_data(args, template, query_args=None, single_request=False):
return list(retrieve_data_gen(args, template, query_args, single_request))
def get_query_args(query_args=None):
if not query_args:
query_args = {}
return query_args
def _get_response(request, auth, template):
retry_timeout = 3
errors = []
# We'll make requests in a loop so we can
# delay and retry in the case of rate-limiting
while True:
should_continue = False
try:
r = urlopen(request, context=https_ctx)
except HTTPError as exc:
errors, should_continue = _request_http_error(exc, auth, errors) # noqa
r = exc
except URLError as e:
logger.warning(e.reason)
should_continue, retry_timeout = _request_url_error(template, retry_timeout)
if not should_continue:
raise
except socket.error as e:
logger.warning(e.strerror)
should_continue, retry_timeout = _request_url_error(template, retry_timeout)
if not should_continue:
raise
if should_continue:
continue
break
return r, errors
def _construct_request(
per_page, page, query_args, template, auth, as_app=None, fine=False
):
all_query_args = {}
if per_page:
all_query_args["per_page"] = per_page
if page:
all_query_args["page"] = page
if query_args:
all_query_args.update(query_args)
request_url = template
if all_query_args:
querystring = urlencode(all_query_args)
request_url = template + "?" + querystring
else:
querystring = ""
request = Request(request_url)
if auth is not None:
if not as_app:
if fine:
request.add_header("Authorization", "token " + auth)
else:
request.add_header("Authorization", "Basic ".encode("ascii") + auth)
else:
auth = auth.encode("ascii")
request.add_header("Authorization", "token ".encode("ascii") + auth)
request.add_header(
"Accept", "application/vnd.github.machine-man-preview+json"
)
log_url = template
if querystring:
log_url += "?" + querystring
logger.info("Requesting {}".format(log_url))
return request
def _request_http_error(exc, auth, errors):
# HTTPError behaves like a Response so we can
# check the status code and headers to see exactly
# what failed.
should_continue = False
headers = exc.headers
limit_remaining = int(headers.get("x-ratelimit-remaining", 0))
if exc.code == 403 and limit_remaining < 1:
# The X-RateLimit-Reset header includes a
# timestamp telling us when the limit will reset
# so we can calculate how long to wait rather
# than inefficiently polling:
gm_now = calendar.timegm(time.gmtime())
reset = int(headers.get("x-ratelimit-reset", 0)) or gm_now
# We'll never sleep for less than 10 seconds:
delta = max(10, reset - gm_now)
limit = headers.get("x-ratelimit-limit")
logger.warning(
"Exceeded rate limit of {} requests; waiting {} seconds to reset".format(
limit, delta
)
) # noqa
if auth is None:
logger.info("Hint: Authenticate to raise your GitHub rate limit")
time.sleep(delta)
should_continue = True
return errors, should_continue
def _request_url_error(template, retry_timeout):
# In case of a connection timing out, we can retry a few time
# But we won't crash and not back-up the rest now
logger.info("'{}' timed out".format(template))
retry_timeout -= 1
if retry_timeout >= 0:
return True, retry_timeout
raise Exception("'{}' timed out to much, skipping!".format(template))
class S3HTTPRedirectHandler(HTTPRedirectHandler):
"""
A subclassed redirect handler for downloading Github assets from S3.
urllib will add the Authorization header to the redirected request to S3, which will result in a 400,
so we should remove said header on redirect.
"""
def redirect_request(self, req, fp, code, msg, headers, newurl):
request = super(S3HTTPRedirectHandler, self).redirect_request(
req, fp, code, msg, headers, newurl
)
# Only delete Authorization header if it exists (attachments may not have it)
if "Authorization" in request.headers:
del request.headers["Authorization"]
return request
def download_file(url, path, auth, as_app=False, fine=False):
# Skip downloading release assets if they already exist on disk so we don't redownload on every sync
if os.path.exists(path):
return
request = _construct_request(
per_page=100,
page=1,
query_args={},
template=url,
auth=auth,
as_app=as_app,
fine=fine,
)
request.add_header("Accept", "application/octet-stream")
opener = build_opener(S3HTTPRedirectHandler)
try:
response = opener.open(request)
chunk_size = 16 * 1024
with open(path, "wb") as f:
while True:
chunk = response.read(chunk_size)
if not chunk:
break
f.write(chunk)
except HTTPError as exc:
# Gracefully handle 404 responses (and others) when downloading from S3
logger.warning(
"Skipping download of asset {0} due to HTTPError: {1}".format(
url, exc.reason
)
)
except URLError as e:
# Gracefully handle other URL errors
logger.warning(
"Skipping download of asset {0} due to URLError: {1}".format(url, e.reason)
)
except socket.error as e:
# Gracefully handle socket errors
# TODO: Implement retry logic
logger.warning(
"Skipping download of asset {0} due to socker error: {1}".format(
url, e.strerror
)
)
def download_attachment_file(url, path, auth, as_app=False, fine=False):
"""Download attachment file directly (not via GitHub API).
Similar to download_file() but for direct file URLs, not API endpoints.
Attachment URLs (user-images, user-attachments) are direct downloads,
not API endpoints, so we skip _construct_request() which adds API params.
URL Format Support & Authentication Requirements:
| URL Format | Auth Required | Notes |
|----------------------------------------------|---------------|--------------------------|
| github.com/user-attachments/assets/* | Private only | Modern format (2024+) |
| github.com/user-attachments/files/* | Private only | Modern format (2024+) |
| user-images.githubusercontent.com/* | No (public) | Legacy CDN, all eras |
| private-user-images.githubusercontent.com/* | JWT in URL | Legacy private (5min) |
| github.com/{owner}/{repo}/files/* | Repo filter | Old repo files |
- Modern user-attachments: Requires GitHub token auth for private repos
- Legacy public CDN: No auth needed/accepted (returns 400 with auth header)
- Legacy private CDN: Uses JWT token embedded in URL, no GitHub token needed
- Repo files: Filtered to current repository only during extraction
Returns dict with metadata:
- success: bool
- http_status: int (200, 404, etc.)
- content_type: str or None
- original_filename: str or None (from Content-Disposition)
- size_bytes: int or None
- error: str or None
"""
import re
from datetime import datetime, timezone
metadata = {
"url": url,
"success": False,
"http_status": None,
"content_type": None,
"original_filename": None,
"size_bytes": None,
"downloaded_at": datetime.now(timezone.utc).isoformat(),
"error": None,
}
# Create simple request (no API query params)
request = Request(url)
request.add_header("Accept", "application/octet-stream")
# Add authentication header only for modern github.com/user-attachments URLs
# Legacy CDN URLs (user-images.githubusercontent.com) are public and don't need/accept auth
# Private CDN URLs (private-user-images) use JWT tokens embedded in the URL
if auth is not None and "github.com/user-attachments/" in url:
if not as_app:
if fine:
# Fine-grained token: plain token with "token " prefix
request.add_header("Authorization", "token " + auth)
else:
# Classic token: base64-encoded with "Basic " prefix
request.add_header("Authorization", "Basic ".encode("ascii") + auth)
else:
# App authentication
auth = auth.encode("ascii")
request.add_header("Authorization", "token ".encode("ascii") + auth)
# Reuse S3HTTPRedirectHandler from download_file()
opener = build_opener(S3HTTPRedirectHandler)
temp_path = path + ".temp"
try:
response = opener.open(request)
metadata["http_status"] = response.getcode()
# Extract Content-Type
content_type = response.headers.get("Content-Type", "").split(";")[0].strip()
if content_type:
metadata["content_type"] = content_type
# Extract original filename from Content-Disposition header
# Format: attachment; filename=example.mov or attachment;filename="example.mov"
content_disposition = response.headers.get("Content-Disposition", "")
if content_disposition:
# Match: filename=something or filename="something" or filename*=UTF-8''something
match = re.search(r'filename\*?=["\']?([^"\';\r\n]+)', content_disposition)
if match:
original_filename = match.group(1).strip()
# Handle RFC 5987 encoding: filename*=UTF-8''example.mov
if "UTF-8''" in original_filename:
original_filename = original_filename.split("UTF-8''")[1]
metadata["original_filename"] = original_filename
# Fallback: Extract filename from final URL after redirects
# This handles user-attachments/assets URLs which redirect to S3 with filename.ext
if not metadata["original_filename"]:
from urllib.parse import urlparse, unquote
final_url = response.geturl()
parsed = urlparse(final_url)
# Get filename from path (last component before query string)
path_parts = parsed.path.split("/")
if path_parts:
# URL might be encoded, decode it
filename_from_url = unquote(path_parts[-1])
# Only use if it has an extension
if "." in filename_from_url:
metadata["original_filename"] = filename_from_url
# Download file to temporary location
chunk_size = 16 * 1024
bytes_downloaded = 0
with open(temp_path, "wb") as f:
while True:
chunk = response.read(chunk_size)
if not chunk:
break
f.write(chunk)
bytes_downloaded += len(chunk)
# Atomic rename to final location
os.rename(temp_path, path)
metadata["size_bytes"] = bytes_downloaded
metadata["success"] = True