-
Notifications
You must be signed in to change notification settings - Fork 716
Expand file tree
/
Copy pathsource_state.rs
More file actions
277 lines (241 loc) · 8.4 KB
/
source_state.rs
File metadata and controls
277 lines (241 loc) · 8.4 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
use super::{BuildInfo, SourceState};
use anyhow::Result;
use chrono::Utc;
use std::path::{Path, PathBuf};
use std::process::Command;
const FNV_OFFSET_BASIS_64: u64 = 0xcbf29ce484222325;
const FNV_PRIME_64: u64 = 0x100000001b3;
fn stable_hash_update(state: &mut u64, bytes: &[u8]) {
for byte in bytes {
*state ^= u64::from(*byte);
*state = state.wrapping_mul(FNV_PRIME_64);
}
}
fn stable_hash_str(state: &mut u64, value: &str) {
stable_hash_update(state, value.as_bytes());
}
fn stable_hash_hex(bytes: &[u8]) -> String {
let mut state = FNV_OFFSET_BASIS_64;
stable_hash_update(&mut state, bytes);
format!("{state:016x}")
}
fn canonicalize_or_self(path: &Path) -> PathBuf {
std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
}
fn hash_path_scope(path: &Path) -> String {
stable_hash_hex(canonicalize_or_self(path).to_string_lossy().as_bytes())
}
fn git_output_bytes(repo_dir: &Path, args: &[&str]) -> Result<Vec<u8>> {
let output = Command::new("git")
.args(args)
.current_dir(repo_dir)
.output()?;
if !output.status.success() {
anyhow::bail!(
"git {} failed with status {:?}",
args.join(" "),
output.status.code()
);
}
Ok(output.stdout)
}
fn git_common_dir(repo_dir: &Path) -> Result<PathBuf> {
let output = git_output_bytes(repo_dir, &["rev-parse", "--git-common-dir"])?;
let raw = String::from_utf8_lossy(&output).trim().to_string();
if raw.is_empty() {
anyhow::bail!("git rev-parse --git-common-dir returned an empty path");
}
let path = PathBuf::from(raw);
let absolute = if path.is_absolute() {
path
} else {
repo_dir.join(path)
};
Ok(canonicalize_or_self(&absolute))
}
pub fn repo_scope_key(repo_dir: &Path) -> Result<String> {
Ok(hash_path_scope(&git_common_dir(repo_dir)?))
}
pub fn worktree_scope_key(repo_dir: &Path) -> Result<String> {
Ok(hash_path_scope(repo_dir))
}
fn append_untracked_file_fingerprint(state: &mut u64, repo_dir: &Path, relative: &str) {
stable_hash_str(state, relative);
let path = repo_dir.join(relative);
match std::fs::metadata(&path) {
Ok(meta) if meta.is_file() => {
stable_hash_update(state, &meta.len().to_le_bytes());
match std::fs::read(&path) {
Ok(bytes) => stable_hash_update(state, &bytes),
Err(err) => stable_hash_str(state, &format!("read-error:{err}")),
}
}
Ok(meta) => {
stable_hash_str(state, if meta.is_dir() { "dir" } else { "other" });
}
Err(err) => stable_hash_str(state, &format!("missing:{err}")),
}
}
pub fn current_source_state(repo_dir: &Path) -> Result<SourceState> {
let short_hash = current_git_hash(repo_dir)?;
let full_hash = current_git_hash_full(repo_dir)?;
let status = git_output_bytes(
repo_dir,
&["status", "--porcelain=v1", "-z", "--untracked-files=all"],
)?;
let diff = git_output_bytes(repo_dir, &["diff", "--binary", "HEAD"])?;
let untracked = git_output_bytes(
repo_dir,
&["ls-files", "--others", "--exclude-standard", "-z"],
)?;
let dirty = !status.is_empty();
let changed_paths = status
.split(|byte| *byte == 0)
.filter(|entry| !entry.is_empty())
.count();
let mut state = FNV_OFFSET_BASIS_64;
stable_hash_str(&mut state, &full_hash);
stable_hash_update(&mut state, &status);
stable_hash_update(&mut state, &diff);
for path in untracked
.split(|byte| *byte == 0)
.filter(|entry| !entry.is_empty())
{
let relative = String::from_utf8_lossy(path);
append_untracked_file_fingerprint(&mut state, repo_dir, &relative);
}
let fingerprint = format!("{state:016x}");
let version_label = if dirty {
format!("{}-dirty-{}", short_hash, &fingerprint[..12])
} else {
short_hash.clone()
};
Ok(SourceState {
repo_scope: repo_scope_key(repo_dir)?,
worktree_scope: worktree_scope_key(repo_dir)?,
short_hash,
full_hash,
dirty,
fingerprint,
version_label,
changed_paths,
})
}
pub fn ensure_source_state_matches(repo_dir: &Path, expected: &SourceState) -> Result<SourceState> {
let current = current_source_state(repo_dir)?;
if current.fingerprint != expected.fingerprint {
anyhow::bail!(
"Source tree drift detected while waiting/building (expected {}, now {}). Refusing to publish or attach this build to the original request.",
expected.fingerprint,
current.fingerprint
);
}
Ok(current)
}
pub fn repo_build_version(repo_dir: &Path) -> Result<String> {
Ok(current_source_state(repo_dir)?.version_label)
}
/// Get the current git hash
pub fn current_git_hash(repo_dir: &Path) -> Result<String> {
let output = Command::new("git")
.args(["rev-parse", "--short", "HEAD"])
.current_dir(repo_dir)
.output()?;
if !output.status.success() {
anyhow::bail!("Failed to get git hash");
}
Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
}
/// Get the full git hash
pub fn current_git_hash_full(repo_dir: &Path) -> Result<String> {
let output = Command::new("git")
.args(["rev-parse", "HEAD"])
.current_dir(repo_dir)
.output()?;
if !output.status.success() {
anyhow::bail!("Failed to get git hash");
}
Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
}
/// Get the git diff for uncommitted changes
pub fn current_git_diff(repo_dir: &Path) -> Result<String> {
let output = Command::new("git")
.args(["diff", "--binary", "HEAD"])
.current_dir(repo_dir)
.output()?;
Ok(String::from_utf8_lossy(&output.stdout).to_string())
}
pub fn current_git_patch_with_untracked(repo_dir: &Path) -> Result<String> {
let mut patch = current_git_diff(repo_dir)?;
let untracked = git_output_bytes(
repo_dir,
&["ls-files", "--others", "--exclude-standard", "-z"],
)?;
for path in untracked
.split(|byte| *byte == 0)
.filter(|entry| !entry.is_empty())
{
let relative = String::from_utf8_lossy(path);
let path = relative.as_ref();
let null_device = if cfg!(windows) { "NUL" } else { "/dev/null" };
let output = Command::new("git")
.args(["diff", "--binary", "--no-index", "--", null_device, path])
.current_dir(repo_dir)
.output()?;
match output.status.code() {
Some(0) | Some(1) => {}
code => {
anyhow::bail!(
"git diff --no-index for untracked file {} failed with status {:?}",
path,
code
);
}
}
if !patch.is_empty() && !patch.ends_with('\n') {
patch.push('\n');
}
patch.push_str(&String::from_utf8_lossy(&output.stdout));
if !output.stderr.is_empty() {
let stderr = String::from_utf8_lossy(&output.stderr);
if !stderr.trim().is_empty() {
anyhow::bail!(
"git diff --no-index for untracked file {} wrote stderr: {}",
path,
stderr.trim()
);
}
}
}
Ok(patch)
}
/// Check if working tree is dirty
pub fn is_working_tree_dirty(repo_dir: &Path) -> Result<bool> {
let output = Command::new("git")
.args(["status", "--porcelain"])
.current_dir(repo_dir)
.output()?;
Ok(!output.stdout.is_empty())
}
/// Get commit message for a hash
pub fn get_commit_message(repo_dir: &Path, hash: &str) -> Result<String> {
let output = Command::new("git")
.args(["log", "-1", "--format=%s", hash])
.current_dir(repo_dir)
.output()?;
Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
}
/// Build info for current state
pub fn current_build_info(repo_dir: &Path) -> Result<BuildInfo> {
let source = current_source_state(repo_dir)?;
let commit_message = get_commit_message(repo_dir, &source.short_hash).ok();
Ok(BuildInfo {
hash: source.short_hash,
full_hash: source.full_hash,
built_at: Utc::now(),
commit_message,
dirty: source.dirty,
source_fingerprint: Some(source.fingerprint),
version_label: Some(source.version_label),
})
}