Skip to main content

artifactize_core/
repository.rs

1//! Git display identity, separate from the artifactize workspace used for execution.
2
3use serde::{Deserialize, Serialize};
4use std::{
5    ffi::OsStr,
6    path::{Path, PathBuf},
7};
8
9#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
10#[serde(rename_all = "camelCase")]
11pub struct Identity {
12    #[serde(
13        default,
14        skip_serializing_if = "Option::is_none",
15        with = "crate::platform::path_serde::option"
16    )]
17    pub common_dir: Option<PathBuf>,
18    #[serde(
19        default,
20        skip_serializing_if = "Option::is_none",
21        with = "crate::platform::path_serde::option"
22    )]
23    pub worktree_path: Option<PathBuf>,
24    #[serde(default, skip_serializing_if = "Option::is_none")]
25    pub branch: Option<String>,
26}
27
28fn git(path: &Path, args: &[&str]) -> Option<Vec<u8>> {
29    let args = [OsStr::new("-C"), path.as_os_str()]
30        .into_iter()
31        .chain(args.iter().map(OsStr::new));
32    crate::process::tool_output("git", args)
33}
34
35fn git_path(path: &Path, arg: &str) -> Option<PathBuf> {
36    let output = git(path, &["rev-parse", "--path-format=absolute", arg])?;
37    // Only the native output terminator is removed; path bytes remain the platform's own.
38    let path = crate::platform::path_from_line(&output);
39    crate::platform::canonicalize(&path).ok()
40}
41
42/// The named Git branch currently checked out, if any.
43pub fn checked_out_branch(path: &Path) -> Option<String> {
44    git(path, &["symbolic-ref", "--quiet", "--short", "HEAD"]).map(|bytes| {
45        crate::platform::output_text(crate::platform::fingerprint_line_ending(&bytes).0)
46            .into_owned()
47    })
48}
49
50/// Missing paths and non-Git workspaces have no inferred Git identity.
51pub fn identify(path: &Path) -> Identity {
52    let common_dir = git_path(path, "--git-common-dir");
53    let worktree_path = git_path(path, "--show-toplevel");
54    if common_dir.is_none() || worktree_path.is_none() {
55        return Identity::default();
56    }
57    let branch = checked_out_branch(path);
58    Identity {
59        common_dir,
60        worktree_path,
61        branch,
62    }
63}
64
65#[derive(Debug, Clone, PartialEq, Eq)]
66pub struct Worktree {
67    pub path: PathBuf,
68    pub branch: Option<String>,
69}
70
71/// The worktrees Git lists for `common_dir` that exist now: one Git marks prunable (its folder
72/// was removed) or whose folder is gone is not a worktree any more. NUL-delimited porcelain does
73/// not quote spaces, tabs or newlines in paths.
74pub fn worktrees(common_dir: &Path) -> Vec<Worktree> {
75    let args = [OsStr::new("--git-dir"), common_dir.as_os_str()]
76        .into_iter()
77        .chain(["worktree", "list", "--porcelain", "-z"].map(OsStr::new));
78    crate::process::tool_output("git", args)
79        .map(|output| parse_worktrees(&output))
80        .unwrap_or_default()
81        .into_iter()
82        .filter(|tree| crate::platform::paths::target_exists(&tree.path).unwrap_or(false))
83        .collect()
84}
85
86fn parse_worktrees(bytes: &[u8]) -> Vec<Worktree> {
87    let mut trees: Vec<(Worktree, bool)> = Vec::new();
88    for field in bytes.split(|byte| *byte == 0) {
89        if let Some(path) = field.strip_prefix(b"worktree ") {
90            let path = crate::platform::path_from_bytes(path);
91            trees.push((Worktree { path, branch: None }, false));
92        } else if let Some((tree, _)) = trees.last_mut()
93            && let Some(branch) = field.strip_prefix(b"branch refs/heads/")
94        {
95            tree.branch = Some(crate::platform::output_text(branch).into_owned());
96        } else if let Some((_, prunable)) = trees.last_mut()
97            && (field == b"prunable" || field.starts_with(b"prunable "))
98        {
99            *prunable = true;
100        }
101    }
102    trees
103        .into_iter()
104        .filter_map(|(tree, prunable)| (!prunable).then_some(tree))
105        .collect()
106}
107
108#[cfg(test)]
109mod tests;