forked from crs4/rocrate-validator
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodels.py
More file actions
3075 lines (2630 loc) · 116 KB
/
models.py
File metadata and controls
3075 lines (2630 loc) · 116 KB
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
# Copyright (c) 2024-2026 CRS4
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import annotations
import bisect
import enum
import inspect
import json
import re
from abc import ABC, abstractmethod
from collections.abc import Collection
from dataclasses import asdict, dataclass
from datetime import datetime, timezone
from functools import total_ordering
from pathlib import Path
from typing import Optional, Protocol, Tuple, Union
from urllib.error import HTTPError
import enum_tools
from rdflib import RDF, RDFS, Graph, Namespace, URIRef
from rocrate_validator.utils import log as logging
from rocrate_validator import __version__
from rocrate_validator.constants import (DEFAULT_ONTOLOGY_FILE,
DEFAULT_PROFILE_IDENTIFIER,
DEFAULT_PROFILE_README_FILE,
IGNORED_PROFILE_DIRECTORIES,
JSON_OUTPUT_FORMAT_VERSION, PROF_NS,
PROFILE_FILE_EXTENSIONS,
PROFILE_SPECIFICATION_FILE,
ROCRATE_METADATA_FILE, SCHEMA_ORG_NS)
from rocrate_validator.errors import (DuplicateRequirementCheck,
InvalidProfilePath, ProfileNotFound,
ProfileSpecificationError,
ProfileSpecificationNotFound,
ROCrateMetadataNotFoundError)
from rocrate_validator.events import Event, EventType, Publisher, Subscriber
from rocrate_validator.rocrate import ROCrate
from rocrate_validator.utils.collections import (MapIndex)
from rocrate_validator.utils.paths import get_profiles_path
from rocrate_validator.utils.python_helpers import get_requirement_name_from_file
from rocrate_validator.utils.uri import URI
from rocrate_validator.utils.collections import MultiIndexMap
# set the default profiles path
DEFAULT_PROFILES_PATH = get_profiles_path()
logger = logging.getLogger(__name__)
BaseTypes = Union[str, Path, bool, int, None]
@enum.unique
@enum_tools.documentation.document_enum
@total_ordering
class Severity(enum.Enum):
"""
Enum ordering "strength" of conditions to be verified
"""
#: the condition is not mandatory
OPTIONAL = 0
#: the condition is recommended
RECOMMENDED = 2
#: the condition is mandatory
REQUIRED = 4
def __lt__(self, other: object) -> bool:
if isinstance(other, Severity):
return self.value < other.value
else:
raise TypeError(f"Comparison not supported between instances of {type(self)} and {type(other)}")
@staticmethod
def get(name: str) -> Severity:
return getattr(Severity, name.upper())
@total_ordering
@dataclass
class RequirementLevel:
"""
Represents a requirement level.
A requirement has a name and a severity level of type :class:`.Severity`.
It implements the comparison operators to allow ordering of the requirement levels.
"""
name: str
severity: Severity
def __eq__(self, other: object) -> bool:
if not isinstance(other, RequirementLevel):
return False
return self.name == other.name and self.severity == other.severity
def __lt__(self, other: object) -> bool:
# TODO: this ordering is not totally coherent, since for two objects a and b
# with equal Severity but different names you would have
# not a < b, which implies a >= b
# and also a != b and not a > b, which is incoherent with a >= b
if not isinstance(other, RequirementLevel):
raise TypeError(f"Cannot compare {type(self)} with {type(other)}")
return self.severity < other.severity
def __hash__(self) -> int:
return hash((self.name, self.severity))
def __repr__(self) -> str:
return f'RequirementLevel(name={self.name}, severity={self.severity})'
def __str__(self) -> str:
return self.name
def __int__(self) -> int:
return self.severity.value
def __index__(self) -> int:
return self.severity.value
class LevelCollection:
"""
Collection of :class:`.RequirementLevel` instances.
Provides a set of predefined RequirementLevel instances
that can be used to define the severity of a requirement.
They map the keywords defined in **RFC 2119** to the corresponding severity levels.
.. note::
The keywords **MUST**, **MUST NOT**, **REQUIRED**,
**SHALL**, **SHALL NOT**, **SHOULD**, **SHOULD NOT**,
**RECOMMENDED**, **MAY**, and **OPTIONAL** in this document
are to be interpreted as described in **RFC 2119**.
"""
#: The requirement level OPTIONAL is mapped to the OPTIONAL severity level
OPTIONAL = RequirementLevel('OPTIONAL', Severity.OPTIONAL)
#: The requirement level MAY is mapped to the OPTIONAL severity level
MAY = RequirementLevel('MAY', Severity.OPTIONAL)
#: The requirement level REQUIRED is mapped to the REQUIRED severity level
REQUIRED = RequirementLevel('REQUIRED', Severity.REQUIRED)
#: The requirement level SHOULD is mapped to the RECOMMENDED severity level
SHOULD = RequirementLevel('SHOULD', Severity.RECOMMENDED)
#: The requirement level SHOULD NOT is mapped to the RECOMMENDED severity level
SHOULD_NOT = RequirementLevel('SHOULD_NOT', Severity.RECOMMENDED)
#: The requirement level RECOMMENDED is mapped to the RECOMMENDED severity level
RECOMMENDED = RequirementLevel('RECOMMENDED', Severity.RECOMMENDED)
#: The requirement level MUST is mapped to the REQUIRED severity level
MUST = RequirementLevel('MUST', Severity.REQUIRED)
#: The requirement level MUST_NOT is mapped to the REQUIRED severity level
MUST_NOT = RequirementLevel('MUST_NOT', Severity.REQUIRED)
#: The requirement level SHALL is mapped to the REQUIRED severity level
SHALL = RequirementLevel('SHALL', Severity.REQUIRED)
#: The requirement level SHALL_NOT is mapped to the REQUIRED severity level
SHALL_NOT = RequirementLevel('SHALL_NOT', Severity.REQUIRED)
def __init__(self):
raise NotImplementedError(f"{type(self)} can't be instantiated")
@staticmethod
def all() -> list[RequirementLevel]:
return [level for name, level in inspect.getmembers(LevelCollection)
if not inspect.isroutine(level)
and not inspect.isdatadescriptor(level) and not name.startswith('__')]
@staticmethod
def get(name: str) -> RequirementLevel:
try:
return getattr(LevelCollection, name.upper())
except AttributeError:
raise ValueError(f"Invalid RequirementLevel: {name}")
@total_ordering
class Profile:
"""
RO-Crate Validator profile.
A profile is a named set of requirements that can be used to validate an RO-Crate.
"""
# store the map of profiles: profile URI -> Profile instance
__profiles_map: MultiIndexMap = \
MultiIndexMap("uri", indexes=[
MapIndex("name"), MapIndex("token", unique=False), MapIndex("identifier", unique=True),
MapIndex("token_path", unique=False)
])
def __init__(self,
profiles_base_path: Path,
profile_path: Path,
requirements: Optional[list[Requirement]] = None,
identifier: str = None,
publicID: Optional[str] = None,
severity: Severity = Severity.REQUIRED):
"""
Initialize the Profile instance
:param profile_path: the path of the profile
:type profile_path: Path
:param requirements: the list of requirements of the profile
:type requirements: list[Requirement]
:param identifier: the identifier of the profile
:type identifier: str
:param publicID: the public identifier of the profile
:type publicID: str
:meta private:
:param severity: the severity of the profile
:type severity: Severity
: raises ProfileSpecificationNotFound: if the profile specification file is not found
: raises ProfileSpecificationError: if the profile specification file contains more than one profile
: raises InvalidProfilePath: if the profile path is not a directory
:meta private:
"""
self._identifier: Optional[str] = identifier
self._profiles_base_path = profiles_base_path
self._profile_path = profile_path
self._name: Optional[str] = None
self._description: Optional[str] = None
self._requirements: list[Requirement] = requirements if requirements is not None else []
self._publicID = publicID
self._severity = severity
self._overrides: list[Profile] = []
self._overridden_by: list[Profile] = []
# init property to store the RDF node which is the root of the profile specification graph
self._profile_node = None
# init property to store the RDF graph of the profile specification
self._profile_specification_graph = None
# check if the profile specification file exists
spec_file = self.profile_specification_file_path
if not spec_file or not spec_file.exists():
raise ProfileSpecificationNotFound(spec_file)
# load the profile specification expressed using the Profiles Vocabulary
profile = Graph()
profile.parse(str(spec_file), format="turtle")
# check that the specification Graph hosts only one profile
profiles = list(profile.subjects(predicate=RDF.type, object=PROF_NS.Profile))
if len(profiles) == 1:
self._profile_node = profiles[0]
self._profile_specification_graph = profile
# initialize the token and version
self._token, self._version = self.__init_token_version__()
# Check if the profile is overriding an existing profile
existing_profile = self.__profiles_map.get_by_key(self._profile_node.toPython())
if existing_profile:
# Check if the existing profile is different from the current one
if existing_profile.path != profile_path:
# if the profile already exists, log a warning
logger.warning(
"Profile with identifier %s at %s is being overridden "
"by the profile loaded from %s.",
existing_profile.identifier,
existing_profile.path,
profile_path
)
# add the existing profile as an override
self.__add_override__(existing_profile)
# add the profile to the profiles map
self.__profiles_map.add(
self._profile_node.toPython(),
self, token=self.token,
name=self.name, identifier=self.identifier,
token_path=self.__extract_token_from_path__()
) # add the profile to the profiles map
else:
raise ProfileSpecificationError(
message=f"Profile specification file {spec_file} must contain exactly one profile")
def __get_specification_property__(
self, property: str, namespace: Namespace,
pop_first: bool = True, as_Python_object: bool = True) -> Union[str, list[Union[str, URIRef]]]:
assert self._profile_specification_graph is not None, "Profile specification graph not loaded"
values = list(self._profile_specification_graph.objects(self._profile_node, namespace[property]))
if values and as_Python_object:
values = [v.toPython() for v in values]
if pop_first:
return values[0] if values and len(values) >= 1 else None
return values
def __add_override__(self, profile: Profile):
"""
Add an override profile to this profile.
:param profile: the profile that overrides this profile
:type profile: Profile
"""
if not isinstance(profile, Profile):
raise TypeError(f"Expected a Profile instance, got {type(profile)}")
if profile not in self._overrides:
self._overrides.append(profile)
profile._overridden_by.append(self)
@property
def overrides(self) -> list[Profile]:
"""
The list of profiles that override this profile.
"""
return self._overrides
@property
def overridden_by(self) -> list[Profile]:
"""
The list of profiles that are overridden by this profile.
"""
return self._overridden_by
@property
def path(self):
"""
The path of the profile directory
"""
return self._profile_path
@property
def identifier(self) -> str:
"""
The identifier of the profile.
"""
if not self._identifier:
version = self.version
self._identifier = f"{self.token}-{version}" if version else self.token
return self._identifier
@property
def name(self):
"""
The name of the profile as specified in the profile specification file
(i.e., the value of the rdfs: label property in the `profile.ttl` file) or
a default name if the label is not specified.
"""
return self.label or f"Profile {self.uri}"
@property
def profile_node(self):
return self._profile_node
@property
def token(self):
"""
A token that uniquely identifies the profile
as specified in the profile specification file
(i.e., the value of the prof: hasToken property
in the `profile.ttl` file).
"""
return self._token
@property
def uri(self):
"""
The URI of the profile.
"""
return self._profile_node.toPython()
@property
def label(self):
return self.__get_specification_property__("label", RDFS)
@property
def comment(self):
"""
The comment added to the profile in the profile specification file
(i.e., the value of the rdfs: comment property in the `profile.ttl` file).
"""
return self.__get_specification_property__("comment", RDFS)
@property
def version(self):
"""
The version of the profile as specified in the profile specification file
(i.e., the value of the prof: version property in the `profile.ttl` file).
"""
return self._version
@property
def is_profile_of(self) -> list[str]:
"""
The list of profiles that this profile is a profile of
as specified in the profile specification file
(i.e., the value of the prof: isProfileOf property in the `profile.ttl` file).
"""
return self.__get_specification_property__("isProfileOf", PROF_NS, pop_first=False)
@property
def is_transitive_profile_of(self) -> list[str]:
"""
The list of profiles that this profile is a transitive profile of
as specified in the profile specification file
(i.e., the value of the prof: isTransitiveProfileOf property in the `profile.ttl` file).
"""
return self.__get_specification_property__("isTransitiveProfileOf", PROF_NS, pop_first=False)
@property
def parents(self) -> list[Profile]:
"""
The list of profiles that this profile is a profile of
as specified in the profile specification file.
"""
return [self.__profiles_map.get_by_key(_) for _ in self.is_profile_of]
@property
def siblings(self) -> list[Profile]:
"""
The list of profiles that are siblings of this profile
(i.e., profiles that share the same parent profile).
"""
return self.get_sibling_profiles(self)
@property
def readme_file_path(self) -> Path:
"""
The path of the README file of the profile.
"""
return self.path / DEFAULT_PROFILE_README_FILE
@property
def profile_specification_file_path(self) -> Path:
"""
The path of the profile specification file.
"""
return self.path / PROFILE_SPECIFICATION_FILE
@property
def publicID(self) -> Optional[str]:
"""
The public identifier of the RO-Crate which is validated by the profile.
:meta private:
"""
return self._publicID
@property
def severity(self) -> Severity:
"""
The severity of the profile which the profile is loaded with,
i.e., the minimum severity level of the requirements of the profile.
"""
return self._severity
@property
def description(self) -> str:
"""
The description of the profile as specified in the profile specification file
(i.e., the value of the rdfs: comment property in the `profile.ttl` file).
"""
if not self._description:
if self.path and self.readme_file_path.exists():
with open(self.readme_file_path, "r") as f:
self._description = f.read()
else:
self._description = self.comment
return self._description
@property
def requirements(self) -> list[Requirement]:
"""
The list of requirements of the profile.
"""
if not self._requirements:
self._requirements = \
RequirementLoader.load_requirements(self, severity=self.severity)
return self._requirements
def get_requirements(
self, severity: Severity = Severity.REQUIRED,
exact_match: bool = False) -> list[Requirement]:
"""
Get the requirements of the profile with the given severity level.
If the exact_match flag is set to `True`, only the requirements with the exact severity level
are returned; otherwise, the requirements with severity level greater than or equal to
the given severity level are returned.
"""
return [requirement for requirement in self.requirements
if (not exact_match and
(not requirement.severity_from_path or requirement.severity_from_path >= severity)) or
(exact_match and requirement.severity_from_path == severity)]
def get_requirement(self, name: str) -> Optional[Requirement]:
"""
Get the requirement with the given name
"""
for requirement in self.requirements:
if requirement.name == name:
return requirement
return None
def get_requirement_check(self, check_name: str) -> Optional[RequirementCheck]:
"""
Get the requirement check with the given name
"""
for requirement in self.requirements:
check = requirement.get_check(check_name)
if check:
return check
return None
@classmethod
def __get_nested_profiles__(cls, source: str) -> list[str]:
result = []
visited = []
queue = [source]
while len(queue) > 0:
p = queue.pop()
if p not in visited:
visited.append(p)
profile = cls.__profiles_map.get_by_key(p)
inherited_profiles = profile.is_profile_of
if inherited_profiles:
for p in sorted(inherited_profiles, reverse=True):
if p not in visited:
queue.append(p)
if p not in result:
result.insert(0, p)
return result
@property
def inherited_profiles(self) -> list[Profile]:
inherited_profiles = self.is_transitive_profile_of
if not inherited_profiles or len(inherited_profiles) == 0:
inherited_profiles = Profile.__get_nested_profiles__(self.uri)
profile_keys = self.__profiles_map.keys
return [self.__profiles_map.get_by_key(_) for _ in inherited_profiles if _ in profile_keys]
def add_requirement(self, requirement: Requirement):
self._requirements.append(requirement)
def remove_requirement(self, requirement: Requirement):
self._requirements.remove(requirement)
def __eq__(self, other: object) -> bool:
return isinstance(other, Profile) \
and self.identifier == other.identifier \
and self.path == other.path
def __lt__(self, other: object) -> bool:
if not isinstance(other, Profile):
raise TypeError(f"Cannot compare {type(self)} with {type(other)}")
# If one profile is a parent of the other, the parent is greater
if other in self.parents:
return False
# If the number of inherited profiles is the same, compare based on identifier
return self.identifier < other.identifier
def __hash__(self) -> int:
return hash((self.identifier, self.path))
def __repr__(self) -> str:
return (
f'Profile(identifier={self.identifier}, '
f'name={self.name}, '
f'path={self.path}, ' if self.path else ''
f'requirements={self.requirements})'
)
def __str__(self) -> str:
return f"{self.name} ({self.identifier})"
def to_dict(self) -> dict:
return {
"identifier": self.identifier,
"uri": self.uri,
"name": self.name,
"description": self.description
}
@staticmethod
def __extract_version_from_token__(token: str) -> Optional[str]:
if not token:
return None
pattern = r"\Wv?(\d+(\.\d+(\.\d+)?)?)"
matches = re.findall(pattern, token)
if matches:
return matches[-1][0]
return None
def __get_consistent_version__(self, candidate_token: str) -> str:
candidates = {_ for _ in [
self.__get_specification_property__("version", SCHEMA_ORG_NS),
self.__extract_version_from_token__(candidate_token),
self.__extract_version_from_token__(str(self.path.relative_to(self._profiles_base_path))),
self.__extract_version_from_token__(str(self.uri))
] if _ is not None}
if len(candidates) > 1:
raise ProfileSpecificationError(f"Inconsistent versions found: {candidates}")
logger.debug("Candidate versions: %s", candidates)
return candidates.pop() if len(candidates) == 1 else None
def __extract_token_from_path__(self) -> str:
base_path = str(self._profiles_base_path.absolute())
identifier = str(self.path.absolute())
# Check if the path starts with the base path
if not identifier.startswith(base_path):
raise ValueError("Path does not start with the base path")
# Remove the base path from the identifier
identifier = identifier.replace(f"{base_path}/", "")
# Replace slashes with hyphens
identifier = identifier.replace('/', '-')
return identifier
def __init_token_version__(self) -> Tuple[str, str, str]:
# try to extract the token from the specs or the path
candidate_token = self.__get_specification_property__("hasToken", PROF_NS)
if not candidate_token:
candidate_token = self.__extract_token_from_path__()
logger.debug("Candidate token: %s", candidate_token)
# try to extract the version from the specs or the token or the path or the URI
version = self.__get_consistent_version__(candidate_token)
logger.debug("Extracted version: %s", version)
# remove the version from the token if it is present
if version:
candidate_token = re.sub(r"[\W|_]+" + re.escape(version) + r"$", "", candidate_token)
# return the candidate token and version
return candidate_token, version
@classmethod
def __load_profile_path__(cls, profiles_base_path: str,
profile_path: Union[str, Path],
publicID: Optional[str] = None,
severity: Severity = Severity.REQUIRED) -> Profile:
# if the path is a string, convert it to a Path
if isinstance(profile_path, str):
profile_path = Path(profile_path)
# check if the path is a directory
if not profile_path.is_dir():
raise InvalidProfilePath(profile_path)
# create a new profile
profile = Profile(profiles_base_path=profiles_base_path,
profile_path=profile_path, publicID=publicID, severity=severity)
logger.debug("Loaded profile: %s", profile)
return profile
@classmethod
def __load_profiles_paths__(cls, profiles_path: Union[str, Path] = None,
extra_profiles_path: Union[str, Path] = None) -> list[Tuple[Path, Path]]:
"""
Load the paths of the profiles from the given profiles path and extra profiles path.
:param profiles_path: the path to the profiles directory
:type profiles_path: Union[str, Path]
:param extra_profiles_path: an additional path to search for profiles
:type extra_profiles_path: Union[str, Path]
:return: a list of tuples containing the root profile directory and the profile directory
:rtype: list[Tuple[Path, Path]]
:raises InvalidProfilePath: if the profiles path is not a directory
"""
result = []
# set the list of root profile directories
root_profile_directories = [profiles_path] if profiles_path else []
if extra_profiles_path is not None and extra_profiles_path != profiles_path:
root_profile_directories.append(extra_profiles_path)
# collect profiles nested in the root profile directories
for root_profile_directory in root_profile_directories:
# if the path is a string, convert it to a Path
if isinstance(root_profile_directory, str):
root_profile_directory = Path(root_profile_directory)
# check if the path is a directory and raise an error if not
if not root_profile_directory.is_dir():
raise InvalidProfilePath(root_profile_directory)
# if the path is a directory, get the profile directories
result.extend([(root_profile_directory, p.parent)
for p in root_profile_directory.rglob('*.*') if p.name == PROFILE_SPECIFICATION_FILE])
# return the list of profile directories
return result
@classmethod
def load_profiles(cls,
profiles_path: Union[str, Path],
extra_profiles_path: Union[str, Path] = None,
publicID: Optional[str] = None,
severity: Severity = Severity.REQUIRED,
allow_requirement_check_override: bool = True) -> list[Profile]:
# initialize the profiles list
profiles = []
# calculate the list of profiles path as the subdirectories of the profiles path
# where the profile specification file is present
profiles_paths = cls.__load_profiles_paths__(profiles_path,
extra_profiles_path)
# iterate through the directories and load the profiles
for root_profile_path, profile_path in profiles_paths:
logger.debug("Checking profile path: %s %s %r", profile_path,
profile_path.is_dir(), IGNORED_PROFILE_DIRECTORIES)
# check if the profile path is a directory and not in the ignored directories
if profile_path.is_dir() and profile_path not in IGNORED_PROFILE_DIRECTORIES:
profile = Profile.__load_profile_path__(
root_profile_path, profile_path, publicID=publicID, severity=severity)
# if the profile overrides another profile,
# remove the overridden profiles from the list of profiles
# to avoid duplicates and ensure that the most specific profile is used
if profile.overrides:
for overridden_profile in profile.overrides:
if overridden_profile in profiles:
profiles.remove(overridden_profile)
# add the profile to the list of profiles
profiles.append(profile)
logger.debug("Loaded profile: %s (%s)", profile.identifier, profile.path)
# order profiles based on the inheritance hierarchy,
# from the most specific to the most general
# (i.e., from the leaves of the graph to the root)
profiles = sorted(profiles, reverse=True)
# Check for overridden checks
if not allow_requirement_check_override:
# Navigate the profiles to check for overridden checks.
# If the override is not enabled in the settings raise an error.
profiles_checks = set()
# Search for duplicated checks in the profiles
for profile in profiles:
profile_checks = [_ for r in profile.get_requirements() for _ in r.get_checks()]
for check in profile_checks:
# If the check is already present in the list of checks,
# raise an error if the override is not enabled.
if check in profiles_checks:
raise DuplicateRequirementCheck(check.name, profile.identifier)
# Add the check to the list of checks
profiles_checks.add(check)
# order profiles according to the number of profiles they depend on:
# i.e, first the profiles that do not depend on any other profile
# then the profiles that depend on the previous ones, and so on
return sorted(profiles, key=lambda x: f"{len(x.inherited_profiles)}_{x.identifier}")
@classmethod
def get_by_identifier(cls, identifier: str) -> Profile:
"""
Get the profile with the given identifier
:param identifier: the identifier
:type identifier: str
:return: the profile
:rtype: Profile
"""
return cls.__profiles_map.get_by_index("identifier", identifier)
@classmethod
def get_by_uri(cls, uri: str) -> Profile:
"""
Get the profile with the given URI
:param uri: the URI
:type uri: str
:return: the profile
:rtype: Profile
"""
return cls.__profiles_map.get_by_key(uri)
@classmethod
def get_by_name(cls, name: str) -> list[Profile]:
"""
Get the profile with the given name
:param name: the name
:type name: str
:return: the profile
:rtype: Profile
"""
return cls.__profiles_map.get_by_index("name", name)
@classmethod
def get_by_token(cls, token: str) -> Profile:
"""
Get the profile with the given token
:param token: the token
:type token: str
:return: the profile
:rtype: Profile
"""
return cls.__profiles_map.get_by_index("token", token)
@classmethod
def get_sibling_profiles(cls, profile: Profile) -> list[Profile]:
"""
Get the sibling profiles of the given profile
:param profile: the profile
:type profile: Profile
:return: the list of sibling profiles
:rtype: list[Profile]
"""
return [p for p in cls.__profiles_map.values() if profile in p.parents]
@classmethod
def all(cls) -> list[Profile]:
"""
Get all the profiles
:return: the list of profiles
:rtype: list[Profile]
"""
return cls.__profiles_map.values()
@classmethod
def find_in_list(cls, profiles: Collection[Profile],
profile_identifier: str) -> Optional[Profile]:
"""
Find a profile with the given identifier in the given list of profiles
:param profiles: the list of profiles
:type profiles: Collection[Profile]
:param identifier: the identifier
:type identifier: str
:return: the profile if found, None otherwise
:rtype: Optional[Profile]
"""
profile = next((p for p in profiles if p.identifier == profile_identifier), None) or \
next((p for p in profiles if str(p.identifier).replace(f"-{p.version}", '') == profile_identifier), None)
if not profile:
raise ProfileNotFound(profile_identifier)
return profile
class SkipRequirementCheck(Exception):
def __init__(self, check: RequirementCheck, message: str = ""):
self.check = check
self.message = message
def __str__(self):
return f"SkipRequirementCheck(check={self.check})"
@total_ordering
class Requirement(ABC):
"""
Abstract class representing a requirement of a profile.
A requirement is a named set of checks that can be used to validate an RO-Crate.
"""
def __init__(self,
profile: Profile,
name: str = "",
description: Optional[str] = None,
path: Optional[Path] = None,
initialize_checks: bool = True):
"""
Initialize the Requirement instance
:meta private:
"""
self._order_number: Optional[int] = None
self._profile = profile
self._description = description
self._path = path # path of code implementing the requirement
self._level_from_path = None
self._checks: list[RequirementCheck] = []
self._overridden = None
if not name and path:
self._name = get_requirement_name_from_file(path)
else:
self._name = name
# set flag to indicate if the checks have been initialized
self._checks_initialized = False
# initialize the checks if the flag is set
if initialize_checks:
_ = self.__init_checks__()
# assign order numbers to checks
self.__reorder_checks__()
# update the checks initialized flag
self._checks_initialized = True
@property
def order_number(self) -> int:
"""
The order number of the requirement in the profile
:return: the order number
:rtype: int
"""
assert self._order_number is not None
return self._order_number
@property
def identifier(self) -> str:
"""
The identifier of the requirement
:return: the identifier
:rtype: str
"""
return f"{self.profile.identifier}_{self.relative_identifier}"
@property
def relative_identifier(self) -> str:
"""
The relative identifier of the requirement
:return: the relative identifier
:rtype: str
:meta private:
"""
return f"{self.order_number}"
@property
def name(self) -> str:
return self._name
@property
def severity_from_path(self) -> Severity:
return self.requirement_level_from_path.severity if self.requirement_level_from_path else None
@property
def requirement_level_from_path(self) -> RequirementLevel:
if not self._level_from_path:
try:
self._level_from_path = LevelCollection.get(self._path.parent.name)
except ValueError:
logger.debug("The requirement level could not be determined from the path: %s", self._path)
return self._level_from_path
@property
def profile(self) -> Profile:
return self._profile
@property
def description(self) -> str:
if not self._description:
self._description = self.__class__.__doc__.strip(
) if self.__class__.__doc__ else f"Profile Requirement {self.name}"
return self._description
@property
def overridden(self) -> bool:
# Check if the requirement has been overridden.
# The requirement can be considered overridden if all its checks have been overridden
if self._overridden is None:
self._overridden = len([_ for _ in self._checks if not _.overridden]) == 0
return self._overridden
@property
@abstractmethod
def hidden(self) -> bool:
pass
@property
def path(self) -> Optional[Path]:
return self._path
@abstractmethod
def __init_checks__(self) -> list[RequirementCheck]:
pass
def get_checks(self) -> list[RequirementCheck]:
return self._checks.copy()
def get_check(self, name: str) -> Optional[RequirementCheck]:
for check in self._checks:
if check.name == name:
return check
return None
def get_checks_by_level(self, level: RequirementLevel) -> list[RequirementCheck]:
return list({check for check in self._checks if check.level.severity == level.severity})
def __reorder_checks__(self) -> None:
for i, check in enumerate(self._checks):
check.order_number = i + 1
def _do_validate_(self, context: ValidationContext) -> bool:
"""