File size: 2,535 Bytes
5afd2f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Explicit lexical prefix relocation; source references and hashes stay intact."""
from pathlib import Path, PurePosixPath
import hashlib
import json


class PathMapping:
    def __init__(self, declarations=()):
        self.rules = []
        for declaration in declarations:
            if '=' not in declaration:
                raise ValueError('path-map must be SOURCE=DESTINATION')
            source, target = declaration.split('=', 1)
            left, right = PurePosixPath(source), Path(target)
            if (not left.is_absolute() or len(left.parts) == 1 or '..' in left.parts
                    or not right.is_absolute() or '..' in right.parts):
                raise ValueError('Path prefixes must be absolute, non-root and contain no traversal')
            if any(left == a for a, _ in self.rules):
                raise ValueError('Duplicate source prefix')
            if not right.is_dir():
                raise ValueError('Mapped destination directory does not exist')
            self.rules.append((left, right))
        self.rules.sort(key=lambda row: len(row[0].parts), reverse=True)

    def __call__(self, path):
        value = PurePosixPath(str(path))
        if not value.is_absolute() or '..' in value.parts:
            raise ValueError('Input reference must be an absolute path without traversal')
        if not self.rules:
            return Path(path)
        for source, target in self.rules:
            try:
                suffix = value.relative_to(source)
            except ValueError:
                continue
            return target.joinpath(*suffix.parts)
        # Native references inside explicitly mapped views remain valid. This
        # is necessary for new runs generated within the same service view.
        for _, target in self.rules:
            try:
                value.relative_to(PurePosixPath(str(target)))
            except ValueError:
                continue
            return Path(path)
        raise ValueError('Undeclared input path prefix: ' + str(path))

    def as_dicts(self):
        return [{'source': str(left), 'destination': str(right)} for left, right in self.rules]

    def signature(self):
        return hashlib.sha256(json.dumps(self.as_dicts(), sort_keys=True).encode()).hexdigest()

    def load(self, path, kind=None):
        from embodied_pipeline.artifacts import load
        return load(path, kind, **({'path_resolver': self} if self.rules else {}))


def mapping(value=None):
    return value if value is not None else PathMapping()