blob: 70c03ad8c9699d90b0b2a164f34fb8462249d3c6 [file] [log] [blame]
Milan Verespej0f182da2019-05-14 16:10:35 +02001#! /usr/bin/env python
2# -*- coding: utf-8 -*-
3
4# COPYRIGHT NOTICE STARTS HERE
5
6# Copyright 2019 © Samsung Electronics Co., Ltd.
7#
8# Licensed under the Apache License, Version 2.0 (the "License");
9# you may not use this file except in compliance with the License.
10# You may obtain a copy of the License at
11#
12# http://www.apache.org/licenses/LICENSE-2.0
13#
14# Unless required by applicable law or agreed to in writing, software
15# distributed under the License is distributed on an "AS IS" BASIS,
16# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17# See the License for the specific language governing permissions and
18# limitations under the License.
19
20# COPYRIGHT NOTICE ENDS HERE
21
22import argparse
23import concurrent.futures
24import hashlib
25import logging
26import os
27import sys
28from retrying import retry
29
30import base
31
32log = logging.getLogger(name=__name__)
33
34
35@retry(stop_max_attempt_number=5, wait_fixed=5000)
36def get_npm(registry, npm_name, npm_version):
37 npm_url = '{}/{}/{}'.format(registry, npm_name, npm_version)
38 npm_req = base.make_get_request(npm_url)
39 npm_json = npm_req.json()
40 tarball_url = npm_json['dist']['tarball']
41 shasum = npm_json['dist']['shasum']
42 tarball_req = base.make_get_request(tarball_url)
43 tarball = tarball_req.content
44 if hashlib.sha1(tarball).hexdigest() == shasum:
45 return tarball
46 else:
47 raise Exception('{}@{}: Wrong checksum. Retrying...'.format(npm_name, npm_version))
48
49
50def download_npm(npm, registry, dst_dir):
51 log.info('Downloading: {}'.format(npm))
52 npm_name, npm_version = npm.split('@')
53 dst_path = '{}/{}-{}.tgz'.format(dst_dir, npm_name, npm_version)
54 try:
55 tarball = get_npm(registry, *npm.split('@'))
56 base.save_to_file(dst_path, tarball)
57 except Exception as err:
58 if os.path.isfile(dst_path):
59 os.remove(dst_path)
Milan Verespej455be472019-05-23 14:21:19 +020060 log.exception('Failed: {}'.format(npm))
Milan Verespej0f182da2019-05-14 16:10:35 +020061 raise err
62 log.info('Downloaded: {}'.format(npm))
63
64
65def missing(npm_set, dst_dir):
66 return {npm for npm in npm_set
67 if not os.path.isfile('{}/{}-{}.tgz'.format(dst_dir, *npm.split('@')))}
68
69
70def download(npm_list, registry, dst_dir, check_mode, progress=None, workers=None):
71 npm_set = base.load_list(npm_list)
72 target_count = len(npm_set)
73 missing_npms = missing(npm_set, dst_dir)
74
75 if check_mode:
76 log.info(base.simple_check_table(npm_set, missing_npms))
77 return 0
78
79 skipping = npm_set - missing_npms
80
81 base.start_progress(progress, len(npm_set), skipping, log)
82 error_count = base.run_concurrent(workers, progress, download_npm, missing_npms, registry, dst_dir)
83
Milan Verespej455be472019-05-23 14:21:19 +020084 base.finish_progress(progress, error_count, log)
Milan Verespej0f182da2019-05-14 16:10:35 +020085 if error_count > 0:
86 log.error('{} packages were not downloaded. Check log for specific failures.'.format(error_count))
Milan Verespej455be472019-05-23 14:21:19 +020087 raise RuntimeError()
Milan Verespej0f182da2019-05-14 16:10:35 +020088
89
90def run_cli():
91 parser = argparse.ArgumentParser(description='Download npm packages from list')
92 parser.add_argument('npm_list', metavar='npm-list',
93 help='File with list of npm packages to download.')
94 parser.add_argument('--registry', '-r', default='https://registry.npmjs.org',
95 help='Download destination')
96 parser.add_argument('--output-dir', '-o', default=os.getcwd(),
97 help='Download destination')
98 parser.add_argument('--check', '-c', action='store_true', default=False,
99 help='Check what is missing. No download.')
100 parser.add_argument('--debug', action='store_true', default=False,
101 help='Turn on debug output')
102 parser.add_argument('--workers', type=int, default=None,
103 help='Set maximum workers for parallel download (default: cores * 5)')
104
105 args = parser.parse_args()
106
107 if args.debug:
108 logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
109 else:
110 logging.basicConfig(stream=sys.stdout, level=logging.INFO, format='%(message)s')
111
112 progress = base.init_progress('npm packages') if not args.check else None
113 sys.exit(download(args.npm_list, args.registry, args.output_dir, args.check, progress,
114 args.workers))
115
116
117if __name__ == '__main__':
118 run_cli()
119