-
Notifications
You must be signed in to change notification settings - Fork 54
/
artifactory.py
executable file
·1285 lines (1046 loc) · 40 KB
/
artifactory.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/env python
# -*- coding: utf-8 -*-
# vim:ts=4:sw=4:expandtab
#
# ==================================================================
#
# Copyright (c) 2005-2014 Parallels Software International, Inc.
# Released under the terms of MIT license (see LICENSE for details)
#
# ==================================================================
#
# pylint: disable=no-self-use, maybe-no-member
""" artifactory: a python module for interfacing with JFrog Artifactory
This module is intended to serve as a logical descendant of pathlib
(https://docs.python.org/3/library/pathlib.html), a Python 3 module
for object-oriented path manipulations. As such, it implements
everything as closely as possible to the origin with few exceptions,
such as stat().
There are PureArtifactoryPath and ArtifactoryPath that can be used
to manipulate artifactory paths. See pathlib docs for details how
pure paths can be used.
"""
import os
import sys
import errno
import pathlib
import collections
import requests
import re
import json
import dateutil.parser
import hashlib
try:
import requests.packages.urllib3 as urllib3
except ImportError:
import urllib3
try:
import configparser
except ImportError:
import ConfigParser as configparser
default_config_path = '~/.artifactory_python.cfg'
global_config = None
def read_config(config_path=default_config_path):
"""
Read configuration file and produce a dictionary of the following structure:
{'<instance1>': {'username': '<user>', 'password': '<pass>',
'verify': <True/False>, 'cert': '<path-to-cert>'}
'<instance2>': {...},
...}
Format of the file:
[https://artifactory-instance.local/artifactory]
username = foo
password = @dmin
verify = false
cert = ~/path-to-cert
config-path - specifies where to read the config from
"""
config_path = os.path.expanduser(config_path)
if not os.path.isfile(config_path):
raise OSError(errno.ENOENT,
"Artifactory configuration file not found: '%s'" %
config_path)
p = configparser.ConfigParser()
p.read(config_path)
result = {}
for section in p.sections():
username = p.get(section, 'username') if p.has_option(section, 'username') else None
password = p.get(section, 'password') if p.has_option(section, 'password') else None
verify = p.getboolean(section, 'verify') if p.has_option(section, 'verify') else True
cert = p.get(section, 'cert') if p.has_option(section, 'cert') else None
result[section] = {'username': username,
'password': password,
'verify': verify,
'cert': cert}
# certificate path may contain '~', and we'd better expand it properly
if result[section]['cert']:
result[section]['cert'] = \
os.path.expanduser(result[section]['cert'])
return result
def read_global_config(config_path=default_config_path):
"""
Attempt to read global configuration file and store the result in
'global_config' variable.
config_path - specifies where to read the config from
"""
global global_config
if global_config is None:
try:
global_config = read_config(config_path)
except OSError:
pass
def without_http_prefix(url):
"""
Returns a URL without the http:// or https:// prefixes
"""
if url.startswith('http://'):
return url[7:]
elif url.startswith('https://'):
return url[8:]
return url
def get_base_url(config, url):
"""
Look through config and try to find best matching base for 'url'
config - result of read_config() or read_global_config()
url - artifactory url to search the base for
"""
if not config:
return None
# First, try to search for the best match
for item in config:
if url.startswith(item):
return item
# Then search for indirect match
for item in config:
if without_http_prefix(url).startswith(without_http_prefix(item)):
return item
def get_config_entry(config, url):
"""
Look through config and try to find best matching entry for 'url'
config - result of read_config() or read_global_config()
url - artifactory url to search the config for
"""
if not config:
return None
# First, try to search for the best match
if url in config:
return config[url]
# Then search for indirect match
for item in config:
if without_http_prefix(item) == without_http_prefix(url):
return config[item]
def get_global_config_entry(url):
"""
Look through global config and try to find best matching entry for 'url'
url - artifactory url to search the config for
"""
read_global_config()
return get_config_entry(global_config, url)
def get_global_base_url(url):
"""
Look through global config and try to find best matching base for 'url'
url - artifactory url to search the base for
"""
read_global_config()
return get_base_url(global_config, url)
def md5sum(filename):
"""
Calculates md5 hash of a file
"""
md5 = hashlib.md5()
with open(filename, 'rb') as f:
for chunk in iter(lambda: f.read(128 * md5.block_size), b''):
md5.update(chunk)
return md5.hexdigest()
def sha1sum(filename):
"""
Calculates sha1 hash of a file
"""
sha1 = hashlib.sha1()
with open(filename, 'rb') as f:
for chunk in iter(lambda: f.read(128 * sha1.block_size), b''):
sha1.update(chunk)
return sha1.hexdigest()
class HTTPResponseWrapper(object):
"""
This class is intended as a workaround for 'requests' module
inability to consume HTTPResponse as a streaming upload source.
I.e. if you want to download data from one url and upload it
to another.
The problem is that underlying code uses seek() and tell() to
calculate stream length, but HTTPResponse throws a NotImplementedError,
according to python file-like object implementation guidelines, since
the stream is obviously non-rewindable.
Another problem arises when requests.put() tries to calculate stream
length with other methods. It tries several ways, including len()
and __len__(), and falls back to reading the whole stream. But
since the stream is not rewindable, by the time it tries to send
actual content, there is nothing left in the stream.
"""
def __init__(self, obj):
self.obj = obj
def __getattr__(self, attr):
"""
Redirect member requests except seek() to original object
"""
if attr in self.__dict__:
return self.__dict__[attr]
if attr == 'seek':
raise AttributeError
return getattr(self.obj, attr)
def __len__(self):
"""
__len__ will be used by requests to determine stream size
"""
return int(self.getheader('content-length'))
def encode_matrix_parameters(parameters):
"""
Performs encoding of url matrix parameters from dictionary to
a string.
See http://www.w3.org/DesignIssues/MatrixURIs.html for specs.
"""
result = []
for param in iter(sorted(parameters)):
if isinstance(parameters[param], (list, tuple)):
value = (';%s=' % (param)).join(parameters[param])
else:
value = parameters[param]
result.append("%s=%s" % (param, value))
return ';'.join(result)
def escape_chars(s):
"""
Performs character escaping of comma, pipe and equals characters
"""
return "".join(['\\' + ch if ch in '=|,' else ch for ch in s])
def encode_properties(parameters):
"""
Performs encoding of url parameters from dictionary to a string. It does
not escape backslash because it is not needed.
See: http://www.jfrog.com/confluence/display/RTF/Artifactory+REST+API#ArtifactoryRESTAPI-SetItemProperties
"""
result = []
for param in iter(sorted(parameters)):
if isinstance(parameters[param], (list, tuple)):
value = ','.join([escape_chars(x) for x in parameters[param]])
else:
value = escape_chars(parameters[param])
result.append("%s=%s" % (param, value))
return '|'.join(result)
class _ArtifactoryFlavour(pathlib._Flavour):
"""
Implements Artifactory-specific pure path manipulations.
I.e. what is 'drive', 'root' and 'path' and how to split full path into
components.
See 'pathlib' documentation for explanation how those are used.
drive: in context of artifactory, it's the base URI like
http://mysite/artifactory
root: repository, e.g. 'libs-snapshot-local' or 'ext-release-local'
path: relative artifact path within the repository
"""
sep = '/'
altsep = '/'
has_drv = True
pathmod = pathlib.posixpath
is_supported = (True)
def parse_parts(self, parts):
drv, root, parsed = super(_ArtifactoryFlavour, self).parse_parts(parts)
return drv, root, parsed
def splitroot(self, part, sep=sep):
"""
Splits path string into drive, root and relative path
Uses '/artifactory/' as a splitting point in URI. Everything
before it, including '/artifactory/' itself is treated as drive.
The next folder is treated as root, and everything else is taken
for relative path.
"""
drv = ''
root = ''
base = get_global_base_url(part)
if base and without_http_prefix(part).startswith(without_http_prefix(base)):
mark = without_http_prefix(base).rstrip(sep)+sep
parts = part.split(mark)
else:
mark = sep+'artifactory'+sep
parts = part.split(mark)
if len(parts) >= 2:
drv = parts[0] + mark.rstrip(sep)
rest = sep + mark.join(parts[1:])
elif part.endswith(mark.rstrip(sep)):
drv = part
rest = ''
else:
rest = part
if not rest:
return drv, '', ''
if rest == sep:
return drv, '', ''
if rest.startswith(sep):
root, _, part = rest[1:].partition(sep)
root = sep + root + sep
return drv, root, part
def casefold(self, string):
"""
Convert path string to default FS case if it's not
case-sensitive. Do nothing otherwise.
"""
return string
def casefold_parts(self, parts):
"""
Convert path parts to default FS case if it's not
case sensitive. Do nothing otherwise.
"""
return parts
def resolve(self, path):
"""
Resolve all symlinks and relative paths in 'path'
"""
return path
def is_reserved(self, _):
"""
Returns True if the file is 'reserved', e.g. device node or socket
For Artifactory there are no reserved files.
"""
return False
def make_uri(self, path):
"""
Return path as URI. For Artifactory this is the same as returning
'path' unmodified.
"""
return path
_artifactory_flavour = _ArtifactoryFlavour()
ArtifactoryFileStat = collections.namedtuple(
'ArtifactoryFileStat',
['ctime',
'mtime',
'created_by',
'modified_by',
'mime_type',
'size',
'sha1',
'md5',
'is_dir',
'children'])
class _ArtifactoryAccessor(pathlib._Accessor):
"""
Implements operations with Artifactory REST API
"""
def rest_get(self, url, params=None, headers=None, auth=None, verify=True, cert=None):
"""
Perform a GET request to url with optional authentication
"""
res = requests.get(url, params=params, headers=headers, auth=auth, verify=verify,
cert=cert)
return res.text, res.status_code
def rest_put(self, url, params=None, headers=None, auth=None, verify=True, cert=None):
"""
Perform a PUT request to url with optional authentication
"""
res = requests.put(url, params=params, headers=headers, auth=auth, verify=verify,
cert=cert)
return res.text, res.status_code
def rest_post(self, url, params=None, headers=None, auth=None, verify=True, cert=None):
"""
Perform a PUT request to url with optional authentication
"""
res = requests.post(url, params=params, headers=headers, auth=auth, verify=verify,
cert=cert)
return res.text, res.status_code
def rest_del(self, url, params=None, auth=None, verify=True, cert=None):
"""
Perform a DELETE request to url with optional authentication
"""
res = requests.delete(url, params=params, auth=auth, verify=verify, cert=cert)
return res.text, res.status_code
def rest_put_stream(self, url, stream, headers=None, auth=None, verify=True, cert=None):
"""
Perform a chunked PUT request to url with optional authentication
This is specifically to upload files.
"""
res = requests.put(url, headers=headers, auth=auth, data=stream, verify=verify, cert=cert)
return res.text, res.status_code
def rest_get_stream(self, url, auth=None, verify=True, cert=None):
"""
Perform a chunked GET request to url with optional authentication
This is specifically to download files.
"""
res = requests.get(url, auth=auth, stream=True, verify=verify, cert=cert)
return res.raw, res.status_code
def get_stat_json(self, pathobj):
"""
Request remote file/directory status info
Returns a json object as specified by Artifactory REST API
"""
url = '/'.join([pathobj.drive,
'api/storage',
str(pathobj.relative_to(pathobj.drive)).strip('/')])
text, code = self.rest_get(url, auth=pathobj.auth, verify=pathobj.verify,
cert=pathobj.cert)
if code == 404 and "Unable to find item" in text:
raise OSError(2, "No such file or directory: '%s'" % url)
if code != 200:
raise RuntimeError(text)
return json.loads(text)
def stat(self, pathobj):
"""
Request remote file/directory status info
Returns an object of class ArtifactoryFileStat.
The following fields are available:
ctime -- file creation time
mtime -- file modification time
created_by -- original uploader
modified_by -- last user modifying the file
mime_type -- MIME type of the file
size -- file size
sha1 -- SHA1 digest of the file
md5 -- MD5 digest of the file
is_dir -- 'True' if path is a directory
children -- list of children names
"""
jsn = self.get_stat_json(pathobj)
is_dir = False
if 'size' not in jsn:
is_dir = True
children = None
if 'children' in jsn:
children = [child['uri'][1:] for child in jsn['children']]
stat = ArtifactoryFileStat(
ctime=dateutil.parser.parse(jsn['created']),
mtime=dateutil.parser.parse(jsn['lastModified']),
created_by=jsn.get('createdBy', None),
modified_by=jsn.get('modifiedBy', None),
mime_type=jsn.get('mimeType', None),
size=int(jsn.get('size', '0')),
sha1=jsn.get('checksums', {'sha1': None})['sha1'],
md5=jsn.get('checksums', {'md5': None})['md5'],
is_dir=is_dir,
children=children)
return stat
def is_dir(self, pathobj):
"""
Returns True if given path is a directory
"""
try:
stat = self.stat(pathobj)
return stat.is_dir
except OSError as exc:
if exc.errno != errno.ENOENT:
raise
return False
def is_file(self, pathobj):
"""
Returns True if given path is a regular file
"""
try:
stat = self.stat(pathobj)
return not stat.is_dir
except OSError as exc:
if exc.errno != errno.ENOENT:
raise
return False
def listdir(self, pathobj):
"""
Returns a list of immediate sub-directories and files in path
"""
stat = self.stat(pathobj)
if not stat.is_dir:
raise OSError(20, "Not a directory: %s" % str(pathobj))
return stat.children
def mkdir(self, pathobj, _):
"""
Creates remote directory
Note that this operation is not recursive
"""
if not pathobj.drive or not pathobj.root:
raise RuntimeError("Full path required: '%s'" % str(pathobj))
if pathobj.exists():
raise OSError(17, "File exists: '%s'" % str(pathobj))
url = str(pathobj) + '/'
text, code = self.rest_put(url, auth=pathobj.auth, verify=pathobj.verify,
cert=pathobj.cert)
if not code == 201:
raise RuntimeError("%s %d" % (text, code))
def rmdir(self, pathobj):
"""
Removes a directory
"""
stat = self.stat(pathobj)
if not stat.is_dir:
raise OSError(20, "Not a directory: '%s'" % str(pathobj))
url = str(pathobj) + '/'
text, code = self.rest_del(url, auth=pathobj.auth, verify=pathobj.verify,
cert=pathobj.cert)
if code not in [200, 202, 204]:
raise RuntimeError("Failed to delete directory: '%s'" % text)
def unlink(self, pathobj):
"""
Removes a file
"""
stat = self.stat(pathobj)
if stat.is_dir:
raise OSError(1, "Operation not permitted: '%s'" % str(pathobj))
url = str(pathobj)
text, code = self.rest_del(url, auth=pathobj.auth, verify=pathobj.verify,
cert=pathobj.cert)
if code not in [200, 202, 204]:
raise RuntimeError("Failed to delete file: %d '%s'" % (code, text))
def touch(self, pathobj):
"""
Create an empty file
"""
if not pathobj.drive or not pathobj.root:
raise RuntimeError('Full path required')
if pathobj.exists():
return
url = str(pathobj)
text, code = self.rest_put(url, auth=pathobj.auth, verify=pathobj.verify,
cert=pathobj.cert)
if not code == 201:
raise RuntimeError("%s %d" % (text, code))
def owner(self, pathobj):
"""
Returns file owner
This makes little sense for Artifactory, but to be consistent
with pathlib, we return modified_by instead, if available
"""
stat = self.stat(pathobj)
if not stat.is_dir:
return stat.modified_by
else:
return 'nobody'
def creator(self, pathobj):
"""
Returns file creator
This makes little sense for Artifactory, but to be consistent
with pathlib, we return created_by instead, if available
"""
stat = self.stat(pathobj)
if not stat.is_dir:
return stat.created_by
else:
return 'nobody'
def open(self, pathobj):
"""
Opens the remote file and returns a file-like object HTTPResponse
Given the nature of HTTP streaming, this object doesn't support
seek()
"""
url = str(pathobj)
raw, code = self.rest_get_stream(url, auth=pathobj.auth, verify=pathobj.verify,
cert=pathobj.cert)
if not code == 200:
raise RuntimeError("%d" % code)
return raw
def deploy(self, pathobj, fobj, md5=None, sha1=None, parameters=None):
"""
Uploads a given file-like object
HTTP chunked encoding will be attempted
"""
if isinstance(fobj, urllib3.response.HTTPResponse):
fobj = HTTPResponseWrapper(fobj)
url = str(pathobj)
if parameters:
url += ";%s" % encode_matrix_parameters(parameters)
headers = {}
if md5:
headers['X-Checksum-Md5'] = md5
if sha1:
headers['X-Checksum-Sha1'] = sha1
text, code = self.rest_put_stream(url,
fobj,
headers=headers,
auth=pathobj.auth,
verify=pathobj.verify,
cert=pathobj.cert)
if code not in [200, 201]:
raise RuntimeError("%s" % text)
def copy(self, src, dst, suppress_layouts=False):
"""
Copy artifact from src to dst
"""
url = '/'.join([src.drive,
'api/copy',
str(src.relative_to(src.drive)).rstrip('/')])
params = {'to': str(dst.relative_to(dst.drive)).rstrip('/'),
'suppressLayouts': int(suppress_layouts)}
text, code = self.rest_post(url,
params=params,
auth=src.auth,
verify=src.verify,
cert=src.cert)
if code not in [200, 201]:
raise RuntimeError("%s" % text)
def move(self, src, dst):
"""
Move artifact from src to dst
"""
url = '/'.join([src.drive,
'api/move',
str(src.relative_to(src.drive)).rstrip('/')])
params = {'to': str(dst.relative_to(dst.drive)).rstrip('/')}
text, code = self.rest_post(url,
params=params,
auth=src.auth,
verify=src.verify,
cert=src.cert)
if code not in [200, 201]:
raise RuntimeError("%s" % text)
def get_properties(self, pathobj):
"""
Get artifact properties and return them as a dictionary.
"""
url = '/'.join([pathobj.drive,
'api/storage',
str(pathobj.relative_to(pathobj.drive)).strip('/')])
params = 'properties'
text, code = self.rest_get(url,
params=params,
auth=pathobj.auth,
verify=pathobj.verify,
cert=pathobj.cert)
if code == 404 and "Unable to find item" in text:
raise OSError(2, "No such file or directory: '%s'" % url)
if code == 404 and "No properties could be found" in text:
return {}
if code != 200:
raise RuntimeError(text)
return json.loads(text)['properties']
def set_properties(self, pathobj, props, recursive):
"""
Set artifact properties
"""
url = '/'.join([pathobj.drive,
'api/storage',
str(pathobj.relative_to(pathobj.drive)).strip('/')])
params = {'properties': encode_properties(props)}
if not recursive:
params['recursive'] = '0'
text, code = self.rest_put(url,
params=params,
auth=pathobj.auth,
verify=pathobj.verify,
cert=pathobj.cert)
if code == 404 and "Unable to find item" in text:
raise OSError(2, "No such file or directory: '%s'" % url)
if code != 204:
raise RuntimeError(text)
def del_properties(self, pathobj, props, recursive):
"""
Delete artifact properties
"""
if isinstance(props, str):
props = (props,)
url = '/'.join([pathobj.drive,
'api/storage',
str(pathobj.relative_to(pathobj.drive)).strip('/')])
params = {'properties': ','.join(sorted(props))}
if not recursive:
params['recursive'] = '0'
text, code = self.rest_del(url,
params=params,
auth=pathobj.auth,
verify=pathobj.verify,
cert=pathobj.cert)
if code == 404 and "Unable to find item" in text:
raise OSError(2, "No such file or directory: '%s'" % url)
if code != 204:
raise RuntimeError(text)
_artifactory_accessor = _ArtifactoryAccessor()
class ArtifactoryProAccessor(_ArtifactoryAccessor):
"""
TODO: implement OpenSource/Pro differentiation
"""
pass
class ArtifactoryOpensourceAccessor(_ArtifactoryAccessor):
"""
TODO: implement OpenSource/Pro differentiation
"""
pass
class PureArtifactoryPath(pathlib.PurePath):
"""
A class to work with Artifactory paths that doesn't connect
to Artifactory server. I.e. it supports only basic path
operations.
"""
_flavour = _artifactory_flavour
__slots__ = ()
class _FakePathTemplate(object):
def __init__(self, accessor):
self._accessor = accessor
class ArtifactoryPath(pathlib.Path, PureArtifactoryPath):
"""
Implements fully-featured pathlib-like Artifactory interface
Unless explicitly mentioned, all methods copy the behaviour
of their pathlib counterparts.
Note that because of peculiarities of pathlib.Path, the methods
that create new path objects, have to also manually set the 'auth'
field, since the copying strategy of pathlib.Path is not based
on regular constructors, but rather on templates.
"""
# Pathlib limits what members can be present in 'Path' class,
# so authentication information has to be added via __slots__
__slots__ = ('auth', 'verify', 'cert')
def __new__(cls, *args, **kwargs):
"""
pathlib.Path overrides __new__ in order to create objects
of different classes based on platform. This magic prevents
us from adding an 'auth' argument to the constructor.
So we have to first construct ArtifactoryPath by Pathlib and
only then add auth information.
"""
obj = pathlib.Path.__new__(cls, *args, **kwargs)
cfg_entry = get_global_config_entry(obj.drive)
obj.auth = kwargs.get('auth', None)
obj.cert = kwargs.get('cert', None)
if obj.auth is None and cfg_entry:
obj.auth = (cfg_entry['username'], cfg_entry['password'])
if obj.cert is None and cfg_entry:
obj.cert = cfg_entry['cert']
if 'verify' in kwargs:
obj.verify = kwargs.get('verify')
elif cfg_entry:
obj.verify = cfg_entry['verify']
else:
obj.verify = True
return obj
def _init(self, *args, **kwargs):
if 'template' not in kwargs:
kwargs['template'] = _FakePathTemplate(_artifactory_accessor)
super(ArtifactoryPath, self)._init(*args, **kwargs)
@property
def parent(self):
"""
The logical parent of the path.
"""
obj = super(ArtifactoryPath, self).parent
obj.auth = self.auth
obj.verify = self.verify
obj.cert = self.cert
return obj
def with_name(self, name):
"""
Return a new path with the file name changed.
"""
obj = super(ArtifactoryPath, self).with_name(name)
obj.auth = self.auth
obj.verify = self.verify
obj.cert = self.cert
return obj
def with_suffix(self, suffix):
"""
Return a new path with the file suffix changed (or added, if none).
"""
obj = super(ArtifactoryPath, self).with_suffix(suffix)
obj.auth = self.auth
obj.verify = self.verify
obj.cert = self.cert
return obj
def relative_to(self, *other):
"""
Return the relative path to another path identified by the passed
arguments. If the operation is not possible (because this is not
a subpath of the other path), raise ValueError.
"""
obj = super(ArtifactoryPath, self).relative_to(*other)
obj.auth = self.auth
obj.verify = self.verify
obj.cert = self.cert
return obj
def joinpath(self, *args):
"""
Combine this path with one or several arguments, and return a
new path representing either a subpath (if all arguments are relative
paths) or a totally different path (if one of the arguments is
anchored).
"""
obj = super(ArtifactoryPath, self).joinpath(*args)
obj.auth = self.auth
obj.verify = self.verify
obj.cert = self.cert
return obj
def __truediv__(self, key):
"""
Join two paths with '/'
"""
obj = super(ArtifactoryPath, self).__truediv__(key)
obj.auth = self.auth
obj.verify = self.verify
obj.cert = self.cert
return obj
def __rtruediv__(self, key):
"""
Join two paths with '/'
"""
obj = super(ArtifactoryPath, self).__truediv__(key)
obj.auth = self.auth
obj.verify = self.verify
obj.cert = self.cert
return obj
if sys.version_info < (3,):
__div__ = __truediv__
__rdiv__ = __rtruediv__
def _make_child(self, args):
obj = super(ArtifactoryPath, self)._make_child(args)
obj.auth = self.auth
obj.verify = self.verify
obj.cert = self.cert
return obj
def _make_child_relpath(self, args):
obj = super(ArtifactoryPath, self)._make_child_relpath(args)
obj.auth = self.auth
obj.verify = self.verify
obj.cert = self.cert
return obj
def __iter__(self):
"""Iterate over the files in this directory. Does not yield any
result for the special paths '.' and '..'.
"""
for name in self._accessor.listdir(self):
if name in ['.', '..']:
# Yielding a path object for these makes little sense
continue
yield self._make_child_relpath(name)
def open(self, mode='r', buffering=-1, encoding=None,
errors=None, newline=None):
"""
Open the given Artifactory URI and return a file-like object
HTTPResponse, as if it was a regular filesystem object.