-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmvn2get.py
2088 lines (1831 loc) · 81.1 KB
/
mvn2get.py
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/python3
"""
Tool to download artifact files from Maven 2 style repositories.
Run with the `-h` argument for help.
"""
# Requires Python 3.7
# MIT License
#
# Copyright (c) 2019-2020 Groboclown
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from typing import List, Tuple, Dict, Iterable, Mapping, Optional, Callable, Any
import os
import sys
import re
import hashlib
import argparse
import shutil
import time
import threading
import http.client
import json
import xml.dom.minidom
from xml.parsers.expat import (ExpatError)
import ssl
import urllib.request
import urllib.response
from urllib.error import (HTTPError, URLError)
VERSION = '1.0.3'
# ---------------------------------------------------------------------------
# User Configuration
class Config:
"""
User configuration. Can be set through CLI and/or configuration file.
"""
problem_file: Optional[str]
remote_repo_urls: List[str]
local_repo_urls: List[str]
pgp_key_servers: List[str]
acceptable_license_urls: List[str]
acceptable_license_names: List[str]
mislabeled_artifact_groups: Dict[str, Tuple[str, str]]
def __init__(self) -> None:
self._loaded = False
# These can also be set by the CLI arguments
self.outdir = os.path.curdir
self.show_progress = False
self.log_level = LOG_WARN
self.problem_file = None
self.recursive = False
self.overwrite = False
self.do_remote_download = True
self.include_dep_management = False
self.check_in_local = True
self.no_pgp = False
self.clean_violations = False
self.progress_indicators = "|/-\\"
self.remote_repo_urls = list(DEFAULT_REMOTE_REPO_URLS)
self.local_repo_urls = []
self.pgp_key_servers = list(DEFAULT_PGP_KEY_SERVERS)
self.acceptable_license_urls = list(DEFAULT_ACCEPTABLE_LICENSE_URLS)
self.acceptable_license_names = list(DEFAULT_ACCEPTABLE_LICENSE_NAMES)
self.allow_unacceptable_licenses = True
self.allow_no_license = True
self.mislabeled_artifact_groups = DEFAULT_MISLABELED_ARTIFACT_GROUP
def can_log(self, level: str) -> int:
return LOG_MAP[self.log_level] >= LOG_MAP[level]
def load(self, filename: str) -> None:
if not os.path.isfile(filename) or self._loaded:
return
with open(filename, 'r') as f:
data = json.load(f)
self._loaded = True
self._set_str(data, 'outdir')
self._set_bool(data, 'show_progress')
self._set_str_of(data, 'log_level', LOG_MAP.keys())
self._set_str(data, 'problem_file')
self._set_bool(data, 'recursive')
self._set_bool(data, 'overwrite')
self._set_bool(data, 'do_remote_download')
self._set_bool(data, 'include_dep_management')
self._set_bool(data, 'check_in_local')
self._set_bool(data, 'no_pgp')
self._set_str(data, 'progress_indicators')
self._set_list_of_str(data, 'remote_repo_urls')
self._set_list_of_str(data, 'local_repo_urls')
self._set_list_of_str(data, 'pgp_key_servers')
self._set_list_of_str(data, 'acceptable_license_urls')
self._set_list_of_str(data, 'acceptable_license_names')
self._set_bool(data, "allow_unacceptable_licenses")
self._set_bool(data, "allow_no_license")
# One-off, complex type.
mag_val = data.get("mislabeled_artifact_groups", None)
if isinstance(mag_val, Mapping):
replace = True
replaced_mag: Dict[str, Tuple[str, str]] = {}
for key, val in mag_val.items():
if (
isinstance(key, str)
and not isinstance(val, str)
and isinstance(val, Iterable)
):
val_list = list(val)
if (
len(val_list) == 2
and isinstance(val_list[0], str)
and isinstance(val_list[1], str)
):
replaced_mag[key] = (val_list[0], val_list[1])
continue
replace = False
break
if replace:
self.mislabeled_artifact_groups = replaced_mag
def _set_str(self, data: Dict[str, Any], key: str) -> None:
val = data.get(key, None)
if isinstance(val, str):
setattr(self, key, val)
def _set_str_of(self, data: Dict[str, Any], key: str, values: Iterable[str]) -> None:
val = data.get(key, None)
if val in values:
setattr(self, key, val)
def _set_list_of_str(self, data: Dict[str, Any], key: str) -> None:
val = data.get(key, None)
if isinstance(val, Iterable):
conv: List[str] = []
for check in val:
if isinstance(check, str):
conv.append(check)
else:
return
setattr(self, key, conv)
def _set_bool(self, data: Dict[str, Any], key: str) -> None:
val = data.get(key, None)
if val in (True, False):
setattr(self, key, val)
# ---------------------------------------------------------------------------
# GPG Compatibility
GPG_INST: Optional[Any] = None
try:
import gnupg
def setup_gpg(outdir: str) -> None:
global GPG_INST
try:
# Different versions of gnupg have different constructors.
try:
GPG_INST = gnupg.GPG(homedir=os.path.join(outdir, '.gnupg'))
except TypeError:
GPG_INST = gnupg.GPG(gnupghome=os.path.join(outdir, '.gnupg'))
except RuntimeError:
# This is thrown if GnuPG binary cannot be found.
GPG_INST = None
except ModuleNotFoundError:
# noinspection PyUnusedLocal
def setup_gpg(outdir: str) -> None:
pass
# ---------------------------------------------------------------------------
# Basic Logging Declarations
LOG_WARN = 'warn'
LOG_INFO = 'info'
LOG_DEBUG = 'debug'
LOG_TRACE = 'trace'
LOG_MAP = {
LOG_WARN: 0,
LOG_INFO: 1,
LOG_DEBUG: 2,
LOG_TRACE: 3,
}
PROGRESS_INDEX = [0]
class Problem:
__slots__ = ('msg', 'artifact_id', 'files', 'file_violation',)
def __init__(self, artifact_id: str, files: Iterable[str], file_violation: bool, msg: str) -> None:
self.msg = msg
self.artifact_id = artifact_id
self.files = list(files)
self.file_violation = file_violation
def __str__(self) -> str:
if self.file_violation:
return 'VIOLATION {0} - {1}'.format(self.artifact_id, self.msg)
return '{0} - {1}'.format(self.artifact_id, self.msg)
def json(self) -> Dict[str, Any]:
return {
"msg": self.msg,
"artifact": self.artifact_id,
"files": list(self.files),
"file_violation": self.file_violation
}
def clean_violations(self) -> None:
if self.file_violation and CONFIG.clean_violations:
for f in self.files:
if os.path.isfile(f):
info("{0} - file in violation of policies; removing {1}".format(self.artifact_id, f))
delete_file(f)
def __eq__(self, other: object) -> bool:
if not isinstance(other, Problem):
return False
return (
self.msg == other.msg and
self.artifact_id == other.artifact_id and
self.files == other.files and
self.file_violation == other.file_violation
)
def __ne__(self, other: object) -> bool:
return not self.__eq__(other)
PROBLEMS: List[Problem] = []
def add_problem(artifact_id: str, files: Iterable[str], file_violation: bool, msg: str) -> None:
PROBLEMS.append(Problem(artifact_id, files, file_violation, msg))
# Windows / Linux / etc os support
if sys.platform == 'win32':
try:
# Windows 10 ANSI support
import ctypes
kernel32 = ctypes.windll.kernel32
kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7)
EOL = "\033[K\n"
PROGRESS_EOL = "\033[K\r"
except AttributeError:
# Not Windows 10
EOL = "\n"
PROGRESS_EOL = "\r"
else:
EOL = "\033[K\n"
PROGRESS_EOL = "\033[K\r"
# TODO find a better exception to trap here.
# noinspection PyBroadException
try:
COLUMN_COUNT, LINE_COUNT = shutil.get_terminal_size(fallback=(-1, -1))
except BaseException:
COLUMN_COUNT = -1
LINE_COUNT = -1
# ---------------------------------------------------------------------------
# Configuration Defaults
DEFAULT_CONFIGURATION_FILE_NAME = '.mvn2get.json'
DEFAULT_LOG_LEVEL = LOG_WARN
DEFAULT_REMOTE_REPO_URLS = (
'https://repo1.maven.org/maven2/',
'https://www.mvnrepository.com/artifact/',
'https://plugins.gradle.org/m2/',
)
DEFAULT_PGP_KEY_SERVERS = (
'hkp://pool.sks-keyservers.net',
'hkps://hkps.pool.sks-keyservers.net'
)
# If a group ID can't be found, and the artifact starts with this key, then
# use this as the group ID and key replacement.
DEFAULT_MISLABELED_ARTIFACT_GROUP = {
"org.apache.felix.": ("org.apache.felix", "",),
"org.osgi.": ("org.osgi", "org.osgi.",),
"wagon-http-shared": ("org.apache.maven.wagon", "wagon-http-shared",),
}
# ACCEPTABLE LICENSES
# Use:
# Licenses that have the license description in the URL must go in the
# URLS group. Those that just reference a general "license" url, and just
# references the project name, should go under the license name, if possible.
DEFAULT_ACCEPTABLE_LICENSE_URLS = (
# Apache Software License, any version.
'http://www.apache.org/licenses/',
# Apache Software License, version 1.1
'http://www.apache.org/licenses/LICENSE-1.1',
# Apache Software License, version 2
'http://opensource.org/licenses/apache2.0.php',
'http://opensource.org/licenses/Apache-2.0',
'http://www.opensource.org/licenses/apache2.0.php',
'http://www.apache.org/licenses/LICENSE-2.0',
'http://www.apache.org/licenses/LICENSE-2.0.txt',
'http://www.apache.org/license/LICENSE-2.0.txt',
'http://www.apache.org/licenses/LICENSE-2.0.html',
'https://www.apache.org/licenses/LICENSE-2.0',
'http://www.scala-lang.org/downloads/license.html', # prior to December 2018, this was BSD 3-clause
'https://www.apache.org/licenses/LICENSE-2.0.txt',
'https://raw.github.com/jsr107/jsr107spec/master/LICENSE.txt',
# Apple License
'http://developer.apple.com/library/mac/#samplecode/AppleJavaExtensions/Listings/README_txt.html#//apple_ref/doc/uid/DTS10000677-README_txt-DontLinkElementID_3',
# BSD (unknown clause count)
'http://xmlunit.svn.sourceforge.net/viewvc/*checkout*/xmlunit/trunk/xmlunit/LICENSE.txt',
'http://jdbc.postgresql.org/license.html',
'http://antlr.org/license.html',
'http://www.antlr.org/license.html',
'http://en.wikipedia.org/wiki/BSD_licenses',
# BSD-2-Clause
'https://jdbc.postgresql.org/about/license.html',
'http://www.opensource.org/licenses/bsd-license.php',
'http://www.opensource.org/licenses/bsd-license.html',
'http://opensource.org/licenses/BSD-2-Clause',
# BSD 3-Clause
'http://www.scala-lang.org/license.html',
'http://opensource.org/licenses/BSD-3-Clause',
'http://asm.ow2.org/license.html',
'https://asm.ow2.io/license.html',
'http://asm.objectweb.org/license.html',
'https://github.com/scodec/scodec-bits/blob/master/LICENSE',
'https://github.com/sbt/test-interface/blob/master/LICENSE',
'http://www.antlr.org/license.html',
'http://jaxen.codehaus.org/license.html',
# jaxen.codehaus.org license URL is no longer valid, it's now located at:
'https://github.com/codehaus/jaxen/blob/master/jaxen/LICENSE.txt',
# New BSD 3-Clause License
'http://dist.codehaus.org/janino/new_bsd_license.txt',
'https://github.com/dom4j/dom4j/blob/master/LICENSE',
'http://www.jcraft.com/jzlib/LICENSE.txt',
'http://www.jcraft.com/jsch/LICENSE.txt',
'http://treelayout.googlecode.com/files/LICENSE.TXT',
# The MIT License
'http://objenesis.googlecode.com/svn/docs/license.html',
'https://github.com/mockito/mockito/blob/master/LICENSE',
'http://github.com/mockito/mockito/blob/master/LICENSE',
'http://code.google.com/p/mockito/wiki/License',
'http://www.opensource.org/licenses/mit-license.php',
'http://www.opensource.org/licenses/mit-license.html',
'http://opensource.org/licenses/MIT',
'https://opensource.org/licenses/MIT',
'http://www.opensource.org/licenses/MIT',
'https://raw.github.com/tatsuhiro-t/argparse4j/master/LICENSE.txt',
# Common Public License Version 1.0
'http://www.opensource.org/licenses/cpl1.0.txt',
# Bouncy Castle Licence
# : "Please note this should be read in the same way as the MIT license."
'http://www.bouncycastle.org/licence.html',
# Mozilla Public License, Version 1.0
'http://www.mozilla.org/MPL/MPL-1.0.txt',
# Mozilla Public License, Version 1.1
'http://www.mozilla.org/MPL/MPL-1.1.html',
# Mozilla Public License, Version 2.0
'http://www.mozilla.org/MPL/2.0/index.txt',
# Common Development and Distribution License (CDDL) v1.0, 1.1
'https://glassfish.dev.java.net/public/CDDLv1.0.html',
'http://www.sun.com/cddl/cddl.html',
'http://www.sun.com/cddl',
'http://repository.jboss.org/licenses/cddl.txt',
'http://www.opensource.org/licenses/cddl1.php',
'https://oss.oracle.com/licenses/CDDL+GPL-1.1',
# CDDL + GPLv2 with classpath exception
'http://glassfish.dev.java.net/nonav/public/CDDL+GPL.html',
'https://glassfish.dev.java.net/public/CDDL+GPL.html',
'https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html',
'https://glassfish.dev.java.net/nonav/public/CDDL+GPL.html',
'http://glassfish.java.net/public/CDDL+GPL_1_1.html',
'https://glassfish.java.net/public/CDDL+GPL_1_1.html',
'https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html',
'https://glassfish.java.net/nonav/public/CDDL+GPL_1_1.html',
'http://glassfish.java.net/public/CDDL+GPL.html',
# Eclipse Distribution License - v 1.0
'http://www.eclipse.org/org/documents/edl-v10.php',
# Eclipse Public License 1.0
'http://www.eclipse.org/legal/epl-v10.html',
'http://opensource.org/licenses/eclipse-1.0.php',
'http://www.spdx.org/licenses/EPL-1.0',
# Eclipse Public License 2.0
'http://www.eclipse.org/legal/epl-v20.html',
'https://www.eclipse.org/legal/epl-v20.html',
'http://www.eclipse.org/legal/epl-2.0',
'https://www.eclipse.org/org/documents/epl-2.0/EPL-2.0.txt',
# The PostgreSQL License
'http://www.postgresql.org/about/licence/',
# WTFPL
'http://www.wtfpl.net/',
# The JSON License
'http://json.org/license.html',
'http://www.json.org/license.html',
# HSQLDB License, similar to BSD-3 Clause
'http://hsqldb.org/web/hsqlLicense.html',
# Public Domain
'http://creativecommons.org/licenses/publicdomain',
'http://www.xmlpull.org/v1/download/unpacked/LICENSE.txt',
# Creative Commons Zero (CC0)
'http://creativecommons.org/publicdomain/zero/1.0/',
# GNU Lesser General Public License (unversioned)
'http://www.gnu.org/licenses/lgpl.txt',
'http://www.gnu.org/licenses/lgpl.html',
'http://www.gnu.org/copyleft/lesser.html',
# GNU Lesser General Public License 2.1
'http://www.gnu.org/licenses/lgpl-2.1.html',
'https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html',
# GNU Lesser General Public License 3.0
'http://www.gnu.org/licenses/lgpl-3.0.txt',
'http://www.gnu.org/licenses/lgpl-2.1.html',
# Mozilla Public License 2.0
'http://www.mozilla.org/MPL/2.0/',
# Mozilla Public License 2.0 or Eclipse Public License 1.0
'http://h2database.com/html/license.html',
# Not currently allowed.
# GNU General Public License (GPL), version 2, with the Classpath exception
# 'http://openjdk.java.net/legal/gplv2+ce.html',
# 'https://www.gnu.org/software/classpath/license.html',
# 'http://repository.jboss.org/licenses/gpl-2.0-ce.txt',
# Not currently allowed.
# GNU General Public License (GPL)
# 'http://www.gnu.org/licenses/gpl.txt',
# 'http://www.gnu.org/licenses/old-licenses/gpl-2.0.html',
# Generic GNU license doesn't tell us what's what.
# 'http://www.gnu.org/licenses/licenses.html',
# Not currently allowed.
# Gatling Highcharts License
# https://raw.githubusercontent.com/gatling/gatling-highcharts/master/LICENSE
)
DEFAULT_ACCEPTABLE_LICENSE_NAMES = (
# Apache License Version 2.0
'Apache License',
'Apache License Version 2.0',
'Apache License, Version 2.0',
'Apache Version 2.0, January 2004',
'The Apache Software License, Version 2.0',
# Public Domain
'Public Domain',
# A BSD license
'BSD License (FreeBSD)',
'BSD',
'BSD License',
'The BSD 2-Clause License',
'The New BSD License',
# BSD-3-Clause
# see http://jtidy.sourceforge.net/license.html
# but it is reported as being at an inactive URL:
# http://svn.sourceforge.net/viewvc/*checkout*/jtidy/trunk/jtidy/LICENSE.txt?revision=95
'Java HTML Tidy License',
# MIT License
'The MIT License',
'MIT License',
# CDDL licenses.
'CDDL + GPLv2 with classpath exception',
'CDDL/GPLv2+CE',
)
# ---------------------------------------------------------------------------
# Configuration
CONFIG = Config()
# ---------------------------------------------------------------------------
# General Constants
FULL_LINK_PATTERN = re.compile(r'<a\s+(.*?)>\s*(.*?)\s*</a>')
HREF_PATTERN = re.compile(r'href\s*=\s*["\'](.*?)["\']')
# ---------------------------------------------------------------------------
# Download File Code
SSL_CONTEXT = ssl.create_default_context()
def urlopen(url: str) -> Any:
# urllib.request.urlopen has no formal type...
if SSL_CONTEXT is None:
return urllib.request.urlopen(url)
else:
return urllib.request.urlopen(url, context=SSL_CONTEXT)
class ToDownload:
__slots__ = ('url', 'filename', 'overwrite', 'required')
def __init__(self, url: str, filename: str, overwrite: bool, required: bool) -> None:
self.url = url
self.filename = filename
self.overwrite = overwrite
self.required = required
def download_artifact(dest_dir: str, artifact_id: str) -> None:
"""
Base function to download an artifact (as the user specified on the command
line), with all its files, and perform the necessary checking on that
artifact.
"""
warn("{0}".format(artifact_id))
source_urls = convert_to_repo_urls(artifact_id)
if not source_urls:
warn("{0} - skipped".format(artifact_id))
return
found = False
for source_url in source_urls:
info("{0}".format(source_url))
dest_path = os.path.join(dest_dir, maven_artifact_path_for_url(source_url))
if not os.path.isdir(dest_path):
os.makedirs(dest_path)
to_download: List[ToDownload] = []
for filename, required in get_files_in(source_url, dest_dir):
if is_valid_filename(filename):
output_file = os.path.join(dest_path, filename)
file_url = source_url + filename
to_download.append(ToDownload(file_url, output_file, CONFIG.overwrite, required))
else:
info("Skipping file {0} (invalid file)".format(filename))
if not to_download:
# Did not find any files in the current URL.
continue
found = True
download_file_list(to_download)
verify_checksums(artifact_id, dest_path)
deps = get_required_dependencies(dest_dir, dest_path)
if CONFIG.recursive:
for d in deps:
# Work has already been done to check if the dependency is in
# local URL or in the download directory.
info("Downloading required dependency {0} from {1}".format(d, artifact_id))
download_artifact(dest_dir, d)
else:
for d in deps:
add_problem(artifact_id, [], False, "requires missing dependency {0}".format(d))
# At this point, the download was successful. Do not attempt to download again.
debug("Found {0} under {1}; no more download attempts.".format(artifact_id, source_url))
break
if not found:
add_problem(artifact_id, [], False, "Did not find any artifact at {0}".format(source_urls))
def download_file_list(artifact_list: List[ToDownload]) -> None:
"""
Takes a list of dicts (args for download) and
downloads the files. This will attempt to use threading to download the
files in parallel. The function will return when all the artifacts have
been downloaded.
"""
def _da(to_download: ToDownload) -> None:
info(" -> {0}".format(to_download.url))
debug(" ---> {0}".format(to_download.filename))
try:
progress("downloading {0}".format(to_download.url))
trace("Downloading {0}".format(to_download.url))
download(
to_download.url, to_download.filename, to_download.overwrite,
show_404=to_download.required
)
except BaseException:
# Assume the download died part-way through. We can't guarantee
# that the file was downloaded right.
delete_file(to_download.filename)
raise
# TODO check if the file already exists in local repository.
if CONFIG.can_log(LOG_INFO):
# Logging requires sequential download
# Parallel is okay with PROGRESS being on.
for x in artifact_list:
_da(x)
else:
runners: List[Tuple[Callable[[ToDownload], None], ToDownload]] = []
for x in artifact_list:
runners.append((_da, x))
parallel_jobs(runners)
def download(url: str, filename: str, overwrite: bool, show_errors: bool = True, show_404: bool = True) -> bool:
"""
Download from the URL to the file.
"""
if os.path.isfile(filename):
if overwrite:
debug("Overwriting existing file {0}".format(filename))
delete_file(filename)
else:
debug("Skipping existing file {0}".format(filename))
return True
if not CONFIG.do_remote_download:
for m_url in CONFIG.remote_repo_urls:
if url.startswith(m_url):
return False
try:
retry = 3
last_err: Optional[URLError] = None
while retry > 0:
try:
with open(filename, "wb") as out:
progress("connecting to {0}".format(url))
with urlopen(url) as inp:
progress("downloading from {0}".format(url))
if hasattr(inp, 'data'):
out.write(inp.data)
else:
out.write(inp.read())
return True
except http.client.IncompleteRead:
# Connection terminated. Try again...
pass
except URLError as e:
# If Errno is 11 ("Resource temporarily unavailable"), or
# -2 ("Name or service unknown")
# wait a bit and retry...
if (
'Resource temporarily unavailable' not in str(e.reason)
and 'Name or service not known' not in str(e.reason)
):
debug("URL ({1}) error {2}; reason: {0}".format(e.reason, url, e.errno))
raise
time.sleep(1)
progress("Encountered {0} error. Waiting to try again: {1}".format(str(e), url[url.rindex('/'):]))
last_err = e
retry -= 1
delete_file(filename)
if show_errors:
if last_err:
add_problem(url, [filename], True, "Failed to download: {0} (too many disconnects)".format(last_err))
else:
add_problem(url, [filename], True, "Failed to download (too many disconnects)")
return False
except HTTPError as e:
# Could be a partial download. Don't keep it.
delete_file(filename)
if e.code == 404 or e.code == 308:
if show_404:
add_problem(url, [filename], True, "Failed to download: {0}".format(e))
elif show_errors:
add_problem(url, [filename], True, "Failed to download: {0}".format(e))
return False
except URLError as e:
# Could be a partial download. Don't keep it.
delete_file(filename)
if show_errors:
add_problem(url, [filename], True, "Incorrectly constructed URL")
raise e
return False
except BaseException:
# Could be a partial download. Don't keep it.
delete_file(filename)
warn("Error downloading {0} into {1}".format(url, filename))
raise
def get_files_in(url: str, outdir: str) -> List[Tuple[str, bool]]:
"""
Load the maven repo page for the URL (it should be the directory for the
artifact), and parse the HTML that lists the files. There might be a
more programatic way to do this.
"""
outfile = os.path.join(
tmpdir(outdir),
url.replace(':', '_').replace('/', '_').replace('?', '_').replace('+', '_')
)
if not download(url=url, filename=outfile, overwrite=False, show_errors=True, show_404=False):
return []
with open(outfile, 'rb') as f:
progress("reading from {0}".format(outfile))
page = f.read().decode('utf-8')
ret: List[str] = []
for a_tag_attributes, display_text in FULL_LINK_PATTERN.findall(page):
# display_text may not show the real link.
href = HREF_PATTERN.search(a_tag_attributes)
if href:
file_url = href.group(1)
if not file_url:
continue
# Some repositories put extra junk in front of the link.
if file_url.startswith('http://') or file_url.startswith('https://'):
file_url = file_url[file_url.rindex('/') + 1:]
while file_url[0] in '/:':
file_url = file_url[1:]
if file_url and not file_url.startswith('..'):
# Just the name of the file; no URL.
ret.append(file_url)
# Some repos do not list the checksum and PGP signatures.
# Explicitly add these to the list.
final_ret: List[Tuple[str, bool]] = []
for file_url in ret:
final_ret.append((file_url, True,))
for ext in VERIFY_FILE_EXTENSIONS:
if file_url.endswith(ext):
continue
extended = file_url + ext
if extended in ret:
continue
# We're guessing that this file exists, so therefore it's not required.
final_ret.append((extended, False,))
return final_ret
def parallel_jobs(callable_list: List[Tuple[Callable[[ToDownload], None], ToDownload]]) -> None:
problems: List[BaseException] = []
waiter = threading.Barrier(len(callable_list) + 1)
def _x(index: int, r: Callable[[ToDownload], None], p: List[BaseException], a: ToDownload) -> None:
try:
trace("Starting {0}".format(index))
r(a)
trace("Ended {0}".format(index))
except BaseException as e:
warn("Exception in {0}: {1}".format(index, e))
p.append(e)
finally:
waiter.wait()
trace("Barrier finished for {0}".format(index))
i = 0
for callback, arg in callable_list:
t = threading.Thread(
target=_x, args=(i, callback, problems, arg), daemon=None
)
t.start()
i += 1
waiter.wait()
if len(problems) > 0:
raise problems[0]
# ---------------------------------------------------------------------------
# Maven 2 Repository Layout
def maven_artifact_path_for_url(url: str) -> str:
"""Get the artifact path for the given maven repo URL."""
for prefix in CONFIG.remote_repo_urls:
if url.startswith(prefix):
return os.path.normpath(url[len(prefix):])
raise ValueError('unknown artifact url ' + str(url))
def convert_to_repo_urls_from_url(src_url: str) -> List[str]:
"""Heuristic to convert a URL into remote maven repo URLs."""
for base_url in [*CONFIG.remote_repo_urls, *CONFIG.local_repo_urls]:
if not src_url.startswith(base_url):
continue
parts = src_url[len(base_url):].split('/')
if parts[-1].endswith(".jar") or parts[-1].endswith(".pom"):
# User could specify a jar or pom artifact, rather than the path.
parts = parts[:-1]
if parts[0].find('.') > 0:
# Some repositories, such as mvnrepository.com, use periods instead of slashes
# for separators in the group name.
parts = [*parts[0].split('.'), *parts[1:]]
ret: List[str] = []
for prefix in CONFIG.remote_repo_urls:
repo_url = prefix + "/".join(parts)
if not repo_url[-1] == '/':
repo_url += '/'
ret.append(repo_url)
return ret
add_problem(src_url, [], False, "Unknown source repository.")
return []
def convert_to_repo_urls(artifact_id: str) -> List[str]:
if artifact_id.startswith("http://") or artifact_id.startswith("https://"):
return convert_to_repo_urls_from_url(artifact_id)
if artifact_id.count(':') == 2:
return convert_to_repo_urls_from_artifact(artifact_id)
add_problem(
artifact_id, [], False,
"Unknown format artifact format. Must be either a maven repo URL or group:artifact:version"
)
return []
def convert_to_repo_urls_from_artifact(aid: str, use_version: bool = True) -> List[str]:
fmt = use_version and "{0}{1}/{2}/{3}/" or "{0}{1}/{2}/"
parts = aid.split(':')
path = parts[0].replace('.', '/')
ret = []
for base_url in CONFIG.remote_repo_urls:
ret.append(fmt.format(base_url, path, parts[1], parts[2]))
return ret
# ---------------------------------------------------------------------------
# Artifact file validation
VERIFY_FILE_EXTENSIONS = ('.md5', '.sha1', '.asc', '.md5.asc', '.sha1.asc', '.asc.md5', '.asc.sha1',)
def verify_checksums(artifact_id: str, dest_path: str) -> None:
"""Perform appropriate verification for the downloaded files."""
for filename in os.listdir(dest_path):
if not (filename.endswith('.sha1') or filename.endswith('.md5')):
path = os.path.join(dest_path, filename)
verify_checksum(artifact_id, path, 'md5')
verify_checksum(artifact_id, path, 'sha1')
# Note: no 'else', because .asc files can have checksums.
if filename.endswith('.asc'):
base_file = os.path.join(dest_path, filename[:-4])
if os.path.isfile(base_file):
verify_pgp(artifact_id, base_file, os.path.join(dest_path, filename))
else:
debug(
" - Downloaded asc file ({0}) with no corresponding signed file (expected {1})".format(
filename, base_file
)
)
def verify_checksum(artifact_id: str, path: str, hash_name: str) -> None:
"""Verify the hash of the source file."""
ck_file = path + '.' + hash_name
if os.path.isfile(ck_file):
progress("verify {0} {1}".format(hash_name, path))
with open(ck_file, "r") as ft:
# Sometimes the file can have newlines at the end, or can be in
# the format 'sha1code filename'
# but it can also be 'MD5(md5code) filename'
ck_parts = ft.read().strip().split(' ')
if len(ck_parts) > 1 and ck_parts[0].lower().startswith(hash_name + '('):
ck_expected = ck_parts[1]
else:
ck_expected = ck_parts[0]
ck = hashlib.new(hash_name)
with open(path, "rb") as fb:
ck.update(fb.read())
if ck.hexdigest() != ck_expected:
add_problem(
artifact_id, [path], True, "{0} {3} does not match downloaded checksum file ({1} vs {2})".format(
path, ck.hexdigest(), ck_expected, hash_name
)
)
elif not path.endswith('.asc'):
# .asc files *should* have a checksum, but often they don't.
info(" !> {0} has no {1} file".format(os.path.basename(path), hash_name))
else:
debug(" !> {0} has no {1} file".format(os.path.basename(path), hash_name))
def verify_pgp(artifact_id: str, src_file: str, signature_file: str) -> None:
if GPG_INST is None or not CONFIG.pgp_key_servers or CONFIG.no_pgp:
debug(" - skipped PGP signature checking of {0}".format(src_file))
return
progress("verify pgp {0}".format(src_file))
with open(signature_file, 'rb') as f:
verify = GPG_INST.verify_file(f, src_file)
# username, key_id, signature_id, fingerprint, trust_level and trust_text
if verify.status == 'no public key':
# Load the public key and try again
debug(" - loading public key {0}".format(verify.key_id))
for key_server in CONFIG.pgp_key_servers:
GPG_INST.recv_keys(key_server, verify.key_id)
with open(signature_file, 'rb') as f:
verify = GPG_INST.verify_file(f, src_file)
if verify.valid:
info(" ~> PGP signature valid for {0}".format(src_file))
debug(" -- key id: {0}, sig id: {1}, fingerprint: {2}, trust: {3}".format(
verify.key_id, verify.signature_id, verify.fingerprint, verify.trust_text))
elif verify.status.lower() == 'no public key':
add_problem(
artifact_id, [src_file, signature_file], True,
"PGP signature could not be validated for {0}: {1}".format(src_file, verify.status)
)
elif verify.status.lower() == 'signature bad':
# Signature in the file is bad, not a failed validation.
add_problem(
artifact_id, [signature_file], True,
"PGP signature validation failed for {0}: signature file is corrupted".format(src_file)
)
elif verify.status.lower() != 'signature valid':
add_problem(
artifact_id, [src_file, signature_file], True,
"PGP signature validation failed for {0}: {1}".format(src_file, verify.status)
)
else:
info(" !> PGP signature not valid, but valid?")
# ---------------------------------------------------------------------------
# POM loading
def get_required_dependencies(outdir: str, path: str) -> List[str]:
progress("loading pom file {0}".format(path))
pom = find_downloaded_pom_file(path)
if pom is None:
info(" !> {0} has no pom file".format(path))
return []
debug("loaded pom {0}".format(pom.decl.id()))
ret = []
for p in pom.parent_dependencies:
parent = load_parent_pom_tree(outdir, pom, p)
if parent is None:
continue
if parent.missing:
ret.append(parent.decl.id())
for d in pom.dependencies:
if d.optional or d.is_test:
# Skip the dependency
debug("skipping optional or test dependency {0}".format(d.id()))
continue
progress("loading dependent version info for {0}".format(d.id()))
load_version_info(outdir, d)
if d.is_vague_version():
debug("skipping vague version for dependency {0}".format(d.id()))
continue
progress("loading dependent pom {0}".format(d.id()))
if not d.group_id:
if not pom.decl.group_id:
warn("Dependent ({0}) has no group, and current ({1}) has no group".format(d.id(), pom.decl.id()))
d.group_id = pom.decl.group_id
if d.group_id == '${pom.groupId}':
# group not defined; might be a mis-labeled artifact.
for mislabeled_group, group_art_replace in CONFIG.mislabeled_artifact_groups:
if d.artifact_id.startswith(mislabeled_group):
old_id = d.id()
d.group_id = group_art_replace[0]
d.artifact_id = group_art_replace[1] + d.artifact_id[len(mislabeled_group) + 1:]
warn("Dependent ({0}) of ({1}) has no group, but is using a mislabeled artifact; using {2}".format(
old_id, pom.decl.id(), d.id()
))
break
dp = load_pom_file(outdir, d)
if dp is None:
add_problem(