haz-vcs 0.2.0

Git helpers for the haz task runner.
Documentation
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
//! Version-control system integration for `haz`.
//!
//! Currently exposes the git-changeset enumeration required by
//! `haz run`'s `--git-changed` / `--git-staged` /
//! `--git-changed-since <REV>` flags (`EXEC-026`..`EXEC-029`).
//! The implementation shells out to the host `git` binary; no
//! libgit2 or pure-Rust git dependency is taken in v1.
//!
//! Future extensions (other revision-control backends, alternate
//! changeset queries) MAY land here so consumers depend on one
//! VCS crate rather than several.

#![deny(missing_docs)]

use std::collections::BTreeSet;
use std::io;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use std::string::FromUtf8Error;

use haz_domain::path::{CanonicalPath, ParseAbsoluteError};
use snafu::{ResultExt, Snafu};

/// Git-changeset filter selected on the `haz run` invocation.
///
/// The three variants correspond to `EXEC-027`, `EXEC-028`, and
/// `EXEC-029`. The enum makes the intra-family mutex
/// (`EXEC-026`) representable: a single optional value is the
/// type-level guarantee that callers never see two filters at
/// once.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GitFilter {
    /// `--git-changed`: working tree vs `HEAD`, untracked
    /// included (`EXEC-027`).
    Changed,
    /// `--git-staged`: index vs `HEAD`, tracked only
    /// (`EXEC-028`).
    Staged,
    /// `--git-changed-since <REV>`: working tree vs the named
    /// revision, untracked included (`EXEC-029`). The string is
    /// the raw user input; `git rev-parse` validates it later.
    ChangedSince(String),
}

/// Error returned by [`workspace_changeset`].
///
/// Each variant maps to a single failure mode the user can act
/// on: git binary missing, workspace not inside a git repo,
/// unresolvable `<REV>`, diff invocation failure, non-UTF-8 path
/// bytes in the output, or workspace-root canonicalisation
/// failure.
#[derive(Debug, Snafu)]
pub enum GitChangesetError {
    /// `git` could not be invoked (typically: not on PATH).
    #[snafu(display("failed to invoke `git`: {source}"))]
    GitInvocationFailed {
        /// The underlying IO error.
        source: io::Error,
    },

    /// Workspace root is not inside a git repository, surfaced by
    /// a non-zero `rev-parse --show-toplevel` exit (`EXEC-026`).
    #[snafu(display("workspace root `{workspace_root}` is not inside a git repository: {stderr}"))]
    NotAGitRepo {
        /// The workspace root that was probed.
        workspace_root: String,
        /// Trimmed `git` stderr.
        stderr: String,
    },

    /// `<REV>` did not resolve to a commit (`EXEC-029`).
    #[snafu(display("`--git-changed-since {rev}` failed: {stderr}"))]
    UnresolvableRev {
        /// The user-supplied revision string.
        rev: String,
        /// Trimmed `git` stderr.
        stderr: String,
    },

    /// A `git diff` or `git ls-files` invocation returned non-zero.
    #[snafu(display("`git {command}` failed: {stderr}"))]
    GitCommandFailed {
        /// The argv tail used (for diagnostic context).
        command: String,
        /// Trimmed `git` stderr.
        stderr: String,
    },

    /// A path in `git`'s output failed UTF-8 decoding. The
    /// [`CanonicalPath`] type the workspace consumes requires
    /// `str`, so byte-only paths cannot be carried forward.
    #[snafu(display("git emitted a non-UTF-8 path: {source}"))]
    NonUtf8Path {
        /// The underlying decoding error.
        source: FromUtf8Error,
    },

    /// The workspace root could not be canonicalised (typically:
    /// the directory was deleted under the process).
    #[snafu(display("failed to canonicalise workspace root `{}`: {source}", path.display()))]
    CanonicaliseWorkspaceRoot {
        /// The underlying IO error.
        source: io::Error,
        /// The path that failed to canonicalise.
        path: PathBuf,
    },

    /// A changeset path inside the workspace failed
    /// [`CanonicalPath::parse_workspace_absolute`] (e.g., contains
    /// a `..` segment or a bidi control). Such paths cannot
    /// participate in input matching, so surfacing the error is
    /// preferable to silently dropping them.
    #[snafu(display("git emitted a path that is not a valid workspace-absolute path: {input}"))]
    InvalidWorkspacePath {
        /// The offending input.
        input: String,
        /// The underlying parse error.
        source: ParseAbsoluteError,
    },
}

