-
Notifications
You must be signed in to change notification settings - Fork 337
/
filesystem.py
1281 lines (1030 loc) · 43.9 KB
/
filesystem.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
"""
Filesystem-based package repository
"""
from contextlib import contextmanager
import os.path
import os
import stat
import errno
import time
import platform
from rez.package_repository import PackageRepository
from rez.package_resources import PackageFamilyResource, VariantResourceHelper, \
PackageResourceHelper, package_pod_schema, \
package_release_keys, package_build_only_keys
from rez.serialise import clear_file_caches, open_file_for_write
from rez.package_serialise import dump_package_data
from rez.exceptions import PackageMetadataError, ResourceError, RezSystemError, \
ConfigurationError, PackageRepositoryError
from rez.utils.formatting import is_valid_package_name
from rez.utils.resources import cached_property
from rez.utils.logging_ import print_warning
from rez.utils.memcached import memcached, pool_memcached_connections
from rez.utils.filesystem import make_path_writable, canonical_path
from rez.utils.platform_ import platform_
from rez.serialise import load_from_file, FileFormat
from rez.config import config
from rez.backport.lru_cache import lru_cache
from rez.vendor.schema.schema import Schema, Optional, And, Use, Or
from rez.vendor.six import six
from rez.vendor.version.version import Version, VersionRange
basestring = six.string_types[0]
debug_print = config.debug_printer("resources")
# ------------------------------------------------------------------------------
# format version
#
# 1:
# Initial format.
# 2:
# Late binding functions added.
# ------------------------------------------------------------------------------
format_version = 2
def check_format_version(filename, data):
format_version_ = data.pop("format_version", None)
if format_version_ is not None:
try:
format_version_ = int(format_version_)
except:
return
if format_version_ > format_version:
print_warning(
"Loading from %s may fail: newer format version (%d) than current "
"format version (%d)" % (filename, format_version_, format_version))
# ------------------------------------------------------------------------------
# utilities
# ------------------------------------------------------------------------------
# this is set when the package repository is instantiated, otherwise an infinite
# loop is caused to to config loading this plugin, loading config ad infinitum
_settings = None
class PackageDefinitionFileMissing(PackageMetadataError):
pass
# ------------------------------------------------------------------------------
# resources
# ------------------------------------------------------------------------------
class FileSystemPackageFamilyResource(PackageFamilyResource):
key = "filesystem.family"
repository_type = "filesystem"
def _uri(self):
return self.path
@cached_property
def path(self):
return os.path.join(self.location, self.name)
def get_last_release_time(self):
# this repository makes sure to update path mtime every time a
# variant is added to the repository
try:
return os.path.getmtime(self.path)
except OSError:
return 0
def iter_packages(self):
# check for unversioned package
if config.allow_unversioned_packages:
filepath, _ = self._repository._get_file(self.path)
if filepath:
package = self._repository.get_resource(
FileSystemPackageResource.key,
location=self.location,
name=self.name)
yield package
return
# versioned packages
for version_str in self._repository._get_version_dirs(self.path):
if _settings.check_package_definition_files:
path = os.path.join(self.path, version_str)
if not self._repository._get_file(path)[0]:
continue
package = self._repository.get_resource(
FileSystemPackageResource.key,
location=self.location,
name=self.name,
version=version_str)
yield package
class FileSystemPackageResource(PackageResourceHelper):
key = "filesystem.package"
variant_key = "filesystem.variant"
repository_type = "filesystem"
schema = package_pod_schema
def _uri(self):
return self.filepath
@cached_property
def parent(self):
family = self._repository.get_resource(
FileSystemPackageFamilyResource.key,
location=self.location,
name=self.name)
return family
@cached_property
def state_handle(self):
if self.filepath:
return os.path.getmtime(self.filepath)
return None
@property
def base(self):
# Note: '_redirected_base' is a special attribute set by the build
# process in order to perform pre-install/release package testing. See
# `LocalBuildProcess._run_tests()`
#
redirected_base = self._data.get("_redirected_base")
return redirected_base or self.path
@cached_property
def path(self):
path = os.path.join(self.location, self.name)
ver_str = self.get("version")
if ver_str:
path = os.path.join(path, ver_str)
return path
@cached_property
def filepath(self):
return self._filepath_and_format[0]
@cached_property
def file_format(self):
return self._filepath_and_format[1]
@cached_property
def _filepath_and_format(self):
return self._repository._get_file(self.path)
def _load(self):
if self.filepath is None:
raise PackageDefinitionFileMissing(
"Missing package definition file: %r" % self)
data = load_from_file(self.filepath, self.file_format)
check_format_version(self.filepath, data)
if "timestamp" not in data: # old format support
data_ = self._load_old_formats()
if data_:
data.update(data_)
return data
def _load_old_formats(self):
data = None
filepath = os.path.join(self.path, "release.yaml")
if os.path.isfile(filepath):
# rez<2.0.BETA.16
data = load_from_file(filepath, FileFormat.yaml,
update_data_callback=self._update_changelog)
else:
path_ = os.path.join(self.path, ".metadata")
if os.path.isdir(path_):
# rez-1
data = {}
filepath = os.path.join(path_, "changelog.txt")
if os.path.isfile(filepath):
data["changelog"] = load_from_file(
filepath, FileFormat.txt,
update_data_callback=self._update_changelog)
filepath = os.path.join(path_, "release_time.txt")
if os.path.isfile(filepath):
value = load_from_file(filepath, FileFormat.txt)
try:
data["timestamp"] = int(value.strip())
except:
pass
return data
@staticmethod
def _update_changelog(file_format, data):
# this is to deal with older package releases. They can contain long
# changelogs (more recent rez versions truncate before release), and
# release.yaml files can contain a list-of-str changelog.
maxlen = config.max_package_changelog_chars
if not maxlen:
return data
if file_format == FileFormat.yaml:
changelog = data.get("changelog")
if changelog:
changed = False
if isinstance(changelog, list):
changelog = '\n'.join(changelog)
changed = True
if len(changelog) > (maxlen + 3):
changelog = changelog[:maxlen] + "..."
changed = True
if changed:
data["changelog"] = changelog
else:
assert isinstance(data, basestring)
if len(data) > (maxlen + 3):
data = data[:maxlen] + "..."
return data
class FileSystemVariantResource(VariantResourceHelper):
key = "filesystem.variant"
repository_type = "filesystem"
@cached_property
def parent(self):
package = self._repository.get_resource(
FileSystemPackageResource.key,
location=self.location,
name=self.name,
version=self.get("version"))
return package
# -- 'combined' resource types
class FileSystemCombinedPackageFamilyResource(PackageFamilyResource):
key = "filesystem.family.combined"
repository_type = "filesystem"
schema = Schema({
Optional("versions"): [
And(basestring, Use(Version))
],
Optional("version_overrides"): {
And(basestring, Use(VersionRange)): dict
}
})
@property
def ext(self):
return self.get("ext")
@property
def filepath(self):
filename = "%s.%s" % (self.name, self.ext)
return os.path.join(self.location, filename)
def _uri(self):
return self.filepath
def get_last_release_time(self):
try:
return os.path.getmtime(self.filepath)
except OSError:
return 0
def iter_packages(self):
# unversioned package
if config.allow_unversioned_packages and not self.versions:
package = self._repository.get_resource(
FileSystemCombinedPackageResource.key,
location=self.location,
name=self.name,
ext=self.ext)
yield package
return
# versioned packages
for version in self.versions:
package = self._repository.get_resource(
FileSystemCombinedPackageResource.key,
location=self.location,
name=self.name,
ext=self.ext,
version=str(version))
yield package
def _load(self):
format_ = FileFormat[self.ext]
data = load_from_file(self.filepath, format_)
check_format_version(self.filepath, data)
return data
class FileSystemCombinedPackageResource(PackageResourceHelper):
key = "filesystem.package.combined"
variant_key = "filesystem.variant.combined"
repository_type = "filesystem"
schema = package_pod_schema
def _uri(self):
ver_str = self.get("version", "")
return "%s<%s>" % (self.parent.filepath, ver_str)
@cached_property
def parent(self):
family = self._repository.get_resource(
FileSystemCombinedPackageFamilyResource.key,
location=self.location,
name=self.name,
ext=self.get("ext"))
return family
@property
def base(self):
return None # combined resource types do not have 'base'
@cached_property
def state_handle(self):
return os.path.getmtime(self.parent.filepath)
def iter_variants(self):
num_variants = len(self._data.get("variants", []))
if num_variants == 0:
indexes = [None]
else:
indexes = range(num_variants)
for index in indexes:
variant = self._repository.get_resource(
self.variant_key,
location=self.location,
name=self.name,
ext=self.get("ext"),
version=self.get("version"),
index=index)
yield variant
def _load(self):
data = self.parent._data.copy()
if "versions" in data:
del data["versions"]
version_str = self.get("version")
data["version"] = version_str
version = Version(version_str)
overrides = self.parent.version_overrides
if overrides:
for range_, data_ in overrides.items():
if version in range_:
data.update(data_)
del data["version_overrides"]
return data
class FileSystemCombinedVariantResource(VariantResourceHelper):
key = "filesystem.variant.combined"
repository_type = "filesystem"
@cached_property
def parent(self):
package = self._repository.get_resource(
FileSystemCombinedPackageResource.key,
location=self.location,
name=self.name,
ext=self.get("ext"),
version=self.get("version"))
return package
def _root(self):
return None # combined resource types do not have 'root'
# ------------------------------------------------------------------------------
# repository
# ------------------------------------------------------------------------------
class FileSystemPackageRepository(PackageRepository):
"""A filesystem-based package repository.
Packages are stored on disk, in either 'package.yaml' or 'package.py' files.
These files are stored into an organised directory structure like so:
/LOCATION/pkgA/1.0.0/package.py
/1.0.1/package.py
/pkgB/2.1/package.py
/2.2/package.py
Another supported storage format is to store all package versions within a
single package family in one file, like so:
/LOCATION/pkgC.yaml
/LOCATION/pkgD.py
These 'combined' package files allow for differences between package
versions via a 'package_overrides' section:
name: pkgC
versions:
- '1.0'
- '1.1'
- '1.2'
version_overrides:
'1.0':
requires:
- python-2.5
'1.1+':
requires:
- python-2.6
"""
schema_dict = {"file_lock_timeout": int,
"file_lock_dir": Or(None, str),
"file_lock_type": Or("default", "link", "mkdir"),
"package_filenames": [basestring]}
building_prefix = ".building"
ignore_prefix = ".ignore"
package_file_mode = (
None if os.name == "nt" else
# These aren't supported on Windows
# https://docs.python.org/2/library/os.html#os.chmod
(stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)
)
@classmethod
def name(cls):
return "filesystem"
def __init__(self, location, resource_pool):
"""Create a filesystem package repository.
Args:
location (str): Path containing the package repository.
"""
# ensure that differing case doesn't get interpreted as different repos
# on case-insensitive platforms (eg windows)
location = canonical_path(location, platform_)
super(FileSystemPackageRepository, self).__init__(location, resource_pool)
global _settings
_settings = config.plugins.package_repository.filesystem
self.register_resource(FileSystemPackageFamilyResource)
self.register_resource(FileSystemPackageResource)
self.register_resource(FileSystemVariantResource)
self.register_resource(FileSystemCombinedPackageFamilyResource)
self.register_resource(FileSystemCombinedPackageResource)
self.register_resource(FileSystemCombinedVariantResource)
self.get_families = lru_cache(maxsize=None)(self._get_families)
self.get_family = lru_cache(maxsize=None)(self._get_family)
self.get_packages = lru_cache(maxsize=None)(self._get_packages)
self.get_variants = lru_cache(maxsize=None)(self._get_variants)
self.get_file = lru_cache(maxsize=None)(self._get_file)
def _uid(self):
t = ["filesystem", self.location]
if os.path.exists(self.location):
st = os.stat(self.location)
t.append(int(st.st_ino))
return tuple(t)
def get_package_family(self, name):
return self.get_family(name)
@pool_memcached_connections
def iter_package_families(self):
for family in self.get_families():
yield family
@pool_memcached_connections
def iter_packages(self, package_family_resource):
for package in self.get_packages(package_family_resource):
yield package
def iter_variants(self, package_resource):
for variant in self.get_variants(package_resource):
yield variant
def get_parent_package_family(self, package_resource):
return package_resource.parent
def get_parent_package(self, variant_resource):
return variant_resource.parent
def get_variant_state_handle(self, variant_resource):
package_resource = variant_resource.parent
return package_resource.state_handle
def get_last_release_time(self, package_family_resource):
return package_family_resource.get_last_release_time()
def get_variant_from_uri(self, uri):
"""
Example URIs:
- /svr/packages/mypkg/1.0.0/package.py[1]
- /svr/packages/mypkg/1.0.0/package.py[] ("null" variant)
- /svr/packages/mypkg/package.py[1] (unversioned package - rare)
- /svr/packages/mypkg/package.py<1.0.0>[1] ("combined" package type - rare)
"""
i = uri.rfind('[')
if i == -1:
return None
prefix = self.location + os.path.sep
if not uri.startswith(prefix):
return None
part1 = uri[len(prefix):i] # 'mypkg/1.0.0/package.py'
part2 = uri[i:][1:-1] # the '1' in '[1]'
# find package
if '<' in part1:
# "combined" package type, like 'mypkg/package.py<1.0.0>'
i = part1.find('<')
pkg_name = part1.split(os.path.sep)[0]
pkg_ver_str = part1[i + 1:-1]
else:
parts = part1.split(os.path.sep)
if len(parts) == 3: # versioned package
pkg_name, pkg_ver_str = parts[0], parts[1]
elif len(parts) == 2: # unversioned package
pkg_name, pkg_ver_str = parts[0], ''
else:
return None
fam = self.get_package_family(pkg_name)
if fam is None:
return None
ver = Version(pkg_ver_str)
pkg = None
for package in fam.iter_packages():
if package.version == ver:
pkg = package
break
if pkg is None:
return None
# find variant in package
if part2 == '':
variant_index = None
else:
try:
variant_index = int(part2)
except:
# future proof - we may move to hash-based indices for hashed variants
variant_index = part2
for variant in pkg.iter_variants():
if variant.index == variant_index:
return variant
return None
@cached_property
def file_lock_dir(self):
dirname = _settings.file_lock_dir
if not dirname:
return None
# sanity check
if os.path.isabs(dirname) or os.path.basename(dirname) != dirname:
raise ConfigurationError(
"filesystem package repository setting 'file_lock_dir' must be "
"a single relative directory such as '.lock'")
# fall back to location path if lock dir doesn't exist.
path = os.path.join(self.location, dirname)
if not os.path.exists(path):
return None
return dirname
def pre_variant_install(self, variant_resource):
if not variant_resource.version:
return
# create 'building' tagfile, this makes sure that a resolve doesn't
# pick up this package if it doesn't yet have a package.py created.
path = self.location
family_path = os.path.join(path, variant_resource.name)
if not os.path.isdir(family_path):
os.makedirs(family_path)
filename = self.building_prefix + str(variant_resource.version)
filepath = os.path.join(family_path, filename)
with open(filepath, 'w'): # create empty file
pass
def on_variant_install_cancelled(self, variant_resource):
"""
TODO:
Currently this will not delete a newly created package version
directory. The reason is because behaviour with multiple rez procs
installing variants of the same package in parallel is not well
tested and hasn't been fully designed for yet. Currently, if this
did delete the version directory, it could delete it while another
proc is performing a successful variant install into the same dir.
Note though that this does do useful work, if the cancelled variant
was getting installed into an existing package. In this case, the
.building file is deleted, because the existing package.py is valid.
Work has to be done to change the way that new variant dirs and the
.building file are created, so that we can safely delete cancelled
variant dirs in the presence of multiple rez procs.
See https://github.com/nerdvegas/rez/issues/810
"""
family_path = os.path.join(self.location, variant_resource.name)
self._delete_stale_build_tagfiles(family_path)
def install_variant(self, variant_resource, dry_run=False, overrides=None):
overrides = overrides or {}
# Name and version overrides are a special case - they change the
# destination variant to be created/replaced.
#
variant_name = variant_resource.name
variant_version = variant_resource.version
if "name" in overrides:
variant_name = overrides["name"]
if variant_name is self.remove:
raise PackageRepositoryError(
"Cannot remove package attribute 'name'")
if "version" in overrides:
ver = overrides["version"]
if ver is self.remove:
raise PackageRepositoryError(
"Cannot remove package attribute 'version'")
if isinstance(ver, basestring):
ver = Version(ver)
overrides = overrides.copy()
overrides["version"] = ver
variant_version = ver
# cannot install over one's self, just return existing variant
if variant_resource._repository is self and \
variant_name == variant_resource.name and \
variant_version == variant_resource.version:
return variant_resource
# create repo path on disk if it doesn't exist
path = self.location
try:
os.makedirs(path)
except OSError as e:
if e.errno != errno.EEXIST:
raise PackageRepositoryError(
"Package repository path %r could not be created: %s: %s"
% (path, e.__class__.__name__, e)
)
# install the variant
def _create_variant():
return self._create_variant(
variant_resource,
dry_run=dry_run,
overrides=overrides
)
if dry_run:
variant = _create_variant()
else:
with self._lock_package(variant_name, variant_version):
variant = _create_variant()
return variant
@contextmanager
def _lock_package(self, package_name, package_version=None):
from rez.vendor.lockfile import NotLocked
if _settings.file_lock_type == 'default':
from rez.vendor.lockfile import LockFile
elif _settings.file_lock_type == 'mkdir':
from rez.vendor.lockfile.mkdirlockfile import MkdirLockFile as LockFile
elif _settings.file_lock_type == 'link':
from rez.vendor.lockfile.linklockfile import LinkLockFile as LockFile
path = self.location
if self.file_lock_dir:
path = os.path.join(path, self.file_lock_dir)
if not os.path.exists(path):
raise PackageRepositoryError(
"Lockfile directory %s does not exist - please create and try "
"again" % path)
filename = ".lock.%s" % package_name
if package_version:
filename += "-%s" % str(package_version)
lock_file = os.path.join(path, filename)
lock = LockFile(lock_file)
try:
lock.acquire(timeout=_settings.file_lock_timeout)
yield
finally:
try:
lock.release()
except NotLocked:
pass
def clear_caches(self):
super(FileSystemPackageRepository, self).clear_caches()
self.get_families.cache_clear()
self.get_family.cache_clear()
self.get_packages.cache_clear()
self.get_variants.cache_clear()
self.get_file.cache_clear()
self._get_family_dirs.forget()
self._get_version_dirs.forget()
# unfortunately we need to clear file cache across the board
clear_file_caches()
def get_package_payload_path(self, package_name, package_version=None):
path = os.path.join(self.location, package_name)
if package_version:
path = os.path.join(path, str(package_version))
return path
# -- internal
def _get_family_dirs__key(self):
if os.path.isdir(self.location):
st = os.stat(self.location)
return str(("listdir", self.location, int(st.st_ino), st.st_mtime))
else:
return str(("listdir", self.location))
@memcached(servers=config.memcached_uri if config.cache_listdir else None,
min_compress_len=config.memcached_listdir_min_compress_len,
key=_get_family_dirs__key,
debug=config.debug_memcache)
def _get_family_dirs(self):
dirs = []
if not os.path.isdir(self.location):
return dirs
for name in os.listdir(self.location):
path = os.path.join(self.location, name)
if os.path.isdir(path):
if is_valid_package_name(name) and name != self.file_lock_dir:
dirs.append((name, None))
else:
name_, ext_ = os.path.splitext(name)
if ext_ in (".py", ".yaml") and is_valid_package_name(name_):
dirs.append((name_, ext_[1:]))
return dirs
def _get_version_dirs__key(self, root):
st = os.stat(root)
return str(("listdir", root, int(st.st_ino), st.st_mtime))
@memcached(servers=config.memcached_uri if config.cache_listdir else None,
min_compress_len=config.memcached_listdir_min_compress_len,
key=_get_version_dirs__key,
debug=config.debug_memcache)
def _get_version_dirs(self, root):
# Ignore a version if there is a .ignore<version> file next to it
def ignore_dir(name):
path = os.path.join(root, self.ignore_prefix + name)
return os.path.isfile(path)
# simpler case if this test is on
#
if _settings.check_package_definition_files:
dirs = []
for name in os.listdir(root):
if name.startswith('.'):
continue
path = os.path.join(root, name)
if os.path.isdir(path) and not ignore_dir(name) \
and self._is_valid_package_directory(path):
dirs.append(name)
return dirs
# with test off, we have to check for 'building' dirs, these have to be
# tested regardless. Failed releases may cause 'building files' to be
# left behind, so we need to clear these out also
#
dirs = set()
building_dirs = set()
# find dirs and dirs marked as 'building'
for name in os.listdir(root):
if name.startswith('.'):
if not name.startswith(self.building_prefix):
continue
ver_str = name[len(self.building_prefix):]
building_dirs.add(ver_str)
path = os.path.join(root, name)
if os.path.isdir(path) and not ignore_dir(name):
dirs.add(name)
# check 'building' dirs for validity
for name in building_dirs:
if name not in dirs:
continue
path = os.path.join(root, name)
if not self._is_valid_package_directory(path):
# package probably still being built
dirs.remove(name)
return list(dirs)
# True if `path` contains package.py or similar
def _is_valid_package_directory(self, path):
return bool(self._get_file(path, "package")[0])
def _get_families(self):
families = []
for name, ext in self._get_family_dirs():
if ext is None: # is a directory
family = self.get_resource(
FileSystemPackageFamilyResource.key,
location=self.location,
name=name)
else:
family = self.get_resource(
FileSystemCombinedPackageFamilyResource.key,
location=self.location,
name=name,
ext=ext)
families.append(family)
return families
def _get_family(self, name):
is_valid_package_name(name, raise_error=True)
if os.path.isdir(os.path.join(self.location, name)):
# force case-sensitive match on pkg family dir, on case-insensitive platforms
if not platform_.has_case_sensitive_filesystem and \
name not in os.listdir(self.location):
return None
return self.get_resource(
FileSystemPackageFamilyResource.key,
location=self.location,
name=name
)
else:
filepath, format_ = self.get_file(self.location, package_filename=name)
if filepath:
# force case-sensitive match on pkg filename, on case-insensitive platforms
if not platform_.has_case_sensitive_filesystem:
ext = os.path.splitext(filepath)[-1]
if (name + ext) not in os.listdir(self.location):
return None
return self.get_resource(
FileSystemCombinedPackageFamilyResource.key,
location=self.location,
name=name,
ext=format_.extension
)
return None
def _get_packages(self, package_family_resource):
return [x for x in package_family_resource.iter_packages()]
def _get_variants(self, package_resource):
return [x for x in package_resource.iter_variants()]
def _get_file(self, path, package_filename=None):
if package_filename:
package_filenames = [package_filename]
else:
package_filenames = _settings.package_filenames
for name in package_filenames:
for format_ in (FileFormat.py, FileFormat.yaml):
filename = "%s.%s" % (name, format_.extension)
filepath = os.path.join(path, filename)
if os.path.isfile(filepath):
return filepath, format_
return None, None
def _create_family(self, name):
path = os.path.join(self.location, name)
if not os.path.exists(path):
os.makedirs(path)
self.clear_caches()
return self.get_package_family(name)
def _create_variant(self, variant, dry_run=False, overrides=None):
# special case overrides
variant_name = overrides.get("name") or variant.name
variant_version = overrides.get("version") or variant.version
overrides = (overrides or {}).copy()
overrides.pop("name", None)
overrides.pop("version", None)
# find or create the package family
family = self.get_package_family(variant_name)
if not family:
family = self._create_family(variant_name)
if isinstance(family, FileSystemCombinedPackageFamilyResource):
raise NotImplementedError(
"Cannot install variant into combined-style package file %r."
% family.filepath)
# find the package if it already exists
existing_package = None
for package in self.iter_packages(family):
if package.version == variant_version:
# during a build, the family/version dirs get created ahead of
# time, which causes a 'missing package definition file' error.
# This is fine, we can just ignore it and write the new file.
try:
package.validate_data()
except PackageDefinitionFileMissing:
break
uuids = set([variant.uuid, package.uuid])
if len(uuids) > 1 and None not in uuids:
raise ResourceError(
"Cannot install variant %r into package %r - the "
"packages are not the same (UUID mismatch)"
% (variant, package))
existing_package = package
if variant.index is None:
if package.variants: