-
Notifications
You must be signed in to change notification settings - Fork 161
Expand file tree
/
Copy pathbuild.rs
More file actions
249 lines (222 loc) · 7.83 KB
/
Copy pathbuild.rs
File metadata and controls
249 lines (222 loc) · 7.83 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
//! Build script: runs `pnpm run build` inside `web/` to produce the static
//! export that `rust-embed` embeds into the binary.
//!
use std::{env, fs, path::Path, process::Command};
fn main() {
let manifest_dir = match env::var("CARGO_MANIFEST_DIR") {
Ok(dir) => dir,
Err(err) => {
eprintln!(
"build.rs: failed to read CARGO_MANIFEST_DIR environment variable: {err}. \
This is required to locate the `web/` frontend directory."
);
std::process::exit(1);
}
};
let web_dir = Path::new(&manifest_dir).join("web");
// Re-run this build script when any web source file changes.
println!("cargo:rerun-if-changed=web/src");
println!("cargo:rerun-if-changed=web/public");
println!("cargo:rerun-if-changed=web/next.config.ts");
println!("cargo:rerun-if-changed=web/package.json");
println!("cargo:rerun-if-changed=web/pnpm-lock.yaml");
println!("cargo:rerun-if-changed=web/tsconfig.json");
println!("cargo:rerun-if-changed=web/tailwind.config.ts");
// Re-run this build script when relevant environment variables change.
println!("cargo:rerun-if-env-changed=LIBRA_PNPM");
println!("cargo:rerun-if-env-changed=NODE_OPTIONS");
println!("cargo:rerun-if-env-changed=LIBRA_SKIP_WEB_BUILD");
println!("cargo:rerun-if-env-changed=CI");
if should_skip_web_build() {
ensure_stub_web_out(&web_dir);
return;
}
// Normal Cargo build: build the frontend directly inside web/.
run_pnpm_build(&web_dir);
}
fn pnpm_executable() -> String {
if let Ok(value) = env::var("LIBRA_PNPM") {
let trimmed = value.trim();
if !trimmed.is_empty() {
return trimmed.to_string();
}
}
if cfg!(windows) {
"pnpm.cmd".to_string()
} else {
"pnpm".to_string()
}
}
fn should_skip_web_build() -> bool {
match env::var("LIBRA_SKIP_WEB_BUILD") {
Ok(value) => matches!(
value.trim().to_ascii_lowercase().as_str(),
"1" | "true" | "yes" | "on"
),
Err(_) => false,
}
}
fn ensure_stub_web_out(web_dir: &Path) {
let out_dir = web_dir.join("out");
if let Err(err) = fs::create_dir_all(&out_dir) {
panic!(
"failed to create fallback frontend output directory `{}`: {err}",
out_dir.display()
);
}
let index_html = out_dir.join("index.html");
if !index_html.exists() {
let fallback = "<!doctype html><html><body>libra web build skipped</body></html>";
if let Err(err) = fs::write(&index_html, fallback.as_bytes()) {
panic!(
"failed to write fallback frontend file `{}`: {err}",
index_html.display()
);
}
}
// Static assets under `web/public/` (e.g. the remote-access notice pages)
// are served straight out of `WebAssets` at runtime, so the skip-build
// stub must still ship them or the embedded server 500s on paths the
// full Next.js export would have covered. Fail closed: a stub binary
// that compiles without these assets is a silent runtime regression.
copy_public_assets(&web_dir.join("public"), &out_dir);
for required in ["remote-notice/index.html", "remote-notice/zh-CN/index.html"] {
let asset = out_dir.join(required);
if !asset.is_file() {
panic!(
"skip-build web stub is missing required asset `{}`; \
expected it under `web/public/` (tracked in the repository)",
asset.display()
);
}
}
}
/// Recursively copies `web/public/` into `web/out/` without overwriting
/// files the (possibly stale) export already provides. Any enumeration or
/// copy failure aborts the build: silently shipping a stub without public
/// assets would 500 at runtime.
fn copy_public_assets(public_dir: &Path, out_dir: &Path) {
let entries = match fs::read_dir(public_dir) {
Ok(entries) => entries,
Err(err) => panic!(
"failed to enumerate web public assets `{}`: {err}",
public_dir.display()
),
};
for entry in entries {
let entry = match entry {
Ok(entry) => entry,
Err(err) => panic!(
"failed to read web public asset entry under `{}`: {err}",
public_dir.display()
),
};
let source = entry.path();
let target = out_dir.join(entry.file_name());
let file_type = match entry.file_type() {
Ok(file_type) => file_type,
Err(err) => panic!(
"failed to inspect web public asset `{}`: {err}",
source.display()
),
};
if file_type.is_dir() {
if let Err(err) = fs::create_dir_all(&target) {
panic!(
"failed to create stub asset directory `{}`: {err}",
target.display()
);
}
copy_public_assets(&source, &target);
} else if file_type.is_file()
&& !target.exists()
&& let Err(err) = fs::copy(&source, &target)
{
panic!(
"failed to copy public asset `{}` to `{}`: {err}",
source.display(),
target.display()
);
}
}
}
/// Runs `pnpm install` (if needed) then `pnpm run build` inside `web_dir`.
fn run_pnpm_build(web_dir: &Path) {
let pnpm = pnpm_executable();
// Install dependencies if node_modules is missing (e.g. fresh clone).
if !web_dir.join("node_modules").exists() {
let mut install_command = pnpm_command(&pnpm);
let install = install_command
.arg("install")
.arg("--frozen-lockfile")
.current_dir(web_dir)
.status()
.expect("failed to execute `pnpm install` — is pnpm installed?");
if !install.success() {
panic!("`pnpm install` failed (exit code {:?})", install.code());
}
}
let mut build_command = pnpm_command(&pnpm);
let status = build_command
.arg("run")
.arg("build")
.current_dir(web_dir)
.status()
.expect("failed to execute `pnpm run build` — is pnpm installed?");
if !status.success() {
panic!("frontend build failed (exit code {:?})", status.code());
}
}
fn pnpm_command(pnpm: &str) -> Command {
let mut command = Command::new(pnpm);
if env::var_os("CI").is_none() {
// pnpm 11 prompts before purging an incompatible node_modules directory.
// Cargo build scripts are non-interactive, so force pnpm's CI behavior.
command.env("CI", "true");
}
if let Some(node_options) = node_options_with_sqlite_flag() {
command.env("NODE_OPTIONS", node_options);
}
command
}
fn node_options_with_sqlite_flag() -> Option<String> {
const SQLITE_FLAG: &str = "--experimental-sqlite";
let existing = env::var("NODE_OPTIONS").unwrap_or_default();
if existing
.split_whitespace()
.any(|option| option == SQLITE_FLAG)
{
return None;
}
if !node_requires_experimental_sqlite() {
return None;
}
let trimmed = existing.trim();
if trimmed.is_empty() {
Some(SQLITE_FLAG.to_string())
} else {
Some(format!("{trimmed} {SQLITE_FLAG}"))
}
}
fn node_requires_experimental_sqlite() -> bool {
let Ok(output) = Command::new("node")
.arg("-p")
.arg("process.versions.node")
.output()
else {
return false;
};
if !output.status.success() {
return false;
}
let stdout = String::from_utf8_lossy(&output.stdout);
let Some(major) = stdout
.trim()
.split('.')
.next()
.and_then(|part| part.parse::<u64>().ok())
else {
return false;
};
(22..24).contains(&major)
}