download_from_google_storage.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  1. #!/usr/bin/env python
  2. # Copyright (c) 2012 The Chromium Authors. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. """Download files from Google Storage based on SHA1 sums."""
  6. from __future__ import print_function
  7. import hashlib
  8. import optparse
  9. import os
  10. try:
  11. import Queue as queue
  12. except ImportError: # For Py3 compatibility
  13. import queue
  14. import re
  15. import shutil
  16. import stat
  17. import sys
  18. import tarfile
  19. import threading
  20. import time
  21. import subprocess2
  22. # Env vars that tempdir can be gotten from; minimally, this
  23. # needs to match python's tempfile module and match normal
  24. # unix standards.
  25. _TEMPDIR_ENV_VARS = ('TMPDIR', 'TEMP', 'TMP')
  26. GSUTIL_DEFAULT_PATH = os.path.join(
  27. os.path.dirname(os.path.abspath(__file__)), 'gsutil.py')
  28. # Maps sys.platform to what we actually want to call them.
  29. PLATFORM_MAPPING = {
  30. 'cygwin': 'win',
  31. 'darwin': 'mac',
  32. 'linux': 'linux', # Python 3.3+.
  33. 'linux2': 'linux', # Python < 3.3 uses "linux2" / "linux3".
  34. 'win32': 'win',
  35. 'aix6': 'aix',
  36. 'aix7': 'aix',
  37. }
  38. class FileNotFoundError(IOError):
  39. pass
  40. class InvalidFileError(IOError):
  41. pass
  42. class InvalidPlatformError(Exception):
  43. pass
  44. def GetNormalizedPlatform():
  45. """Returns the result of sys.platform accounting for cygwin.
  46. Under cygwin, this will always return "win32" like the native Python."""
  47. if sys.platform == 'cygwin':
  48. return 'win32'
  49. return sys.platform
  50. # Common utilities
  51. class Gsutil(object):
  52. """Call gsutil with some predefined settings. This is a convenience object,
  53. and is also immutable.
  54. HACK: This object is used directly by the external script
  55. `<depot_tools>/win_toolchain/get_toolchain_if_necessary.py`
  56. """
  57. MAX_TRIES = 5
  58. RETRY_BASE_DELAY = 5.0
  59. RETRY_DELAY_MULTIPLE = 1.3
  60. VPYTHON = 'vpython.bat' if GetNormalizedPlatform() == 'win32' else 'vpython'
  61. def __init__(self, path, boto_path=None, version='4.28'):
  62. if not os.path.exists(path):
  63. raise FileNotFoundError('GSUtil not found in %s' % path)
  64. self.path = path
  65. self.boto_path = boto_path
  66. self.version = version
  67. def get_sub_env(self):
  68. env = os.environ.copy()
  69. if self.boto_path == os.devnull:
  70. env['AWS_CREDENTIAL_FILE'] = ''
  71. env['BOTO_CONFIG'] = ''
  72. elif self.boto_path:
  73. env['AWS_CREDENTIAL_FILE'] = self.boto_path
  74. env['BOTO_CONFIG'] = self.boto_path
  75. if PLATFORM_MAPPING[sys.platform] != 'win':
  76. env.update((x, "/tmp") for x in _TEMPDIR_ENV_VARS)
  77. return env
  78. def call(self, *args):
  79. cmd = [self.VPYTHON, self.path, '--force-version', self.version]
  80. cmd.extend(args)
  81. return subprocess2.call(cmd, env=self.get_sub_env())
  82. def check_call(self, *args):
  83. cmd = [self.VPYTHON, self.path, '--force-version', self.version]
  84. cmd.extend(args)
  85. ((out, err), code) = subprocess2.communicate(
  86. cmd,
  87. stdout=subprocess2.PIPE,
  88. stderr=subprocess2.PIPE,
  89. env=self.get_sub_env())
  90. out = out.decode('utf-8', 'replace')
  91. err = err.decode('utf-8', 'replace')
  92. # Parse output.
  93. status_code_match = re.search('status=([0-9]+)', err)
  94. if status_code_match:
  95. return (int(status_code_match.group(1)), out, err)
  96. if ('You are attempting to access protected data with '
  97. 'no configured credentials.' in err):
  98. return (403, out, err)
  99. if 'matched no objects' in err:
  100. return (404, out, err)
  101. return (code, out, err)
  102. def check_call_with_retries(self, *args):
  103. delay = self.RETRY_BASE_DELAY
  104. for i in xrange(self.MAX_TRIES):
  105. code, out, err = self.check_call(*args)
  106. if not code or i == self.MAX_TRIES - 1:
  107. break
  108. time.sleep(delay)
  109. delay *= self.RETRY_DELAY_MULTIPLE
  110. return code, out, err
  111. def check_platform(target):
  112. """Checks if any parent directory of target matches (win|mac|linux)."""
  113. assert os.path.isabs(target)
  114. root, target_name = os.path.split(target)
  115. if not target_name:
  116. return None
  117. if target_name in ('linux', 'mac', 'win'):
  118. return target_name
  119. return check_platform(root)
  120. def get_sha1(filename):
  121. sha1 = hashlib.sha1()
  122. with open(filename, 'rb') as f:
  123. while True:
  124. # Read in 1mb chunks, so it doesn't all have to be loaded into memory.
  125. chunk = f.read(1024*1024)
  126. if not chunk:
  127. break
  128. sha1.update(chunk)
  129. return sha1.hexdigest()
  130. # Download-specific code starts here
  131. def enumerate_input(input_filename, directory, recursive, ignore_errors, output,
  132. sha1_file, auto_platform):
  133. if sha1_file:
  134. if not os.path.exists(input_filename):
  135. if not ignore_errors:
  136. raise FileNotFoundError(
  137. '{} not found when attempting enumerate files to download.'.format(
  138. input_filename))
  139. print('%s not found.' % input_filename, file=sys.stderr)
  140. with open(input_filename, 'rb') as f:
  141. sha1_match = re.match(b'^([A-Za-z0-9]{40})$', f.read(1024).rstrip())
  142. if sha1_match:
  143. yield (sha1_match.groups(1)[0].decode('utf-8'), output)
  144. return
  145. if not ignore_errors:
  146. raise InvalidFileError('No sha1 sum found in %s.' % input_filename)
  147. print('No sha1 sum found in %s.' % input_filename, file=sys.stderr)
  148. return
  149. if not directory:
  150. yield (input_filename, output)
  151. return
  152. for root, dirs, files in os.walk(input_filename):
  153. if not recursive:
  154. for item in dirs[:]:
  155. dirs.remove(item)
  156. else:
  157. for exclude in ['.svn', '.git']:
  158. if exclude in dirs:
  159. dirs.remove(exclude)
  160. for filename in files:
  161. full_path = os.path.join(root, filename)
  162. if full_path.endswith('.sha1'):
  163. if auto_platform:
  164. # Skip if the platform does not match.
  165. target_platform = check_platform(os.path.abspath(full_path))
  166. if not target_platform:
  167. err = ('--auto_platform passed in but no platform name found in '
  168. 'the path of %s' % full_path)
  169. if not ignore_errors:
  170. raise InvalidFileError(err)
  171. print(err, file=sys.stderr)
  172. continue
  173. current_platform = PLATFORM_MAPPING[sys.platform]
  174. if current_platform != target_platform:
  175. continue
  176. with open(full_path, 'rb') as f:
  177. sha1_match = re.match(b'^([A-Za-z0-9]{40})$', f.read(1024).rstrip())
  178. if sha1_match:
  179. yield (
  180. sha1_match.groups(1)[0].decode('utf-8'),
  181. full_path.replace('.sha1', '')
  182. )
  183. else:
  184. if not ignore_errors:
  185. raise InvalidFileError('No sha1 sum found in %s.' % filename)
  186. print('No sha1 sum found in %s.' % filename, file=sys.stderr)
  187. def _validate_tar_file(tar, prefix):
  188. def _validate(tarinfo):
  189. """Returns false if the tarinfo is something we explicitly forbid."""
  190. if tarinfo.issym() or tarinfo.islnk():
  191. return False
  192. if ('../' in tarinfo.name or
  193. '..\\' in tarinfo.name or
  194. not tarinfo.name.startswith(prefix)):
  195. return False
  196. return True
  197. return all(map(_validate, tar.getmembers()))
  198. def _downloader_worker_thread(thread_num, q, force, base_url,
  199. gsutil, out_q, ret_codes, _verbose, extract,
  200. delete=True):
  201. while True:
  202. input_sha1_sum, output_filename = q.get()
  203. if input_sha1_sum is None:
  204. return
  205. extract_dir = None
  206. if extract:
  207. if not output_filename.endswith('.tar.gz'):
  208. out_q.put('%d> Error: %s is not a tar.gz archive.' % (
  209. thread_num, output_filename))
  210. ret_codes.put((1, '%s is not a tar.gz archive.' % (output_filename)))
  211. continue
  212. extract_dir = output_filename[:-len('.tar.gz')]
  213. if os.path.exists(output_filename) and not force:
  214. if not extract or os.path.exists(extract_dir):
  215. if get_sha1(output_filename) == input_sha1_sum:
  216. continue
  217. # Check if file exists.
  218. file_url = '%s/%s' % (base_url, input_sha1_sum)
  219. (code, _, err) = gsutil.check_call('ls', file_url)
  220. if code != 0:
  221. if code == 404:
  222. out_q.put('%d> File %s for %s does not exist, skipping.' % (
  223. thread_num, file_url, output_filename))
  224. ret_codes.put((1, 'File %s for %s does not exist.' % (
  225. file_url, output_filename)))
  226. else:
  227. # Other error, probably auth related (bad ~/.boto, etc).
  228. out_q.put('%d> Failed to fetch file %s for %s, skipping. [Err: %s]' %
  229. (thread_num, file_url, output_filename, err))
  230. ret_codes.put((1, 'Failed to fetch file %s for %s. [Err: %s]' %
  231. (file_url, output_filename, err)))
  232. continue
  233. # Fetch the file.
  234. out_q.put('%d> Downloading %s...' % (thread_num, output_filename))
  235. try:
  236. if delete:
  237. os.remove(output_filename) # Delete the file if it exists already.
  238. except OSError:
  239. if os.path.exists(output_filename):
  240. out_q.put('%d> Warning: deleting %s failed.' % (
  241. thread_num, output_filename))
  242. code, _, err = gsutil.check_call('cp', file_url, output_filename)
  243. if code != 0:
  244. out_q.put('%d> %s' % (thread_num, err))
  245. ret_codes.put((code, err))
  246. continue
  247. remote_sha1 = get_sha1(output_filename)
  248. if remote_sha1 != input_sha1_sum:
  249. msg = ('%d> ERROR remote sha1 (%s) does not match expected sha1 (%s).' %
  250. (thread_num, remote_sha1, input_sha1_sum))
  251. out_q.put(msg)
  252. ret_codes.put((20, msg))
  253. continue
  254. if extract:
  255. if not tarfile.is_tarfile(output_filename):
  256. out_q.put('%d> Error: %s is not a tar.gz archive.' % (
  257. thread_num, output_filename))
  258. ret_codes.put((1, '%s is not a tar.gz archive.' % (output_filename)))
  259. continue
  260. with tarfile.open(output_filename, 'r:gz') as tar:
  261. dirname = os.path.dirname(os.path.abspath(output_filename))
  262. # If there are long paths inside the tarball we can get extraction
  263. # errors on windows due to the 260 path length limit (this includes
  264. # pwd). Use the extended path syntax.
  265. if sys.platform == 'win32':
  266. dirname = '\\\\?\\%s' % dirname
  267. if not _validate_tar_file(tar, os.path.basename(extract_dir)):
  268. out_q.put('%d> Error: %s contains files outside %s.' % (
  269. thread_num, output_filename, extract_dir))
  270. ret_codes.put((1, '%s contains invalid entries.' % (output_filename)))
  271. continue
  272. if os.path.exists(extract_dir):
  273. try:
  274. shutil.rmtree(extract_dir)
  275. out_q.put('%d> Removed %s...' % (thread_num, extract_dir))
  276. except OSError:
  277. out_q.put('%d> Warning: Can\'t delete: %s' % (
  278. thread_num, extract_dir))
  279. ret_codes.put((1, 'Can\'t delete %s.' % (extract_dir)))
  280. continue
  281. out_q.put('%d> Extracting %d entries from %s to %s' %
  282. (thread_num, len(tar.getmembers()),output_filename,
  283. extract_dir))
  284. tar.extractall(path=dirname)
  285. # Set executable bit.
  286. if sys.platform == 'cygwin':
  287. # Under cygwin, mark all files as executable. The executable flag in
  288. # Google Storage will not be set when uploading from Windows, so if
  289. # this script is running under cygwin and we're downloading an
  290. # executable, it will be unrunnable from inside cygwin without this.
  291. st = os.stat(output_filename)
  292. os.chmod(output_filename, st.st_mode | stat.S_IEXEC)
  293. elif sys.platform != 'win32':
  294. # On non-Windows platforms, key off of the custom header
  295. # "x-goog-meta-executable".
  296. code, out, err = gsutil.check_call('stat', file_url)
  297. if code != 0:
  298. out_q.put('%d> %s' % (thread_num, err))
  299. ret_codes.put((code, err))
  300. elif re.search(r'executable:\s*1', out):
  301. st = os.stat(output_filename)
  302. os.chmod(output_filename, st.st_mode | stat.S_IEXEC)
  303. class PrinterThread(threading.Thread):
  304. def __init__(self, output_queue):
  305. super(PrinterThread, self).__init__()
  306. self.output_queue = output_queue
  307. self.did_print_anything = False
  308. def run(self):
  309. while True:
  310. line = self.output_queue.get()
  311. # It's plausible we want to print empty lines: Explicit `is None`.
  312. if line is None:
  313. break
  314. self.did_print_anything = True
  315. print(line)
  316. def _data_exists(input_sha1_sum, output_filename, extract):
  317. """Returns True if the data exists locally and matches the sha1.
  318. This conservatively returns False for error cases.
  319. Args:
  320. input_sha1_sum: Expected sha1 stored on disk.
  321. output_filename: The file to potentially download later. Its sha1 will be
  322. compared to input_sha1_sum.
  323. extract: Wheather or not a downloaded file should be extracted. If the file
  324. is not extracted, this just compares the sha1 of the file. If the file
  325. is to be extracted, this only compares the sha1 of the target archive if
  326. the target directory already exists. The content of the target directory
  327. is not checked.
  328. """
  329. extract_dir = None
  330. if extract:
  331. if not output_filename.endswith('.tar.gz'):
  332. # This will cause an error later. Conservativly return False to not bail
  333. # out too early.
  334. return False
  335. extract_dir = output_filename[:-len('.tar.gz')]
  336. if os.path.exists(output_filename):
  337. if not extract or os.path.exists(extract_dir):
  338. if get_sha1(output_filename) == input_sha1_sum:
  339. return True
  340. return False
  341. def download_from_google_storage(
  342. input_filename, base_url, gsutil, num_threads, directory, recursive,
  343. force, output, ignore_errors, sha1_file, verbose, auto_platform, extract):
  344. # Tuples of sha1s and paths.
  345. input_data = list(enumerate_input(
  346. input_filename, directory, recursive, ignore_errors, output, sha1_file,
  347. auto_platform))
  348. # Sequentially check for the most common case and see if we can bail out
  349. # early before making any slow calls to gsutil.
  350. if not force and all(
  351. _data_exists(sha1, path, extract) for sha1, path in input_data):
  352. return 0
  353. # Call this once to ensure gsutil's update routine is called only once. Only
  354. # needs to be done if we'll process input data in parallel, which can lead to
  355. # a race in gsutil's self-update on the first call. Note, this causes a
  356. # network call, therefore any fast bailout should be done before this point.
  357. if len(input_data) > 1:
  358. gsutil.check_call('version')
  359. # Start up all the worker threads.
  360. all_threads = []
  361. download_start = time.time()
  362. stdout_queue = queue.Queue()
  363. work_queue = queue.Queue()
  364. ret_codes = queue.Queue()
  365. ret_codes.put((0, None))
  366. for thread_num in range(num_threads):
  367. t = threading.Thread(
  368. target=_downloader_worker_thread,
  369. args=[thread_num, work_queue, force, base_url,
  370. gsutil, stdout_queue, ret_codes, verbose, extract])
  371. t.daemon = True
  372. t.start()
  373. all_threads.append(t)
  374. printer_thread = PrinterThread(stdout_queue)
  375. printer_thread.daemon = True
  376. printer_thread.start()
  377. # Populate our work queue.
  378. for sha1, path in input_data:
  379. work_queue.put((sha1, path))
  380. for _ in all_threads:
  381. work_queue.put((None, None)) # Used to tell worker threads to stop.
  382. # Wait for all downloads to finish.
  383. for t in all_threads:
  384. t.join()
  385. stdout_queue.put(None)
  386. printer_thread.join()
  387. # See if we ran into any errors.
  388. max_ret_code = 0
  389. for ret_code, message in ret_codes.queue:
  390. max_ret_code = max(ret_code, max_ret_code)
  391. if message:
  392. print(message, file=sys.stderr)
  393. # Only print summary if any work was done.
  394. if printer_thread.did_print_anything:
  395. print('Downloading %d files took %1f second(s)' %
  396. (len(input_data), time.time() - download_start))
  397. return max_ret_code
  398. def main(args):
  399. usage = ('usage: %prog [options] target\n'
  400. 'Target must be:\n'
  401. ' (default) a sha1 sum ([A-Za-z0-9]{40}).\n'
  402. ' (-s or --sha1_file) a .sha1 file, containing a sha1 sum on '
  403. 'the first line.\n'
  404. ' (-d or --directory) A directory to scan for .sha1 files.')
  405. parser = optparse.OptionParser(usage)
  406. parser.add_option('-o', '--output',
  407. help='Specify the output file name. Defaults to: '
  408. '(a) Given a SHA1 hash, the name is the SHA1 hash. '
  409. '(b) Given a .sha1 file or directory, the name will '
  410. 'match (.*).sha1.')
  411. parser.add_option('-b', '--bucket',
  412. help='Google Storage bucket to fetch from.')
  413. parser.add_option('-e', '--boto',
  414. help='Specify a custom boto file.')
  415. parser.add_option('-c', '--no_resume', action='store_true',
  416. help='DEPRECATED: Resume download if file is '
  417. 'partially downloaded.')
  418. parser.add_option('-f', '--force', action='store_true',
  419. help='Force download even if local file exists.')
  420. parser.add_option('-i', '--ignore_errors', action='store_true',
  421. help='Don\'t throw error if we find an invalid .sha1 file.')
  422. parser.add_option('-r', '--recursive', action='store_true',
  423. help='Scan folders recursively for .sha1 files. '
  424. 'Must be used with -d/--directory')
  425. parser.add_option('-t', '--num_threads', default=1, type='int',
  426. help='Number of downloader threads to run.')
  427. parser.add_option('-d', '--directory', action='store_true',
  428. help='The target is a directory. '
  429. 'Cannot be used with -s/--sha1_file.')
  430. parser.add_option('-s', '--sha1_file', action='store_true',
  431. help='The target is a file containing a sha1 sum. '
  432. 'Cannot be used with -d/--directory.')
  433. parser.add_option('-g', '--config', action='store_true',
  434. help='Alias for "gsutil config". Run this if you want '
  435. 'to initialize your saved Google Storage '
  436. 'credentials. This will create a read-only '
  437. 'credentials file in ~/.boto.depot_tools.')
  438. parser.add_option('-n', '--no_auth', action='store_true',
  439. help='Skip auth checking. Use if it\'s known that the '
  440. 'target bucket is a public bucket.')
  441. parser.add_option('-p', '--platform',
  442. help='A regular expression that is compared against '
  443. 'Python\'s sys.platform. If this option is specified, '
  444. 'the download will happen only if there is a match.')
  445. parser.add_option('-a', '--auto_platform',
  446. action='store_true',
  447. help='Detects if any parent folder of the target matches '
  448. '(linux|mac|win). If so, the script will only '
  449. 'process files that are in the paths that '
  450. 'that matches the current platform.')
  451. parser.add_option('-u', '--extract',
  452. action='store_true',
  453. help='Extract a downloaded tar.gz file. '
  454. 'Leaves the tar.gz file around for sha1 verification'
  455. 'If a directory with the same name as the tar.gz '
  456. 'file already exists, is deleted (to get a '
  457. 'clean state in case of update.)')
  458. parser.add_option('-v', '--verbose', action='store_true', default=True,
  459. help='DEPRECATED: Defaults to True. Use --no-verbose '
  460. 'to suppress.')
  461. parser.add_option('-q', '--quiet', action='store_false', dest='verbose',
  462. help='Suppresses diagnostic and progress information.')
  463. (options, args) = parser.parse_args()
  464. # Make sure we should run at all based on platform matching.
  465. if options.platform:
  466. if options.auto_platform:
  467. parser.error('--platform can not be specified with --auto_platform')
  468. if not re.match(options.platform, GetNormalizedPlatform()):
  469. if options.verbose:
  470. print('The current platform doesn\'t match "%s", skipping.' %
  471. options.platform)
  472. return 0
  473. # Set the boto file to /dev/null if we don't need auth.
  474. if options.no_auth:
  475. if (set(('http_proxy', 'https_proxy')).intersection(
  476. env.lower() for env in os.environ) and
  477. 'NO_AUTH_BOTO_CONFIG' not in os.environ):
  478. print('NOTICE: You have PROXY values set in your environment, but gsutil'
  479. 'in depot_tools does not (yet) obey them.',
  480. file=sys.stderr)
  481. print('Also, --no_auth prevents the normal BOTO_CONFIG environment'
  482. 'variable from being used.',
  483. file=sys.stderr)
  484. print('To use a proxy in this situation, please supply those settings'
  485. 'in a .boto file pointed to by the NO_AUTH_BOTO_CONFIG environment'
  486. 'variable.',
  487. file=sys.stderr)
  488. options.boto = os.environ.get('NO_AUTH_BOTO_CONFIG', os.devnull)
  489. # Make sure gsutil exists where we expect it to.
  490. if os.path.exists(GSUTIL_DEFAULT_PATH):
  491. gsutil = Gsutil(GSUTIL_DEFAULT_PATH,
  492. boto_path=options.boto)
  493. else:
  494. parser.error('gsutil not found in %s, bad depot_tools checkout?' %
  495. GSUTIL_DEFAULT_PATH)
  496. # Passing in -g/--config will run our copy of GSUtil, then quit.
  497. if options.config:
  498. print('===Note from depot_tools===')
  499. print('If you do not have a project ID, enter "0" when asked for one.')
  500. print('===End note from depot_tools===')
  501. print()
  502. gsutil.check_call('version')
  503. return gsutil.call('config')
  504. if not args:
  505. parser.error('Missing target.')
  506. if len(args) > 1:
  507. parser.error('Too many targets.')
  508. if not options.bucket:
  509. parser.error('Missing bucket. Specify bucket with --bucket.')
  510. if options.sha1_file and options.directory:
  511. parser.error('Both --directory and --sha1_file are specified, '
  512. 'can only specify one.')
  513. if options.recursive and not options.directory:
  514. parser.error('--recursive specified but --directory not specified.')
  515. if options.output and options.directory:
  516. parser.error('--directory is specified, so --output has no effect.')
  517. if (not (options.sha1_file or options.directory)
  518. and options.auto_platform):
  519. parser.error('--auto_platform must be specified with either '
  520. '--sha1_file or --directory')
  521. input_filename = args[0]
  522. # Set output filename if not specified.
  523. if not options.output and not options.directory:
  524. if not options.sha1_file:
  525. # Target is a sha1 sum, so output filename would also be the sha1 sum.
  526. options.output = input_filename
  527. elif options.sha1_file:
  528. # Target is a .sha1 file.
  529. if not input_filename.endswith('.sha1'):
  530. parser.error('--sha1_file is specified, but the input filename '
  531. 'does not end with .sha1, and no --output is specified. '
  532. 'Either make sure the input filename has a .sha1 '
  533. 'extension, or specify --output.')
  534. options.output = input_filename[:-5]
  535. else:
  536. parser.error('Unreachable state.')
  537. base_url = 'gs://%s' % options.bucket
  538. try:
  539. return download_from_google_storage(
  540. input_filename, base_url, gsutil, options.num_threads, options.directory,
  541. options.recursive, options.force, options.output, options.ignore_errors,
  542. options.sha1_file, options.verbose, options.auto_platform,
  543. options.extract)
  544. except FileNotFoundError as e:
  545. print("Fatal error: {}".format(e))
  546. return 1
  547. if __name__ == '__main__':
  548. sys.exit(main(sys.argv))