/// Compute the workspace-normalised changeset for the active
/// [`GitFilter`].
///
/// `workspace_root` MUST exist on the host filesystem (the
/// function canonicalises it via [`std::fs::canonicalize`] to
/// align with the symlink-resolved paths `git` emits).
///
/// The returned set contains every changeset path whose canonical
/// host location is inside the canonical workspace root,
/// expressed as a [`CanonicalPath`] (`PATH-004`). Paths outside
/// the workspace root are silently dropped (`EXEC-026`).
///
/// # Errors
///
/// See [`GitChangesetError`].
pub fn workspace_changeset(
    filter: &GitFilter,
    workspace_root: &Path,
) -> Result<BTreeSet<CanonicalPath>, GitChangesetError> {
    let ws_canonical =
        std::fs::canonicalize(workspace_root).context(CanonicaliseWorkspaceRootSnafu {
            path: workspace_root.to_path_buf(),
        })?;
    let repo_root = git_repo_root(&ws_canonical)?;

    let mut diff_args: Vec<&str> = Vec::new();
    let mut include_untracked = false;
    match filter {
        GitFilter::Changed => {
            diff_args.extend(["diff", "--name-only", "-z", "HEAD", "--"]);
            include_untracked = true;
        }
        GitFilter::Staged => {
            diff_args.extend(["diff", "--staged", "--name-only", "-z", "--"]);
        }
        GitFilter::ChangedSince(rev) => {
            diff_args.extend(["diff", "--name-only", "-z", rev.as_str(), "--"]);
            include_untracked = true;
        }
    }

    let diff_output = run_git(&ws_canonical, &diff_args)?;
    let diff_paths = match filter {
        GitFilter::ChangedSince(rev) if !diff_output.status.success() => {
            return Err(GitChangesetError::UnresolvableRev {
                rev: rev.clone(),
                stderr: stderr_string(&diff_output),
            });
        }
        _ if !diff_output.status.success() => {
            return Err(GitChangesetError::GitCommandFailed {
                command: diff_args.join(" "),
                stderr: stderr_string(&diff_output),
            });
        }
        _ => parse_nul_separated(&diff_output.stdout)?,
    };

    let mut all_paths: Vec<String> = diff_paths;
    if include_untracked {
        let ls_args = ["ls-files", "--others", "--exclude-standard", "-z"];
        let ls_output = run_git(&ws_canonical, &ls_args)?;
        if !ls_output.status.success() {
            return Err(GitChangesetError::GitCommandFailed {
                command: ls_args.join(" "),
                stderr: stderr_string(&ls_output),
            });
        }
        all_paths.extend(parse_nul_separated(&ls_output.stdout)?);
    }

    let mut out: BTreeSet<CanonicalPath> = BTreeSet::new();
    for relative in all_paths {
        let absolute = repo_root.join(&relative);
        let Ok(workspace_relative) = absolute.strip_prefix(&ws_canonical) else {
            // Path outside the workspace root: drop per EXEC-026.
            continue;
        };
        if workspace_relative.as_os_str().is_empty() {
            // The repo-root output included the workspace root
            // itself (vanishingly unlikely with diff/ls-files, but
            // explicitly guarded so the empty-segment case can't
            // produce a malformed CanonicalPath).
            continue;
        }
        let Some(rel_str) = workspace_relative.to_str() else {
            // Non-UTF-8 path that nevertheless decoded earlier
            // (raw bytes did UTF-8 cleanly, but the resulting
            // OsStr cannot round-trip). On Unix this is
            // unreachable: `to_str` on a UTF-8-decoded `OsString`
            // succeeds.
            continue;
        };
        let canonical_input = format!("/{rel_str}");
        let canonical = CanonicalPath::parse_workspace_absolute(&canonical_input).context(
            InvalidWorkspacePathSnafu {
                input: canonical_input.clone(),
            },
        )?;
        out.insert(canonical);
    }
    Ok(out)
}

