forked from sarbian/ModuleManager
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodulemanager_deploy.py
More file actions
208 lines (154 loc) · 6.92 KB
/
Copy pathmodulemanager_deploy.py
File metadata and controls
208 lines (154 loc) · 6.92 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
#!/usr/bin/env python3
"""Cross-platform build and deploy script for ModuleManager."""
from __future__ import annotations
import argparse
import os
import re
import shutil
import subprocess
import sys
from pathlib import Path
from typing import Iterable, Optional
MSBUILD_FALLBACKS = [
r"C:\BuildTools2022\MSBuild\Current\Bin\MSBuild.exe",
r"C:\Program Files\Microsoft Visual Studio\2022\BuildTools\MSBuild\Current\Bin\MSBuild.exe",
r"C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Current\Bin\MSBuild.exe",
]
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Build and deploy ModuleManager")
parser.add_argument("--ksp-dir", default="")
parser.add_argument("--build-configuration", default="Release")
parser.add_argument("--project-name", default="ModuleManager")
parser.add_argument("--skip-build", action="store_true")
parser.add_argument("--wipe", action="store_true")
legacy_wipe = any(arg == "--wipe" for arg in sys.argv[1:])
args = parser.parse_args()
args.wipe = args.wipe or legacy_wipe
return args
def read_install_root(repo_root: Path, cli_ksp_dir: str = "") -> Path:
if cli_ksp_dir.strip():
return Path(cli_ksp_dir)
env_kspdir = os.environ.get("KSPDIR")
if env_kspdir:
return Path(env_kspdir)
config_path = repo_root / "deploy.user.cfg"
if not config_path.exists():
raise RuntimeError(f"Expected KSPDIR to be set or {config_path} to exist")
config_text = config_path.read_text(encoding="utf-8")
first_line = config_text.splitlines()[0] if config_text else ""
match = re.match(r"^InstallRoot=(.+)$", first_line)
if not match:
raise RuntimeError("deploy.user.cfg must contain InstallRoot=<path>")
return Path(match.group(1).strip())
def get_ksp_managed_dir(install_root: Path) -> Path:
candidates = [
install_root / "KSP_x64_Data" / "Managed",
install_root / "KSP_Data" / "Managed",
install_root / "Managed",
]
for candidate in candidates:
if (candidate / "Assembly-CSharp.dll").exists():
return candidate
raise RuntimeError(f"Could not locate KSP managed assemblies under install root: {install_root}")
def resolve_msbuild() -> Optional[Path]:
msbuild = shutil.which("msbuild")
if msbuild:
return Path(msbuild)
for candidate in MSBUILD_FALLBACKS:
path = Path(candidate)
if path.exists():
return path
return None
def run_checked(cmd: Iterable[str], cwd: Path) -> None:
result = subprocess.run(list(cmd), cwd=str(cwd), check=False)
if result.returncode != 0:
raise RuntimeError(f"Command failed ({result.returncode}): {' '.join(cmd)}")
def invoke_build_info(repo_root: Path) -> None:
build_script = repo_root / "modulemanager_build.py"
if not build_script.exists():
raise RuntimeError(f"Expected build utility to exist: {build_script}")
# Keep this non-recursive: modulemanager_build.py info does not call modulemanager_deploy.py.
run_checked([sys.executable, str(build_script), "info"], repo_root)
def invoke_build(repo_root: Path, project_file: Path, install_root: Path, configuration: str, skip_build: bool) -> None:
if not project_file.exists():
raise RuntimeError(f"Expected project file to exist: {project_file}")
if skip_build:
print("Skipping build as requested")
return
ksp_managed_dir = get_ksp_managed_dir(install_root)
netfx_root = repo_root / "packages" / "Microsoft.NETFramework.ReferenceAssemblies.net471.1.0.3" / "build"
framework_override = netfx_root / ".NETFramework" / "v4.7.1"
build_props = [
f"/p:Configuration={configuration}",
f"/p:ReferencePath={ksp_managed_dir}",
"/p:RunPostBuildEvent=Never",
"/p:PostBuildEvent=",
]
if (framework_override / "mscorlib.dll").exists():
build_props.append(f"/p:TargetFrameworkRootPath={netfx_root}{os.sep}")
build_props.append(f"/p:FrameworkPathOverride={framework_override}")
msbuild = resolve_msbuild()
if msbuild is not None:
print("Building with MSBuild")
run_checked([str(msbuild), str(project_file), *build_props, "/m"], repo_root)
return
dotnet = shutil.which("dotnet")
if dotnet:
print("Building with dotnet build")
run_checked([dotnet, "build", str(project_file), "-c", configuration, *build_props], repo_root)
return
raise RuntimeError("No build tool found. Install MSBuild (recommended) or dotnet SDK.")
def copy_if_exists(src: Path, dest: Path) -> None:
if src.exists():
shutil.copy2(src, dest)
def wipe_cache_files(game_data_dir: Path) -> int:
wipe_targets = [
game_data_dir / "ModuleManager.ConfigCache",
game_data_dir / "ModuleManager.ConfigCache.pre_update",
game_data_dir / "ModuleManager.ConfigSHA",
game_data_dir / "ModuleManager.ConfigSHA.pre_update",
game_data_dir / "ModuleManager.Physics",
game_data_dir / "ModuleManager.TechTree",
]
wiped = 0
for target in wipe_targets:
if target.exists():
target.unlink()
wiped += 1
return wiped
def main() -> int:
args = parse_args()
repo_root = Path(__file__).resolve().parent
project_dir = repo_root / args.project_name
project_file = project_dir / f"{args.project_name}.csproj"
install_root = read_install_root(repo_root, args.ksp_dir)
game_data_dir = install_root / "GameData"
if not install_root.exists():
raise RuntimeError(f"Expected install root to exist: {install_root}")
if not game_data_dir.exists():
raise RuntimeError(f"Expected GameData directory to exist: {game_data_dir}")
invoke_build_info(repo_root)
invoke_build(repo_root, project_file, install_root, args.build_configuration, args.skip_build)
target_dir = project_dir / "bin" / args.build_configuration
target_path = target_dir / f"{args.project_name}.dll"
if not target_path.exists():
raise RuntimeError(f"Expected build output to exist: {target_path}")
for stale in game_data_dir.glob("ModuleManager.*.dll"):
if stale.name != f"{args.project_name}.dll":
print(f"Removing stale assembly {stale}")
stale.unlink()
print(f"Copying {target_path} to {game_data_dir}")
shutil.copy2(target_path, game_data_dir)
copy_if_exists(target_dir / f"{args.project_name}.pdb", game_data_dir)
copy_if_exists(target_dir / f"{args.project_name}.dll.mdb", game_data_dir)
if args.wipe:
wiped_count = wipe_cache_files(game_data_dir)
print(f"Wipe completed: removed {wiped_count} ModuleManager cache file(s)")
print(f"Build and deploy completed: {install_root}")
return 0
if __name__ == "__main__":
try:
raise SystemExit(main())
except Exception as ex: # pragma: no cover - top-level script error handling
print(str(ex), file=sys.stderr)
raise SystemExit(1)