-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexport_godot_reference.py
More file actions
307 lines (256 loc) · 9.5 KB
/
export_godot_reference.py
File metadata and controls
307 lines (256 loc) · 9.5 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
#!/usr/bin/env python3
"""
Create a trimmed Unity reference export for rebuilding this project in Godot.
The export is intentionally not a runnable Unity project. It is a dated snapshot
of gameplay code, authored assets, prefab/scene references, and project notes
that are useful while recreating the game in Godot.
"""
from __future__ import annotations
import argparse
import fnmatch
import hashlib
import json
import os
import shutil
import subprocess
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import Iterable
from godot_reference_config import (
DEFAULT_CONFIG_TEMPLATE_PATH,
DEFAULT_OUTPUT_ROOT,
ExportPolicy,
load_policy,
policy_to_config_dict,
write_policy_template,
)
@dataclass(frozen=True)
class ExportedFile:
source: str
destination: str
size: int
sha256: str
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Export a trimmed Godot reference snapshot from the Unity project."
)
parser.add_argument(
"--output-root",
default=None,
help=f"Directory that receives export folders. Default: {DEFAULT_OUTPUT_ROOT}",
)
parser.add_argument(
"--project-root",
default=".",
help="Unity project root to export from. Default: current working directory.",
)
parser.add_argument(
"--config",
default=None,
help="Optional JSON file with include/exclude policy overrides.",
)
parser.add_argument(
"--init-config",
nargs="?",
const=DEFAULT_CONFIG_TEMPLATE_PATH,
default=None,
metavar="FILE",
help=f"Write a tunable JSON config template and exit. Default file: {DEFAULT_CONFIG_TEMPLATE_PATH}",
)
parser.add_argument(
"--force",
action="store_true",
help="Overwrite an existing file when used with --init-config.",
)
parser.add_argument(
"--print-policy",
action="store_true",
help="Print the active merged export policy as JSON and exit.",
)
parser.add_argument(
"--name",
default=None,
help="Export folder name. Default: godot-reference-YYYYmmdd, with -2/-3 suffixes if needed.",
)
parser.add_argument(
"--include-vendors",
action="store_true",
help="Also export known bulky/vendor Unity folders. Not recommended for normal Godot reference packs.",
)
parser.add_argument(
"--no-meta",
action="store_true",
help="Skip Unity .meta files. Default keeps them for GUID traceability.",
)
parser.add_argument(
"--dry-run",
action="store_true",
help="Print what would be exported without copying files.",
)
parser.add_argument(
"--zip",
action="store_true",
help="Create a .zip archive next to the export folder.",
)
return parser.parse_args()
def resolve_project_root(project_root: str) -> Path:
return Path(project_root).expanduser().resolve()
def git_value(root: Path, args: list[str]) -> str:
try:
return subprocess.check_output(
["git", *args],
cwd=root,
text=True,
stderr=subprocess.DEVNULL,
).strip()
except (subprocess.CalledProcessError, FileNotFoundError):
return "unknown"
def normalize(path: Path | str) -> str:
return str(path).replace(os.sep, "/")
def display_path(path: Path, root: Path) -> str:
try:
return normalize(path.relative_to(root))
except ValueError:
return normalize(path)
def is_excluded(relative_path: str, include_vendors: bool, policy: ExportPolicy) -> bool:
paths_to_check = [relative_path]
if relative_path.endswith(".meta"):
paths_to_check.append(relative_path[:-5])
if not include_vendors:
for path in paths_to_check:
for vendor_path in policy.vendor_paths_excluded_by_default:
if path == vendor_path or path.startswith(vendor_path + "/"):
return True
return any(
fnmatch.fnmatch(path, pattern)
for path in paths_to_check
for pattern in policy.exclude_patterns
)
def iter_files(
root: Path,
include_vendors: bool,
keep_meta: bool,
policy: ExportPolicy,
) -> Iterable[Path]:
seen: set[Path] = set()
for include in policy.include_paths:
path = root / include
if not path.exists():
continue
candidates = [path] if path.is_file() else sorted(p for p in path.rglob("*") if p.is_file())
for candidate in candidates:
relative = normalize(candidate.relative_to(root))
if not keep_meta and candidate.suffix == ".meta":
continue
if is_excluded(relative, include_vendors, policy):
continue
if candidate in seen:
continue
seen.add(candidate)
yield candidate
def sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def copy_file(root: Path, destination_root: Path, source: Path) -> ExportedFile:
relative = source.relative_to(root)
destination = destination_root / relative
destination.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(source, destination)
return ExportedFile(
source=normalize(relative),
destination=normalize(destination.relative_to(destination_root)),
size=destination.stat().st_size,
sha256=sha256(destination),
)
def choose_export_name(output_root: Path, requested_name: str | None) -> str:
if requested_name:
return requested_name
date_stamp = datetime.now().strftime("%Y%m%d")
base_name = f"godot-reference-{date_stamp}"
candidate = base_name
suffix = 2
while (output_root / candidate).exists() or (output_root / f"{candidate}.zip").exists():
candidate = f"{base_name}-{suffix}"
suffix += 1
return candidate
def write_manifest(
root: Path,
destination_root: Path,
exported_files: list[ExportedFile],
args: argparse.Namespace,
policy: ExportPolicy,
) -> None:
generated_at = datetime.now(timezone.utc).replace(microsecond=0).isoformat()
status = git_value(root, ["status", "--short"])
manifest = {
"generated_at_utc": generated_at,
"source_project": root.name,
"source_root": normalize(root),
"git_commit": git_value(root, ["rev-parse", "HEAD"]),
"git_branch": git_value(root, ["branch", "--show-current"]),
"git_dirty": bool(status),
"include_vendors": args.include_vendors,
"include_meta": not args.no_meta,
"policy_config": args.config,
"include_paths": policy.include_paths,
"vendor_paths_excluded_by_default": policy.vendor_paths_excluded_by_default,
"exclude_patterns": policy.exclude_patterns,
"file_count": len(exported_files),
"total_bytes": sum(file.size for file in exported_files),
"ai_context_file": "AI_CONTEXT.md",
"note_file": "EXPORT_NOTE.md",
"files": [file.__dict__ for file in exported_files],
}
(destination_root / "EXPORT_NOTE.md").write_text(
policy.export_note
+ "\n"
+ f"Generated at UTC: `{generated_at}`\n\n"
+ f"Source Git commit: `{manifest['git_commit']}`\n\n"
+ f"Source Git branch: `{manifest['git_branch']}`\n\n"
+ f"Source worktree dirty: `{manifest['git_dirty']}`\n\n"
+ f"Exported files: `{manifest['file_count']}`\n\n",
encoding="utf-8",
)
(destination_root / "export_manifest.json").write_text(
json.dumps(manifest, indent=2) + "\n",
encoding="utf-8",
)
ai_context = policy.ai_context_template.replace("{source_project}", root.name)
(destination_root / "AI_CONTEXT.md").write_text(ai_context, encoding="utf-8")
def main() -> int:
args = parse_args()
root = resolve_project_root(args.project_root)
if args.init_config:
path = write_policy_template(args.init_config, overwrite=args.force)
print(f"Wrote config template to {display_path(path, root)}")
return 0
policy = load_policy(args.config)
if args.print_policy:
print(json.dumps(policy_to_config_dict(policy), indent=2))
return 0
output_root = root / (args.output_root or policy.output_root)
export_name = choose_export_name(output_root, args.name)
destination_root = output_root / export_name
files = list(iter_files(root, args.include_vendors, not args.no_meta, policy))
if args.dry_run:
print(f"Would export {len(files)} files to {display_path(destination_root, root)}")
for file in files:
print(normalize(file.relative_to(root)))
return 0
if destination_root.exists():
raise SystemExit(f"Export destination already exists: {destination_root}")
exported_files = [copy_file(root, destination_root, file) for file in files]
write_manifest(root, destination_root, exported_files, args, policy)
if args.zip:
archive_base = output_root / export_name
shutil.make_archive(str(archive_base), "zip", output_root, export_name)
print(f"Exported {len(exported_files)} files to {display_path(destination_root, root)}")
if args.zip:
print(f"Created archive {display_path(output_root / (export_name + '.zip'), root)}")
return 0
if __name__ == "__main__":
raise SystemExit(main())