forked from devopshq/artifactory
-
Notifications
You must be signed in to change notification settings - Fork 0
/
artifactory.py
executable file
·2837 lines (2412 loc) · 87.6 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 collections
import datetime
import errno
import fnmatch
import hashlib
import io
import json
import os
import pathlib
import platform
import re
import sys
import urllib.parse
from itertools import islice
import dateutil.parser
import requests
from dohq_artifactory.admin import Group
from dohq_artifactory.admin import PermissionTarget
from dohq_artifactory.admin import Project
from dohq_artifactory.admin import Repository
from dohq_artifactory.admin import RepositoryLocal
from dohq_artifactory.admin import RepositoryRemote
from dohq_artifactory.admin import RepositoryVirtual
from dohq_artifactory.admin import User
from dohq_artifactory.auth import XJFrogArtApiAuth
from dohq_artifactory.auth import XJFrogArtBearerAuth
from dohq_artifactory.exception import ArtifactoryException
from dohq_artifactory.exception import raise_for_status
from dohq_artifactory.logger import logger
try:
import requests.packages.urllib3 as urllib3
except ImportError:
import urllib3
try:
import configparser
except ImportError:
import ConfigParser as configparser
if "DOHQ_ARTIFACTORY_PYTHON_CFG" in os.environ:
default_config_path = os.environ["DOHQ_ARTIFACTORY_PYTHON_CFG"]
elif platform.system() == "Windows":
default_config_path = "~\\.artifactory_python.cfg"
else:
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/path-to-CA_BUNDLE>, '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, f"Artifactory configuration file not found: '{config_path}'"
)
p = configparser.ConfigParser()
p.read(config_path)
result = {}
for section in p.sections():
username = p.get(section, "username", fallback=None)
password = p.get(section, "password", fallback=None)
try:
verify = p.getboolean(section, "verify", fallback=True)
except ValueError:
# the path to a CA_BUNDLE file or directory with certificates of trusted CAs
# see https://github.com/devopshq/artifactory/issues/281
verify = p.get(section, "verify", fallback=True)
# path may contain '~', and we'd better expand it properly
verify = os.path.expanduser(verify)
cert = p.get(section, "cert", fallback=None)
if cert:
# certificate path may contain '~', and we'd better expand it properly
cert = os.path.expanduser(cert)
result[section] = {
"username": username,
"password": password,
"verify": verify,
"cert": 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]
return None
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()
def sha256sum(filename):
"""
Calculates sha256 hash of a file
"""
sha256 = hashlib.sha256()
with open(filename, "rb") as f:
for chunk in iter(lambda: f.read(128 * sha256.block_size), b""):
sha256.update(chunk)
return sha256.hexdigest()
def chunks(data, size):
"""
Get chink for dict, copy as-is from https://stackoverflow.com/a/8290508/6753144
"""
it = iter(data)
for _ in range(0, len(data), size):
yield {k: data[k] for k in islice(it, size)}
def log_download_progress(bytes_now, total_size):
"""
Function to log download progress
:param bytes_now: current number of bytes
:param total_size: total file size in bytes
:return:
"""
if total_size > 0:
msg = "Downloaded {}/{}MB...[{}%]".format(
int(bytes_now / 1024 / 1024),
int(total_size / 1024 / 1024),
round(bytes_now / total_size * 100, 2),
)
else:
msg = "Downloaded {}MB".format(int(bytes_now / 1024 / 1024))
logger.debug(msg)
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, quote_parameters):
"""
Performs encoding of url matrix parameters from dictionary to
a string.
See http://www.w3.org/DesignIssues/MatrixURIs.html for specs.
If quote_parameters is true, then apply URL quoting to the values and the parameter names.
"""
result = []
for param in iter(sorted(parameters)):
raw_value = parameters[param]
resolved_param = urllib.parse.quote(param) if quote_parameters else param
if isinstance(raw_value, (list, tuple)):
values = (
[urllib.parse.quote(v) for v in raw_value]
if quote_parameters
else raw_value
)
value = f";{resolved_param}=".join(values)
else:
value = urllib.parse.quote(raw_value) if quote_parameters else raw_value
result.append("=".join((resolved_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("=".join((param, value)))
return ";".join(result)
# Declare contextlib class that was enabled in Py 3.7. Declare for compatibility with 3.6
# this class is taken and modified from standard module contextlib
class nullcontext:
"""Context manager that does no additional processing.
Used as a stand-in for a normal context manager, when a particular
block of code is only sometimes used with a normal context manager:
cm = optional_cm if condition else nullcontext()
with cm:
# Perform operation, using optional_cm if condition is True
"""
def __init__(self, enter_result=None):
self.enter_result = enter_result
def __enter__(self):
return self.enter_result
def __exit__(self, *excinfo):
pass
def quote_url(url):
"""
Quote URL to allow URL fragment identifier as artifact folder or file names.
See https://en.wikipedia.org/wiki/Percent-encoding#Reserved_characters
Function will percent-encode the URL
:param url: (str) URL that should be quoted
:return: (str) quoted URL
"""
logger.debug(f"Raw URL passed for encoding: {url}")
parsed_url = urllib3.util.parse_url(url)
if parsed_url.port:
quoted_path = requests.utils.quote(
url.partition(f"{parsed_url.host}:{parsed_url.port}")[2]
)
quoted_url = (
f"{parsed_url.scheme}://{parsed_url.host}:{parsed_url.port}{quoted_path}"
)
else:
quoted_path = requests.utils.quote(url.partition(parsed_url.host)[2])
quoted_url = f"{parsed_url.scheme}://{parsed_url.host}{quoted_path}"
return quoted_url
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 _get_base_url(self, url):
return get_global_base_url(url)
def compile_pattern(self, pattern):
return re.compile(fnmatch.translate(pattern), re.IGNORECASE).fullmatch
def parse_parts(self, parts):
drv, root, parsed = super(_ArtifactoryFlavour, self).parse_parts(parts)
return drv, root, parsed
def join_parsed_parts(self, drv, root, parts, drv2, root2, parts2):
drv2, root2, parts2 = super(_ArtifactoryFlavour, self).join_parsed_parts(
drv, root, parts, drv2, root2, parts2
)
if not root2 and len(parts2) > 1:
root2 = self.sep + parts2.pop(1) + self.sep
# quick hack for https://github.com/devopshq/artifactory/issues/29
# drive or repository must start with / , if not - add it
if not drv2.endswith("/") and not root2.startswith("/"):
drv2 = drv2 + self.sep
return drv2, root2, parts2
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.
If '/artifactory/' is not in the URI. Everything before the path
component is treated as drive. The first folder of the path is
treated as root, and everything else is taken for relative path.
"""
drv = ""
root = ""
base = self._get_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)
elif sep not in part:
return "", "", part
else:
url = urllib3.util.parse_url(part)
if (
without_http_prefix(part).strip("/") == part.strip("/")
and url.path
and not url.path.strip("/").startswith("artifactory")
):
return "", "", part
if url.path is None or url.path == sep:
if url.scheme:
return part.rstrip(sep), "", ""
return "", "", part
elif url.path.lstrip("/").startswith("artifactory"):
mark = sep + "artifactory" + sep
parts = part.split(mark)
else:
path = self._get_path(part)
drv = part.rpartition(path)[0]
path_parts = path.strip(sep).split(sep)
root = sep + path_parts[0] + sep
rest = sep.join(path_parts[1:])
return drv, root, rest
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 _get_path(self, url):
"""
Get path of a url and return without percent-encoding
http://example.com/dir/file.html
path = /dir/file.html
http://example.com/dir/inval:[email protected]
path = /dir/inval:[email protected]
!= /dir/inval%3Ad-ch%40rs.html
:param url: Full URL to parse
:return: path: /dir/file.html
"""
parsed_url = urllib3.util.parse_url(url)
return url.rpartition(parsed_url.host)[2]
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
class _ArtifactorySaaSFlavour(_ArtifactoryFlavour):
def _get_base_url(self, url):
split_url = pathlib.PurePosixPath(url)
if len(split_url.parts) < 3:
return None
return urllib.parse.urljoin(
"//".join((split_url.parts[0], split_url.parts[1])), split_url.parts[2]
)
_artifactory_flavour = _ArtifactoryFlavour()
_saas_artifactory_flavour = _ArtifactorySaaSFlavour()
ArtifactoryFileStat = collections.namedtuple(
"ArtifactoryFileStat",
[
"ctime",
"mtime",
"created_by",
"modified_by",
"mime_type",
"size",
"sha1",
"sha256",
"md5",
"is_dir",
"children",
"repo",
"created",
"last_modified",
"last_updated",
],
)
ArtifactoryDownloadStat = collections.namedtuple(
"ArtifactoryDownloadStat",
[
"last_downloaded",
"download_count",
"last_downloaded_by",
"remote_download_count",
"remote_last_downloaded",
"uri",
],
)
class _ScandirIter:
"""
For compatibility with different python versions.
Pathlib:
- prior 3.8 - Use it as an iterator
- 3.8 - Use it as an context manager
"""
def __init__(self, iterator):
self.iterator = iterator
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
pass
def __iter__(self):
return self.iterator
class _ArtifactoryAccessor:
"""
Implements operations with Artifactory REST API
"""
@staticmethod
def rest_get(
url,
params=None,
headers=None,
session=None,
verify=True,
cert=None,
timeout=None,
):
"""
Perform a GET request to url with requests.session
:param url:
:param params:
:param headers:
:param session:
:param verify:
:param cert:
:param timeout:
:return: response object
"""
url = quote_url(url)
response = session.get(
url,
params=params,
headers=headers,
verify=verify,
cert=cert,
timeout=timeout,
)
return response
@staticmethod
def rest_put(
url,
params=None,
headers=None,
session=None,
verify=True,
cert=None,
timeout=None,
):
"""
Perform a PUT request to url with requests.session
"""
url = quote_url(url)
response = session.put(
url,
params=params,
headers=headers,
verify=verify,
cert=cert,
timeout=timeout,
)
return response
@staticmethod
def rest_post(
url,
params=None,
headers=None,
session=None,
verify=True,
cert=None,
timeout=None,
json_data=None,
):
"""
Perform a POST request to url with requests.session
"""
url = quote_url(url)
response = session.post(
url,
json=json_data,
params=params,
headers=headers,
verify=verify,
cert=cert,
timeout=timeout,
)
raise_for_status(response)
return response
@staticmethod
def rest_del(url, params=None, session=None, verify=True, cert=None, timeout=None):
"""
Perform a DELETE request to url with requests.session
:param url: url
:param params: request parameters
:param session:
:param verify:
:param cert:
:param timeout:
:return: request response object
"""
url = quote_url(url)
response = session.delete(
url, params=params, verify=verify, cert=cert, timeout=timeout
)
raise_for_status(response)
return response
@staticmethod
def rest_patch(
url,
json_data=None,
params=None,
session=None,
verify=True,
cert=None,
timeout=None,
):
"""
Perform a PATCH request to url with requests.session
:param url: url
:param json_data: (dict) JSON data to attach to patch request
:param params: request parameters
:param session:
:param verify:
:param cert:
:param timeout:
:return: request response object
"""
url = quote_url(url)
response = session.patch(
url=url,
json=json_data,
params=params,
verify=verify,
cert=cert,
timeout=timeout,
)
return response
@staticmethod
def rest_put_stream(
url,
stream,
headers=None,
session=None,
verify=True,
cert=None,
timeout=None,
matrix_parameters=None,
):
"""
Perform a chunked PUT request to url with requests.session
This is specifically to upload files.
"""
url = quote_url(url)
if matrix_parameters is not None:
# added later, otherwise ; and = are converted
url += matrix_parameters
response = session.put(
url, headers=headers, data=stream, verify=verify, cert=cert, timeout=timeout
)
raise_for_status(response)
return response
@staticmethod
def rest_get_stream(
url,
params=None,
session=None,
verify=True,
cert=None,
timeout=None,
quote=True,
):
"""
Perform a chunked GET request to url with requests.session
This is specifically to download files.
"""
if quote:
url = quote_url(url)
response = session.get(
url, params=params, stream=True, verify=verify, cert=cert, timeout=timeout
)
raise_for_status(response)
return response
def get_stat_json(self, pathobj, key=None):
"""
Request remote file/directory status info
Returns a json object as specified by Artifactory REST API
Args:
pathobj: ArtifactoryPath for which we request data
key: (str) (optional) additional key to specify query, eg 'stats', 'lastModified'
Returns:
(dict) stat dictionary
"""
url = "/".join(
[
pathobj.drive.rstrip("/"),
"api/storage",
str(pathobj.relative_to(pathobj.drive)).strip("/"),
]
)
response = self.rest_get(
url,
session=pathobj.session,
verify=pathobj.verify,
cert=pathobj.cert,
timeout=pathobj.timeout,
params=key,
)
code = response.status_code
text = response.text
if code == 404 and ("Unable to find item" in text or "Not Found" in text or "File not found" in text):
raise OSError(2, f"No such file or directory: {url}")
raise_for_status(response)
return response.json()
def stat(self, pathobj):
"""
Request remote file/directory status info
Returns an object of class ArtifactoryFileStat.
"""
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"]]
checksums = jsn.get("checksums", {})
ctime = dateutil.parser.parse(jsn["created"])
mtime = dateutil.parser.parse(jsn["lastModified"])
stat = ArtifactoryFileStat(
ctime=ctime,
mtime=mtime,
created_by=jsn.get("createdBy"),
modified_by=jsn.get("modifiedBy"),
mime_type=jsn.get("mimeType"),
size=int(jsn.get("size", "0")),
sha1=checksums.get("sha1", None),
sha256=checksums.get("sha256", None),
md5=checksums.get("md5", None),
is_dir=is_dir,
children=children,
repo=jsn.get("repo", None),
created=ctime,
last_modified=mtime,
last_updated=dateutil.parser.parse(jsn["lastUpdated"]),
)
return stat
def download_stats(self, pathobj):
jsn = self.get_stat_json(pathobj, key="stats")
# divide timestamp by 1000 since it is provided in ms
download_time = datetime.datetime.fromtimestamp(
jsn.get("lastDownloaded", 0) / 1000
)
stat = ArtifactoryDownloadStat(
last_downloaded=download_time,
last_downloaded_by=jsn.get("lastDownloadedBy", None),
download_count=jsn.get("downloadCount", None),
remote_download_count=jsn.get("remoteDownloadCount", None),
remote_last_downloaded=jsn.get("remoteLastDownloaded", None),
uri=jsn.get("uri", None),
)
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, f"Not a directory: {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 ArtifactoryException(f"Full path required: '{pathobj}'")
if pathobj.exists():
raise OSError(17, f"File exists: '{pathobj}'")
url = str(pathobj) + "/"
response = self.rest_put(
url,
session=pathobj.session,
verify=pathobj.verify,
cert=pathobj.cert,
timeout=pathobj.timeout,
)
raise_for_status(response)