Skip to content

Commit e23d12d

Browse files
authored
Merge pull request josegonzalez#173 from gallofeliz/make-compatible-python-call
Try to make compatible code with direct Python call ; reduce the hard link of the code with the cli
2 parents f8e1151 + fa7148d commit e23d12d

File tree

2 files changed

+26
-24
lines changed

2 files changed

+26
-24
lines changed

bin/github-backup

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
#!/usr/bin/env python
22

3-
import os
3+
import os, sys, logging
44

55
from github_backup.github_backup import (
66
backup_account,
@@ -9,11 +9,17 @@ from github_backup.github_backup import (
99
filter_repositories,
1010
get_authenticated_user,
1111
log_info,
12+
log_warning,
1213
mkdir_p,
1314
parse_args,
1415
retrieve_repositories,
1516
)
1617

18+
logging.basicConfig(
19+
format='%(asctime)s.%(msecs)03d: %(message)s',
20+
datefmt='%Y-%m-%dT%H:%M:%S',
21+
level=logging.INFO
22+
)
1723

1824
def main():
1925
args = parse_args()
@@ -39,4 +45,8 @@ def main():
3945

4046

4147
if __name__ == '__main__':
42-
main()
48+
try:
49+
main()
50+
except Exception as e:
51+
log_warning(str(e))
52+
sys.exit(1)

github_backup/github_backup.py

Lines changed: 14 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
import select
1818
import subprocess
1919
import sys
20+
import logging
2021
import time
2122
import platform
2223
from urllib.parse import urlparse
@@ -40,15 +41,6 @@
4041
def _get_log_date():
4142
return datetime.datetime.isoformat(datetime.datetime.now())
4243

43-
44-
def log_error(message):
45-
"""
46-
Log message (str) or messages (List[str]) to stderr and exit with status 1
47-
"""
48-
log_warning(message)
49-
sys.exit(1)
50-
51-
5244
def log_info(message):
5345
"""
5446
Log message (str) or messages (List[str]) to stdout
@@ -57,7 +49,7 @@ def log_info(message):
5749
message = [message]
5850

5951
for msg in message:
60-
sys.stdout.write("{0}: {1}\n".format(_get_log_date(), msg))
52+
logging.info(msg)
6153

6254

6355
def log_warning(message):
@@ -68,7 +60,7 @@ def log_warning(message):
6860
message = [message]
6961

7062
for msg in message:
71-
sys.stderr.write("{0}: {1}\n".format(_get_log_date(), msg))
63+
logging.warning(msg)
7264

7365

7466
def logging_subprocess(popenargs,
@@ -140,7 +132,7 @@ def mask_password(url, secret='*****'):
140132
return url.replace(parsed.password, secret)
141133

142134

143-
def parse_args():
135+
def parse_args(args = None):
144136
parser = argparse.ArgumentParser(description='Backup a github account')
145137
parser.add_argument('user',
146138
metavar='USER',
@@ -331,18 +323,18 @@ def parse_args():
331323
type=float,
332324
default=30.0,
333325
help='wait this amount of seconds when API request throttling is active (default: 30.0, requires --throttle-limit to be set)')
334-
return parser.parse_args()
326+
return parser.parse_args(args)
335327

336328

337329
def get_auth(args, encode=True, for_git_cli=False):
338330
auth = None
339331

340332
if args.osx_keychain_item_name:
341333
if not args.osx_keychain_item_account:
342-
log_error('You must specify both name and account fields for osx keychain password items')
334+
raise Exception('You must specify both name and account fields for osx keychain password items')
343335
else:
344336
if platform.system() != 'Darwin':
345-
log_error("Keychain arguments are only supported on Mac OSX")
337+
raise Exception("Keychain arguments are only supported on Mac OSX")
346338
try:
347339
with open(os.devnull, 'w') as devnull:
348340
token = (subprocess.check_output([
@@ -353,9 +345,9 @@ def get_auth(args, encode=True, for_git_cli=False):
353345
token = token.decode('utf-8')
354346
auth = token + ':' + 'x-oauth-basic'
355347
except subprocess.SubprocessError:
356-
log_error('No password item matching the provided name and account could be found in the osx keychain.')
348+
raise Exception('No password item matching the provided name and account could be found in the osx keychain.')
357349
elif args.osx_keychain_item_account:
358-
log_error('You must specify both name and account fields for osx keychain password items')
350+
raise Exception('You must specify both name and account fields for osx keychain password items')
359351
elif args.token:
360352
_path_specifier = 'file://'
361353
if args.token.startswith(_path_specifier):
@@ -377,7 +369,7 @@ def get_auth(args, encode=True, for_git_cli=False):
377369
password = urlquote(args.password)
378370
auth = args.username + ':' + password
379371
elif args.password:
380-
log_error('You must specify a username for basic auth')
372+
raise Exception('You must specify a username for basic auth')
381373

382374
if not auth:
383375
return None
@@ -466,7 +458,7 @@ def retrieve_data_gen(args, template, query_args=None, single_request=False):
466458
if status_code != 200:
467459
template = 'API request returned HTTP {0}: {1}'
468460
errors.append(template.format(status_code, r.reason))
469-
log_error(errors)
461+
raise Exception(', '.join(errors))
470462

471463
response = json.loads(r.read().decode('utf-8'))
472464
if len(errors) == 0:
@@ -479,7 +471,7 @@ def retrieve_data_gen(args, template, query_args=None, single_request=False):
479471
yield response
480472

481473
if len(errors) > 0:
482-
log_error(errors)
474+
raise Exception(', '.join(errors))
483475

484476
if single_request:
485477
break
@@ -582,7 +574,7 @@ def _request_url_error(template, retry_timeout):
582574
if retry_timeout >= 0:
583575
return True
584576

585-
log_error('{} timed out to much, skipping!')
577+
raise Exception('{} timed out to much, skipping!')
586578
return False
587579

588580

@@ -640,7 +632,7 @@ def get_authenticated_user(args):
640632
def check_git_lfs_install():
641633
exit_code = subprocess.call(['git', 'lfs', 'version'])
642634
if exit_code != 0:
643-
log_error('The argument --lfs requires you to have Git LFS installed.\nYou can get it from https://git-lfs.github.com.')
635+
raise Exception('The argument --lfs requires you to have Git LFS installed.\nYou can get it from https://git-lfs.github.com.')
644636

645637

646638
def retrieve_repositories(args, authenticated_user):

0 commit comments

Comments
 (0)