-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.rs
More file actions
214 lines (177 loc) · 5.94 KB
/
build.rs
File metadata and controls
214 lines (177 loc) · 5.94 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
use sha2::{Digest, Sha256};
use std::{
env,
fmt::Write,
fs,
io::{self, Write as IoWrite},
path::{Path, PathBuf},
process::Command,
};
const TARGETS: &[TargetSpec] = &[
TargetSpec {
const_name: "OPENCODE_EMBEDDED_ASSETS",
relative_root: "assets/generated/config/opencode",
include_prefix: "/assets/generated/config/opencode/",
},
TargetSpec {
const_name: "CLAUDE_EMBEDDED_ASSETS",
relative_root: "assets/generated/config/claude",
include_prefix: "/assets/generated/config/claude/",
},
TargetSpec {
const_name: "HOOK_EMBEDDED_ASSETS",
relative_root: "assets/hooks",
include_prefix: "/assets/hooks/",
},
];
struct TargetSpec {
const_name: &'static str,
relative_root: &'static str,
include_prefix: &'static str,
}
fn main() {
if let Err(error) = generate_embedded_asset_manifest() {
panic!("failed to generate setup embedded asset manifest: {error}");
}
emit_git_commit();
}
fn emit_git_commit() {
println!("cargo:rerun-if-env-changed=SCE_GIT_COMMIT");
if let Ok(commit) = env::var("SCE_GIT_COMMIT") {
let commit = commit.trim();
if !commit.is_empty() {
println!("cargo:rustc-env=SCE_GIT_COMMIT={commit}");
return;
}
}
let manifest_dir = match env::var("CARGO_MANIFEST_DIR") {
Ok(value) => PathBuf::from(value),
Err(_) => return,
};
let repository_root = match manifest_dir.parent() {
Some(path) => path.to_path_buf(),
None => return,
};
let git_dir = repository_root.join(".git");
println!("cargo:rerun-if-changed={}", git_dir.join("HEAD").display());
println!(
"cargo:rerun-if-changed={}",
git_dir.join("packed-refs").display()
);
let output = Command::new("git")
.args(["rev-parse", "--short=12", "HEAD"])
.current_dir(&repository_root)
.output();
let Ok(output) = output else {
return;
};
if !output.status.success() {
return;
}
let Ok(commit) = String::from_utf8(output.stdout) else {
return;
};
let commit = commit.trim();
if !commit.is_empty() {
println!("cargo:rustc-env=SCE_GIT_COMMIT={commit}");
}
}
fn generate_embedded_asset_manifest() -> io::Result<()> {
let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").map_err(|e| invalid_data(&e))?);
let out_dir = PathBuf::from(env::var("OUT_DIR").map_err(|e| invalid_data(&e))?);
let destination_path = out_dir.join("setup_embedded_assets.rs");
let mut output = String::new();
for target in TARGETS {
let source_root = manifest_dir.join(target.relative_root);
println!("cargo:rerun-if-changed={}", source_root.display());
let mut files = Vec::new();
collect_files(&source_root, &source_root, &mut files)?;
files.sort_unstable_by(|a, b| a.relative_path.cmp(&b.relative_path));
writeln!(
output,
"pub static {}: &[EmbeddedAsset] = &[",
target.const_name
)
.expect("writing to String buffer should never fail");
for file in &files {
println!("cargo:rerun-if-changed={}", file.absolute_path.display());
let sha256 = compute_sha256(&file.absolute_path)?;
let sha256_literal = format_sha256_literal(&sha256);
writeln!(
output,
" EmbeddedAsset {{ relative_path: \"{}\", bytes: include_bytes!(concat!(env!(\"CARGO_MANIFEST_DIR\"), \"{}{}\")), sha256: {} }},",
escape_for_rust_string(&file.relative_path),
target.include_prefix,
escape_for_rust_string(&file.relative_path),
sha256_literal,
)
.expect("writing to String buffer should never fail");
}
output.push_str("];\n\n");
}
let mut output_file = fs::File::create(destination_path)?;
output_file.write_all(output.as_bytes())
}
#[derive(Debug)]
struct SourceFile {
absolute_path: PathBuf,
relative_path: String,
}
fn collect_files(
base_root: &Path,
current_dir: &Path,
output: &mut Vec<SourceFile>,
) -> io::Result<()> {
for entry in fs::read_dir(current_dir)? {
let entry = entry?;
let path = entry.path();
if entry.file_type()?.is_dir() {
collect_files(base_root, &path, output)?;
continue;
}
let relative_path = path
.strip_prefix(base_root)
.map_err(|_| invalid_data(&"failed to strip source root from file path"))?;
let relative_path = normalize_relative_path(relative_path)?;
output.push(SourceFile {
absolute_path: path,
relative_path,
});
}
Ok(())
}
fn normalize_relative_path(path: &Path) -> io::Result<String> {
let normalized = path
.to_str()
.ok_or_else(|| invalid_data(&"non-UTF-8 config paths are not supported"))?
.replace('\\', "/");
if normalized.is_empty() {
return Err(invalid_data(&"relative path cannot be empty"));
}
if normalized.starts_with('/') {
return Err(invalid_data(&"relative path must not start with '/'"));
}
Ok(normalized)
}
fn escape_for_rust_string(value: &str) -> String {
value.replace('\\', "\\\\").replace('"', "\\\"")
}
fn compute_sha256(path: &Path) -> io::Result<[u8; 32]> {
let bytes = fs::read(path)?;
let digest = Sha256::digest(&bytes);
Ok(digest.into())
}
fn format_sha256_literal(hash: &[u8; 32]) -> String {
let mut output = String::from("[");
for (index, byte) in hash.iter().enumerate() {
if index > 0 {
output.push_str(", ");
}
write!(&mut output, "0x{byte:02x}").expect("writing to String buffer should never fail");
}
output.push(']');
output
}
fn invalid_data<E: ToString>(error: &E) -> io::Error {
io::Error::new(io::ErrorKind::InvalidData, error.to_string())
}