download_from_google_storage.py 24 KB

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