agent_hub_runtime/core/project_git/
actions.rs1use anyhow::{bail, Result};
3use std::path::Path;
4use std::process::Command;
5
6pub(super) fn repository(root: &Path) -> Result<git2::Repository> {
7 Ok(git2::Repository::open_ext(
8 root,
9 git2::RepositoryOpenFlags::NO_SEARCH,
10 &[] as &[&Path],
11 )?)
12}
13
14pub(super) fn ensure_ready(repo: &git2::Repository) -> Result<()> {
15 if repo.state() != git2::RepositoryState::Clean || repo.index()?.has_conflicts() {
16 bail!("Resolve the current repository operation and conflicts first");
17 }
18 Ok(())
19}
20
21pub(crate) fn validate_branch_name(branch: &str) -> Result<()> {
22 if branch.is_empty()
23 || branch.starts_with('-')
24 || !git2::Reference::is_valid_name(&format!("refs/heads/{branch}"))
25 {
26 bail!("Enter a valid local branch name");
27 }
28 Ok(())
29}
30
31pub(super) fn git_command(root: &Path) -> Command {
32 let mut command = Command::new("git");
33 command
34 .arg("--literal-pathspecs")
35 .arg("-C")
36 .arg(root)
37 .env("GIT_TERMINAL_PROMPT", "0");
38 for name in [
40 "GIT_DIR",
41 "GIT_WORK_TREE",
42 "GIT_INDEX_FILE",
43 "GIT_COMMON_DIR",
44 ] {
45 command.env_remove(name);
46 }
47 command
48}
49
50pub(crate) fn run_git(root: &Path, args: &[&str]) -> Result<()> {
51 let mut command = git_command(root);
52 command.args(args);
53 match super::super::cli_process::capture_prepared(command, "git", 120, None) {
54 Ok(_) => Ok(()),
55 Err(error) => {
56 let message = format!(
57 "Unable to complete Git operation: {}",
58 super::super::log_sanitize::sanitize(&error)
59 );
60 log::error!("project git operation failed: {message}");
61 Err(anyhow::anyhow!(message))
62 }
63 }
64}
65
66pub fn set_staged(root: &Path, paths: &[String], staged: bool) -> Result<()> {
68 if paths.is_empty() || paths.len() > 2000 {
69 bail!("Select between 1 and 2000 files");
70 }
71 for path in paths {
72 super::validate_file_path(path)?;
73 }
74 let repo = repository(root)?;
75 let mut selected = paths.to_vec();
76 if !staged {
78 let mut options = git2::StatusOptions::new();
79 options.renames_head_to_index(true);
80 for entry in repo.statuses(Some(&mut options))?.iter() {
81 if let Some(delta) = entry.head_to_index() {
82 let old = delta.old_file().path().and_then(Path::to_str);
83 let new = delta.new_file().path().and_then(Path::to_str);
84 if old
85 .into_iter()
86 .chain(new)
87 .any(|path| paths.iter().any(|item| item == path))
88 {
89 for path in old.into_iter().chain(new) {
90 super::validate_file_path(path)?;
91 if !selected.iter().any(|item| item == path) {
92 selected.push(path.to_string());
93 }
94 }
95 }
96 }
97 }
98 }
99 let mut args = if staged {
100 vec!["add", "-A", "--"]
101 } else if repo.head().is_ok() {
102 vec!["reset", "-q", "HEAD", "--"]
103 } else {
104 vec!["rm", "--cached", "-r", "--ignore-unmatch", "--"]
105 };
106 args.extend(selected.iter().map(String::as_str));
107 run_git(root, &args)
108}
109
110pub fn discard(root: &Path, paths: &[String]) -> Result<()> {
113 if paths.is_empty() || paths.len() > 2000 {
114 bail!("Select between 1 and 2000 files");
115 }
116 let repo = repository(root)?;
117 let index = repo.index()?;
118 if index.has_conflicts() {
119 bail!("Resolve index conflicts before discarding changes");
120 }
121 let mut tracked = Vec::new();
122 let mut untracked = Vec::new();
123 for path in paths {
124 super::validate_file_path(path)?;
125 if index.get_path(Path::new(path), 0).is_some() {
126 tracked.push(path.as_str());
127 } else {
128 let status = repo.status_file(Path::new(path))?;
129 if !status.is_wt_new() {
130 bail!("Selected path is not an untracked file: {path}");
131 }
132 let metadata = std::fs::symlink_metadata(root.join(path))?;
133 if metadata.is_dir() {
134 bail!("Select individual files rather than directories: {path}");
135 }
136 untracked.push(path.as_str());
137 }
138 }
139 if !tracked.is_empty() {
140 let mut args = vec!["restore", "--worktree", "--"];
141 args.extend(tracked);
142 run_git(root, &args)?;
143 }
144 if !untracked.is_empty() {
145 let mut args = vec!["clean", "-f", "--"];
146 args.extend(untracked);
147 run_git(root, &args)?;
148 }
149 Ok(())
150}
151
152pub fn commit(root: &Path, message: &str) -> Result<()> {
154 if message.trim().is_empty() || message.len() > 64 * 1024 || message.contains('\0') {
155 bail!("Enter a commit message of at most 64 KiB");
156 }
157 let repo = repository(root)?;
158 if repo.state() != git2::RepositoryState::Clean || repo.index()?.has_conflicts() {
159 bail!("Resolve the current repository operation and conflicts before committing");
160 }
161 run_git(root, &["commit", "-m", message])
162}
163
164#[cfg(test)]
165mod tests;