File size: 6,322 Bytes
476afc0
 
 
 
 
 
 
 
207a1a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
476afc0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
207a1a1
 
 
 
 
25f4255
 
 
 
 
207a1a1
476afc0
 
 
 
 
 
 
 
 
 
 
 
 
207a1a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25f4255
 
 
 
 
 
 
 
 
 
 
 
 
 
 
207a1a1
 
 
 
 
 
 
 
476afc0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
207a1a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import argparse
import json
from pathlib import Path
from typing import Iterable

CONFIG_NAME = "release_config.json"
DEFAULT_MANIFEST_EXCLUDE_DIRS = {
    ".cache",
    ".git",
    ".ipynb_checkpoints",
    ".pytest_cache",
    "__pycache__",
    "essd",
    "essd_scripts",
    "eval_events",
    "eval_picks",
    "eval_snr",
    "figures",
    "notebooks",
    "paired_eval_all",
    "paired_eval_full_pnsn_v3_diff",
    "paired_eval_mini",
    "paired_eval_mini_station_windows",
    "publish_mini",
    "temp",
}
DEFAULT_MANIFEST_EXCLUDE_NAMES = {
    ".DS_Store",
    "manifest_filesizes.tsv",
    "manifest_sha256.txt",
}
DEFAULT_MANIFEST_EXCLUDE_PREFIXES = (
    "._",
    "overleaf-",
    "paired_eval",
)
DEFAULT_MANIFEST_EXCLUDE_SUFFIXES = {
    ".aux",
    ".doc",
    ".docx",
    ".log",
    ".out",
    ".pdf",
    ".pyc",
    ".tex",
    ".zip",
}


def find_release_root(start: str | Path | None = None) -> Path:
    current = Path(start or Path.cwd()).resolve()
    if current.is_file():
        current = current.parent
    for path in (current, *current.parents):
        if (path / CONFIG_NAME).is_file():
            return path
    raise FileNotFoundError(f"Could not find {CONFIG_NAME} from {current}")


def load_config(config_path: str | Path | None = None) -> tuple[Path, dict]:
    if config_path is None:
        root = find_release_root()
        path = root / CONFIG_NAME
    else:
        path = Path(config_path).resolve()
        root = path.parent
    with path.open("r", encoding="utf-8") as f:
        config = json.load(f)
    return root, config


def manifest_paths(root: Path, config: dict, *, code_only: bool = False) -> list[str]:
    manifest = config.get("upload_manifest", "upload_manifest.txt")
    selected: list[str] = []
    if code_only:
        prefixes = tuple(config.get("code_prefixes", ["scripts/", "utils/"]))
        selected.extend(
            rel
            for p in root.rglob("*")
            if p.is_file()
            for rel in [p.relative_to(root).as_posix()]
            if rel.startswith(prefixes) and should_include_in_code_package(p, root, config)
        )
        selected.extend(
            [CONFIG_NAME, "requirements.txt", manifest]
            + list(config.get("integrity_manifests", []))
        )
        return sorted(dict.fromkeys(selected))

    manifest_path = root / manifest
    if not manifest_path.is_file():
        raise FileNotFoundError(f"Manifest not found: {manifest_path}")
    for raw in manifest_path.read_text(encoding="utf-8").splitlines():
        line = raw.strip()
        if not line or line.startswith("#"):
            continue
        selected.append(line)
    return sorted(dict.fromkeys(selected))


def should_include_in_upload_manifest(path: Path, root: Path, config: dict) -> bool:
    rel = path.relative_to(root)
    parts = rel.parts
    name = path.name
    exclude_dirs = set(DEFAULT_MANIFEST_EXCLUDE_DIRS)
    exclude_dirs.update(config.get("manifest_exclude_dirs", []))
    exclude_names = set(DEFAULT_MANIFEST_EXCLUDE_NAMES)
    exclude_names.update(config.get("manifest_exclude_names", []))
    exclude_prefixes = tuple(DEFAULT_MANIFEST_EXCLUDE_PREFIXES) + tuple(
        config.get("manifest_exclude_prefixes", [])
    )
    exclude_suffixes = set(DEFAULT_MANIFEST_EXCLUDE_SUFFIXES)
    exclude_suffixes.update(config.get("manifest_exclude_suffixes", []))

    if any(part in exclude_dirs for part in parts):
        return False
    if parts and parts[0].startswith(exclude_prefixes):
        return False
    if name in exclude_names or name.startswith(exclude_prefixes):
        return False
    if path.suffix in exclude_suffixes:
        return False
    return True


def should_include_in_code_package(path: Path, root: Path, config: dict) -> bool:
    """Keep manuscript source code while excluding generated paper artifacts."""
    rel = path.relative_to(root)
    if not rel.parts or rel.parts[0] != "essd_scripts":
        return should_include_in_upload_manifest(path, root, config)

    if any(part in {"__pycache__", "outputs"} for part in rel.parts):
        return False
    if path.name in DEFAULT_MANIFEST_EXCLUDE_NAMES:
        return False
    if path.name.startswith(DEFAULT_MANIFEST_EXCLUDE_PREFIXES):
        return False
    return path.suffix not in DEFAULT_MANIFEST_EXCLUDE_SUFFIXES


def build_upload_manifest(root: Path, config: dict) -> list[str]:
    selected = []
    for path in root.rglob("*"):
        if path.is_file() and should_include_in_upload_manifest(path, root, config):
            selected.append(path.relative_to(root).as_posix())
    return sorted(dict.fromkeys(selected))


def existing_files(root: Path, paths: Iterable[str]) -> list[tuple[str, Path]]:
    out: list[tuple[str, Path]] = []
    missing: list[str] = []
    for rel in paths:
        path = root / rel
        if path.is_file():
            out.append((rel, path))
        else:
            missing.append(rel)
    if missing:
        raise FileNotFoundError("Missing manifest files:\n" + "\n".join(missing))
    return out


def parser(description: str) -> argparse.ArgumentParser:
    p = argparse.ArgumentParser(description=description)
    p.add_argument("--config", default=None, help="Path to release_config.json")
    p.add_argument("--repo-id", default=None, help="Override destination repo id")
    p.add_argument("--dry-run", action="store_true", help="Print files without uploading")
    p.add_argument("--code-only", action="store_true", help="Upload only scripts, utils, config, and manifest")
    return p


def main() -> None:
    p = argparse.ArgumentParser(description="Build the canonical release upload manifest")
    p.add_argument("--config", default=None, help="Path to release_config.json")
    p.add_argument("--write", action="store_true", help="Write upload_manifest.txt instead of printing paths")
    args = p.parse_args()
    root, config = load_config(args.config)
    paths = build_upload_manifest(root, config)
    if args.write:
        manifest = root / config.get("upload_manifest", "upload_manifest.txt")
        manifest.write_text("\n".join(paths) + "\n", encoding="utf-8")
        print(f"wrote {manifest} ({len(paths)} files)")
    else:
        print("\n".join(paths))


if __name__ == "__main__":
    main()