/// Resolve the git-worktree root that encloses `workspace_root`.
///
/// `git -C <workspace_root> rev-parse --show-toplevel` returns the
/// absolute path of the worktree root, or fails with a non-zero
/// exit when the path is not inside any git repository.
fn git_repo_root(workspace_root: &Path) -> Result<PathBuf, GitChangesetError> {
    let output = run_git(workspace_root, &["rev-parse", "--show-toplevel"])?;
    if !output.status.success() {
        return Err(GitChangesetError::NotAGitRepo {
            workspace_root: workspace_root.display().to_string(),
            stderr: stderr_string(&output),
        });
    }
    let stdout = String::from_utf8(output.stdout)
        .map_err(|source| GitChangesetError::NonUtf8Path { source })?;
    Ok(PathBuf::from(stdout.trim_end_matches('\n')))
}

fn run_git(cwd: &Path, args: &[&str]) -> Result<Output, GitChangesetError> {
    Command::new("git")
        .arg("-C")
        .arg(cwd)
        .args(args)
        .output()
        .context(GitInvocationFailedSnafu)
}

fn stderr_string(output: &Output) -> String {
    String::from_utf8_lossy(&output.stderr).trim().to_owned()
}

/// Split `bytes` on `\0` and return each entry as a UTF-8 string.
///
/// `git`'s `-z` mode emits entries separated by `\0`; the trailing
/// separator after the last entry produces an empty tail that is
/// filtered out.
fn parse_nul_separated(bytes: &[u8]) -> Result<Vec<String>, GitChangesetError> {
    let mut out = Vec::new();
    for segment in bytes.split(|b| *b == 0) {
        if segment.is_empty() {
            continue;
        }
        out.push(
            String::from_utf8(segment.to_vec())
                .map_err(|source| GitChangesetError::NonUtf8Path { source })?,
        );
    }
    Ok(out)
}

#[cfg(test)]
mod tests {
    use super::{GitChangesetError, GitFilter, workspace_changeset};
    use std::fs;
    use std::path::Path;
    use std::process::Command;

