Skip to main content

lds_git/
lib.rs

1//! Git operations backed by [`git2`], with session-scoped write safety.
2//!
3//! Every public method returns a typed [`output`] struct wrapped in
4//! [`anyhow::Result`]. The lds MCP layer serialises these structs with
5//! `serde_json::to_string_pretty` so callers receive a stable JSON shape and
6//! can access fields directly instead of parsing free-form text.
7//!
8//! Read operations (status, log, diff, worktree_list, remote inspection) are
9//! always available. Write operations (commit, merge, worktree add/remove,
10//! branch delete, reset) require the target path / branch to have been
11//! created — or formally adopted via [`GitModule::session_release`] — by the
12//! current session.
13
14use std::collections::HashSet;
15use std::path::{Path, PathBuf};
16use std::process::Command;
17use std::sync::Arc;
18
19use anyhow::{Context, Result, bail};
20use lds_core::Session;
21
22pub mod output;
23mod read;
24mod remote;
25mod reset;
26mod session;
27mod write;
28
29pub use read::LogFilters;
30
31pub use output::{
32    BranchDeleteOutput, BranchStatusOutput, CommitEntry, CommitOutput, DiffOutput, EntryStatus,
33    FetchOutput, IsPushedOutput, LogOutput, MergeOutput, OtherStagedMode, RemoteEntry,
34    RemoteListOutput, ResetMode, ResetOutput, SessionReleaseOutput, StatusKind, StatusOutput,
35    TagPushedOutput, UnpushedCommitsOutput, WorktreeAddOutput, WorktreeEntry, WorktreeListOutput,
36    WorktreeRemoveOutput, WorktreeStateOutput,
37};
38
39/// Git module instance, tied to a [`Session`].
40///
41/// Tracks which worktrees and branches were created by this session.
42/// Write operations check ownership before proceeding; read operations
43/// bypass the check entirely.
44#[derive(Debug)]
45pub struct GitModule {
46    session: Arc<Session>,
47    /// Worktrees created by this session — only these can be committed to / removed.
48    owned_worktrees: HashSet<PathBuf>,
49    /// Branches created by this session — only these can be deleted / merged.
50    owned_branches: HashSet<String>,
51}
52
53impl GitModule {
54    pub fn new(session: Arc<Session>) -> Self {
55        Self {
56            session,
57            owned_worktrees: HashSet::new(),
58            owned_branches: HashSet::new(),
59        }
60    }
61
62    pub fn register_worktree(&mut self, path: PathBuf) {
63        self.owned_worktrees.insert(path);
64    }
65
66    pub fn is_owned(&self, path: &PathBuf) -> bool {
67        self.owned_worktrees.contains(path)
68    }
69
70    pub fn ensure_owned(&self, path: &PathBuf) -> Result<()> {
71        if !self.is_owned(path) {
72            bail!(
73                "worktree not owned by this session ({}): {}",
74                self.session.id(),
75                path.display()
76            );
77        }
78        Ok(())
79    }
80
81    pub(crate) fn ensure_branch_owned(&self, branch: &str) -> Result<()> {
82        if !self.owned_branches.contains(branch) {
83            bail!(
84                "branch not owned by this session ({}): {}",
85                self.session.id(),
86                branch,
87            );
88        }
89        Ok(())
90    }
91
92    pub(crate) fn worktrees_dir(&self) -> PathBuf {
93        self.session.root().join(".worktrees")
94    }
95
96    pub(crate) fn ensure_session_scope(&self, working_dir: &Path) -> Result<()> {
97        if working_dir == self.session.root() {
98            return Ok(());
99        }
100        let canon = working_dir
101            .canonicalize()
102            .unwrap_or_else(|_| working_dir.to_path_buf());
103        if self.owned_worktrees.contains(&canon) {
104            return Ok(());
105        }
106        if self.owned_worktrees.contains(working_dir) {
107            return Ok(());
108        }
109        bail!(
110            "working_dir not owned by this session ({}): {}",
111            self.session.id(),
112            working_dir.display(),
113        );
114    }
115
116    pub(crate) fn session(&self) -> &Session {
117        &self.session
118    }
119
120    pub(crate) fn register_branch(&mut self, branch: String) {
121        self.owned_branches.insert(branch);
122    }
123
124    pub(crate) fn forget_worktree(&mut self, path: &Path) {
125        let canon = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
126        self.owned_worktrees.remove(&canon);
127        self.owned_worktrees.remove(path);
128    }
129}
130
131/// Run `git <args>` inside `cwd`, returning trimmed stdout on success.
132///
133/// Shared by every module that needs to shell out (fetch, ls-remote,
134/// for-each-ref, worktree, commit, merge, reset). git2-rs is preferred for
135/// pure read paths (statuses, revwalk, diff, graph_ahead_behind) because it
136/// avoids spawning a subprocess and exposes typed data — but anything that
137/// touches credentials, refspecs, or worktree-level porcelain is delegated
138/// here to keep the implementation honest about what stock `git` would do.
139pub(crate) fn git_cmd(cwd: &Path, args: &[&str]) -> Result<String> {
140    let output = Command::new("git")
141        .args(args)
142        .current_dir(cwd)
143        .output()
144        .with_context(|| format!("failed to run git {}", args.first().unwrap_or(&"")))?;
145
146    if !output.status.success() {
147        let stderr = String::from_utf8_lossy(&output.stderr);
148        bail!("git {}: {}", args.first().unwrap_or(&""), stderr.trim());
149    }
150    Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
151}
152
153/// Variant of [`git_cmd`] that merges stdout + stderr so callers can capture
154/// transport diagnostics (typical for `git fetch`).
155pub(crate) fn git_cmd_combined(cwd: &Path, args: &[&str]) -> Result<String> {
156    let output = Command::new("git")
157        .args(args)
158        .current_dir(cwd)
159        .output()
160        .with_context(|| format!("failed to run git {}", args.first().unwrap_or(&"")))?;
161
162    let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
163    let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
164
165    if !output.status.success() {
166        let combined = if stderr.is_empty() { stdout } else { stderr };
167        bail!("git {}: {}", args.first().unwrap_or(&""), combined);
168    }
169
170    Ok(match (stdout.is_empty(), stderr.is_empty()) {
171        (true, true) => String::new(),
172        (false, true) => stdout,
173        (true, false) => stderr,
174        (false, false) => format!("{stdout}\n{stderr}"),
175    })
176}