File size: 3,685 Bytes
0bf6eef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Build an allowlisted staging tree and a nonrecursive SHA-256 manifest."""
import argparse
from hashlib import sha256
import json
from pathlib import Path
import shutil

from research.build import json_bytes
from .audit import ROOT, RELEASE, VERSION, check_history

STAGE = ROOT / '.release-staging' / VERSION
TOP_FILES = ('README.md', 'LICENSE', 'pyproject.toml', 'requirements-dev.txt', 'requirements-release.txt', '.gitattributes', '.gitignore')
ROOTS = ('curation', 'data', 'research', 'scripts', 'tests', 'releases', 'docs')
SUFFIXES = {'.py', '.md', '.json', '.jsonl', '.toml', '.txt', '.lock'}


def source_inventory():
    paths = [ROOT / name for name in TOP_FILES]
    for directory in ROOTS:
        paths.extend(p for p in (ROOT / directory).rglob('*') if p.is_file()
                     and '__pycache__' not in p.parts
                     and (p.suffix in SUFFIXES or p.name in {'Dockerfile', '.dockerignore'}))
    return sorted(set(paths))


def file_inventory(folder):
    return {p.relative_to(folder).as_posix(): {'sha256': sha256(p.read_bytes()).hexdigest(), 'bytes': p.stat().st_size}
            for p in sorted(folder.rglob('*')) if p.is_file() and p.relative_to(folder).as_posix() != 'RELEASE_MANIFEST.json'}


def verify_manifest(folder):
    folder = Path(folder)
    manifest = json.loads((folder / 'RELEASE_MANIFEST.json').read_text())
    if file_inventory(folder) != manifest['files']:
        raise ValueError('Release manifest mismatch: changed, missing, or unexpected files')
    return manifest


def build():
    check_history()
    STAGE.mkdir(parents=True, exist_ok=True)
    sources = source_inventory()
    expected = {p.relative_to(ROOT).as_posix() for p in sources}
    existing = {p.relative_to(STAGE).as_posix() for p in STAGE.rglob('*') if p.is_file() and p.relative_to(STAGE).as_posix() != 'RELEASE_MANIFEST.json'}
    if existing - expected:
        raise ValueError('Unexpected files already present in staging; inspect manually: ' + str(sorted(existing-expected)))
    for source in sources:
        if source.is_symlink() or not source.resolve().is_relative_to(ROOT):
            raise ValueError('Unsafe source path')
        target = STAGE / source.relative_to(ROOT)
        target.parent.mkdir(parents=True, exist_ok=True)
        shutil.copyfile(source, target)
    inventory = file_inventory(STAGE)
    manifest = dict(version=VERSION, status='research_release_candidate',
                    repo_id='Helinity/python-security-benchmark', repo_type='dataset',
                    intended_visibility='private', branch='rc-' + VERSION,
                    files=inventory, file_count=len(inventory), total_bytes=sum(v['bytes'] for v in inventory.values()),
                    checksum_policy='SHA-256 of exact bytes. Manifest excludes itself; preserve its digest externally.',
                    historical_preservation='Additive version directory plus immutable branch/tag and Hub commit history; no deletions.')
    (STAGE / 'RELEASE_MANIFEST.json').write_bytes(json_bytes(manifest))
    verify_manifest(STAGE)
    print(f"Staged {len(inventory)} payload files, {manifest['total_bytes']} bytes at {STAGE}")
    print('Manifest SHA-256:', sha256((STAGE / 'RELEASE_MANIFEST.json').read_bytes()).hexdigest())
    return manifest


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--check', action='store_true')
    args = parser.parse_args()
    if args.check:
        verify_manifest(STAGE)
        print('Staging manifest verified.')
    else:
        build()


if __name__ == '__main__':
    main()