    /// Run `git` with `args` inside `cwd`, asserting success. The
    /// test fixtures use this to script tracked, staged, and
    /// untracked states.
    fn git(cwd: &Path, args: &[&str]) {
        let output = Command::new("git")
            .arg("-C")
            .arg(cwd)
            .args(args)
            .output()
            .expect("git binary must be available on PATH for these tests");
        assert!(
            output.status.success(),
            "git {} failed:\nstdout: {}\nstderr: {}",
            args.join(" "),
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr),
        );
    }

    /// Initialise a git repo at `root` with a minimal identity so
    /// `git commit` succeeds in CI environments that lack global
    /// config.
    fn init_repo(root: &Path) {
        git(root, &["init", "--quiet", "--initial-branch=main"]);
        git(root, &["config", "user.email", "test@example.invalid"]);
        git(root, &["config", "user.name", "Test"]);
        git(root, &["config", "commit.gpgsign", "false"]);
    }

    fn write(path: &Path, contents: &str) {
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).unwrap();
        }
        fs::write(path, contents).unwrap();
    }

    /// Render the changeset as a `Vec<String>` for deterministic
    /// test assertions. `BTreeSet<CanonicalPath>` iterates in the
    /// canonical lexicographic order on segments, so the order
    /// here matches the test expectations directly.
    fn collect_strings(
        set: &std::collections::BTreeSet<haz_domain::path::CanonicalPath>,
    ) -> Vec<String> {
        set.iter().map(ToString::to_string).collect()
    }

    #[test]
    fn not_a_repo_surfaces_typed_error() {
        let tempdir = tempfile::TempDir::new().unwrap();
        let err = workspace_changeset(&GitFilter::Changed, tempdir.path()).unwrap_err();
        match err {
            GitChangesetError::NotAGitRepo { .. } => {}
            other => panic!("unexpected error: {other:?}"),
        }
    }

    #[test]
    fn exec_027_git_changed_lists_unstaged_modification() {
        let tempdir = tempfile::TempDir::new().unwrap();
        let root = tempdir.path();
        init_repo(root);
        write(&root.join("a.txt"), "v1\n");
        git(root, &["add", "."]);
        git(root, &["commit", "--quiet", "-m", "init"]);
        write(&root.join("a.txt"), "v2\n");

        let set = workspace_changeset(&GitFilter::Changed, root).unwrap();
        assert_eq!(collect_strings(&set), vec!["/a.txt"]);
    }

    #[test]
    fn exec_027_git_changed_lists_staged_modification() {
        let tempdir = tempfile::TempDir::new().unwrap();
        let root = tempdir.path();
        init_repo(root);
        write(&root.join("a.txt"), "v1\n");
        git(root, &["add", "."]);
        git(root, &["commit", "--quiet", "-m", "init"]);
        write(&root.join("a.txt"), "v2\n");
        git(root, &["add", "a.txt"]);

        let set = workspace_changeset(&GitFilter::Changed, root).unwrap();
        assert_eq!(collect_strings(&set), vec!["/a.txt"]);
    }

    #[test]
    fn exec_027_git_changed_includes_untracked() {
        let tempdir = tempfile::TempDir::new().unwrap();
        let root = tempdir.path();
        init_repo(root);
        write(&root.join("seed.txt"), "x\n");
        git(root, &["add", "."]);
        git(root, &["commit", "--quiet", "-m", "init"]);
        write(&root.join("new.txt"), "y\n");

        let set = workspace_changeset(&GitFilter::Changed, root).unwrap();
        assert_eq!(collect_strings(&set), vec!["/new.txt"]);
    }

    #[test]
    fn git_staged_excludes_unstaged_and_untracked() {
        let tempdir = tempfile::TempDir::new().unwrap();
        let root = tempdir.path();
        init_repo(root);
        write(&root.join("a.txt"), "v1\n");
        write(&root.join("b.txt"), "v1\n");
        git(root, &["add", "."]);
        git(root, &["commit", "--quiet", "-m", "init"]);

        // Stage a.txt; leave b.txt unstaged; create untracked u.txt.
        write(&root.join("a.txt"), "v2\n");
        git(root, &["add", "a.txt"]);
        write(&root.join("b.txt"), "v2\n");
        write(&root.join("u.txt"), "u\n");

        let set = workspace_changeset(&GitFilter::Staged, root).unwrap();
        assert_eq!(collect_strings(&set), vec!["/a.txt"]);
    }

    #[test]
    fn git_changed_since_lists_files_since_rev() {
        let tempdir = tempfile::TempDir::new().unwrap();
        let root = tempdir.path();
        init_repo(root);
        write(&root.join("a.txt"), "v1\n");
        git(root, &["add", "."]);
        git(root, &["commit", "--quiet", "-m", "init"]);
        git(root, &["tag", "base"]);
        write(&root.join("a.txt"), "v2\n");
        git(root, &["add", "a.txt"]);
        git(root, &["commit", "--quiet", "-m", "tick"]);
        write(&root.join("b.txt"), "b\n");

        let filter = GitFilter::ChangedSince("base".to_owned());
        let set = workspace_changeset(&filter, root).unwrap();
        // a.txt (committed since base) plus b.txt (untracked).
        assert_eq!(collect_strings(&set), vec!["/a.txt", "/b.txt"]);
    }

    #[test]
    fn git_changed_since_unresolvable_rev_errors() {
        let tempdir = tempfile::TempDir::new().unwrap();
        let root = tempdir.path();
        init_repo(root);
        write(&root.join("a.txt"), "v1\n");
        git(root, &["add", "."]);
        git(root, &["commit", "--quiet", "-m", "init"]);

        let filter = GitFilter::ChangedSince("does-not-exist".to_owned());
        let err = workspace_changeset(&filter, root).unwrap_err();
        match err {
            GitChangesetError::UnresolvableRev { rev, .. } => {
                assert_eq!(rev, "does-not-exist");
            }
            other => panic!("unexpected error: {other:?}"),
        }
    }

    #[test]
    fn workspace_inside_repo_subdir_returns_workspace_relative_paths() {
        // Git repo at /repo; workspace at /repo/ws. The diff
        // output is repo-relative (`ws/a.txt`); the function MUST
        // strip the workspace prefix and emit `/a.txt`.
        let tempdir = tempfile::TempDir::new().unwrap();
        let repo_root = tempdir.path();
        let workspace_root = repo_root.join("ws");
        fs::create_dir_all(&workspace_root).unwrap();
        init_repo(repo_root);
        write(&workspace_root.join("a.txt"), "v1\n");
        write(&repo_root.join("outside.txt"), "z\n");
        git(repo_root, &["add", "."]);
        git(repo_root, &["commit", "--quiet", "-m", "init"]);
        write(&workspace_root.join("a.txt"), "v2\n");
        // Also modify a file OUTSIDE the workspace; the function
        // MUST drop it.
        write(&repo_root.join("outside.txt"), "y\n");

        let set = workspace_changeset(&GitFilter::Changed, &workspace_root).unwrap();
        assert_eq!(collect_strings(&set), vec!["/a.txt"]);
    }
}