File size: 5,846 Bytes
7ff74f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""目录机械字段的同步与漂移检查:catalog.json 里的 link_type、bindings.subject 由核心重算(核心是权威)。

只执行本地核心代码(core_lib、catalog_reader),输入一次读入、读时核对未被改动。
`python3 -B -m np sync-catalog --catalog spec/questions [--check]`;--check 由 make spec-check 跑。
"""
import hashlib
from pathlib import Path
import sys
import types
import uuid


def sync_catalog(directory, *, check=False):
    """Rebuild the catalog's mechanical fields from core declarations."""
    import copy
    import json
    root, data, _, _ = capture(directory)
    core, namespace = authoritative_core(root, data)
    try:
        catalog = json.loads(data[root / 'catalog.json'])
        rows = [row for form in catalog['forms'] for row in form['versions']]
        ids = [row['id'] for row in rows]
        active = set(core.catalog_reader.active_ids())
        missing, extra = active - core.versions.keys(), core.versions.keys() - active
        if len(ids) != len(set(ids)) or missing or extra:
            raise ValueError(f'catalog coverage mismatch: duplicates={len(ids) - len(set(ids))}, '
                             f'missing core={sorted(missing)}, extra core={sorted(extra)}')
        changed, covered = [], set()
        for form in catalog['forms']:
            for row in form['versions']:
                if row['id'] not in active:
                    continue
                covered.add(row['id'])
                before = copy.deepcopy(row)
                fields = core.catalog_mechanics(core.versions[row['id']])
                link = fields['link_type']['value']
                if link is None:
                    row.pop('link_type', None)
                else:
                    row['link_type'] = link
                if 'subject' in fields:
                    row.setdefault('bindings', {})['subject'] = fields['subject']['value']
                elif 'bindings' in row:
                    row['bindings'].pop('subject', None)
                if row != before:
                    changed.append(row['id'])
        if check and changed:
            raise ValueError('generated catalog fields drifted: ' + ', '.join(changed))
        if changed and not check:
            (root / 'catalog.json').write_text(json.dumps(catalog, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
        return dict(changed=changed, checked=len(covered))
    finally:
        for name in list(sys.modules):
            if name == namespace or name.startswith(namespace + '.'):
                del sys.modules[name]


def capture(directory):
    root = Path(directory).resolve(strict=True)
    for name in ('catalog.json', 'methods.json', 'policy.json', 'core/core_lib.py', 'core/catalog_reader.py'):
        if not (root / name).is_file():
            raise ValueError('authoritative Core/CatalogReader input missing: ' + name)
    paths = [root / 'catalog.json', root / 'methods.json', root / 'policy.json',
             root / 'forms_build.py',
             *sorted((root / 'forms-src').glob('*.json')),
             *sorted((root / 'core').glob('*.py'))]
    data, manifest, stamps = {}, {}, {}
    for path in paths:
        before = path.stat()
        value = path.read_bytes()
        after = path.stat()
        stamp = (after.st_ino, after.st_size, after.st_mtime_ns, after.st_ctime_ns)
        if stamp != (before.st_ino, before.st_size, before.st_mtime_ns, before.st_ctime_ns):
            raise ValueError('input changed during capture: ' + str(path))
        data[path] = value
        manifest[path.relative_to(root).as_posix()] = dict(bytes=len(value), sha256=hashlib.sha256(value).hexdigest())
        stamps[path] = stamp
    return root, data, manifest, stamps


def authoritative_core(root, data):
    """Private module namespace, with a memoized *I/O* boundary, no alternate parser.

    A local Path subclass lets both authoritative readers reuse captured bytes.
    No global pathlib/json patch, and no writes to the supplied core checkout.
    """
    namespace = '_np_compile_' + uuid.uuid4().hex
    package = types.ModuleType(namespace)
    package.__path__ = [str(root / 'core')]
    sys.modules[namespace] = package

    class InputPath(type(Path())):
        def read_text(self, encoding=None, errors=None, **kwargs):
            resolved = Path(self).resolve()
            if resolved not in data:
                raise ValueError('uncaptured core input: ' + str(self))
            return data[resolved].decode(encoding or 'utf-8', errors or 'strict')

    # Execute captured bytes so provenance binds the code actually executed.
    def module(name, directory='core'):
        full = namespace + '.' + name
        result = types.ModuleType(full)
        result.__file__ = str(root / directory / (name + '.py'))
        result.__package__ = namespace
        sys.modules[full] = result
        exec(compile(data[Path(result.__file__)], result.__file__, 'exec'), result.__dict__)
        result.Path = InputPath
        return result

    old = sys.dont_write_bytecode
    try:
        sys.dont_write_bytecode = True
        forms = module('forms_build', '')
        module('catalog_reader')
        lib = module('core_lib')
        lib.load_forms = forms.load
        lib.dump_form = forms.dump
        # query_context is imported lazily by Core; preload its captured version.
        if root / 'core/query_context.py' in data:
            module('query_context')
        core = lib.Core(master=root / 'methods.json', catalog=root / 'catalog.json', locale='en')
    except BaseException:
        for name in list(sys.modules):
            if name == namespace or name.startswith(namespace + '.'):
                del sys.modules[name]
        raise
    finally:
        sys.dont_write_bytecode = old
    return core, namespace