git-claw 0.2.3

Deterministic git worktree orchestration engine for developers and AI agents
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
//! Git CLI command wrappers for repository discovery, merge, and path resolution.

use crate::infra::error::GitError;
use std::path::{Path, PathBuf};
use std::process::Command;

/// Resolves the Git common directory (`git rev-parse --git-common-dir`)
/// for repository-wide state like `claw/slots.json` and `claw/slots.lock`.
pub fn resolve_git_common_dir(repo_root: Option<&Path>) -> Result<PathBuf, GitError> {
    let mut cmd = Command::new("git");
    if let Some(root) = repo_root {
        cmd.current_dir(root);
    }
    cmd.args(["rev-parse", "--git-common-dir"]);

    let output = cmd.output().map_err(GitError::ProcessFailed)?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        if stderr.contains("not a git repository") {
            return Err(GitError::NotAGitRepository);
        }
        return Err(GitError::CommandFailed {
            command: "git rev-parse --git-common-dir".to_string(),
            message: stderr.trim().to_string(),
        });
    }

    let path_str = String::from_utf8_lossy(&output.stdout).trim().to_string();
    let path = PathBuf::from(path_str);
    let resolved = if path.is_absolute() {
        path
    } else {
        let base = repo_root
            .map(|p| p.to_path_buf())
            .unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")));
        base.join(path)
    };

    Ok(resolved.canonicalize().unwrap_or(resolved))
}

/// Resolves the top-level repository working tree directory (`git rev-parse --show-toplevel`).
pub fn resolve_toplevel(repo_root: Option<&Path>) -> Result<PathBuf, GitError> {
    let mut cmd = Command::new("git");
    if let Some(root) = repo_root {
        cmd.current_dir(root);
    }
    cmd.args(["rev-parse", "--show-toplevel"]);

    let output = cmd.output().map_err(GitError::ProcessFailed)?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        if stderr.contains("not a git repository") {
            return Err(GitError::NotAGitRepository);
        }
        return Err(GitError::CommandFailed {
            command: "git rev-parse --show-toplevel".to_string(),
            message: stderr.trim().to_string(),
        });
    }

    let path_str = String::from_utf8_lossy(&output.stdout).trim().to_string();
    let path = PathBuf::from(path_str);
    Ok(path.canonicalize().unwrap_or(path))
}

/// Extracts repository name from top-level directory.
pub fn resolve_repo_name(toplevel: &Path) -> String {
    toplevel
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("repo")
        .to_string()
}

/// Runs `git worktree prune` to clean internal Git worktree tracking.
pub fn git_worktree_prune(repo_root: Option<&Path>) -> Result<(), GitError> {
    let mut cmd = Command::new("git");
    if let Some(root) = repo_root {
        cmd.current_dir(root);
    }
    cmd.args(["worktree", "prune"]);

    let output = cmd.output().map_err(GitError::ProcessFailed)?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(GitError::CommandFailed {
            command: "git worktree prune".to_string(),
            message: stderr.trim().to_string(),
        });
    }
    Ok(())
}

/// Checks whether the Git repository working tree has any unstaged or staged modifications.
pub fn git_is_clean(repo_root: &Path) -> Result<bool, GitError> {
    let mut cmd = Command::new("git");
    cmd.current_dir(repo_root);
    cmd.args(["status", "--porcelain"]);

    let output = cmd.output().map_err(GitError::ProcessFailed)?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(GitError::CommandFailed {
            command: "git status --porcelain".to_string(),
            message: stderr.trim().to_string(),
        });
    }

    Ok(output.stdout.is_empty())
}

/// Merges `branch` into the currently checked-out branch.
pub fn git_merge(repo_root: &Path, branch: &str) -> Result<(), GitError> {
    let mut cmd = Command::new("git");
    cmd.current_dir(repo_root);
    cmd.args(["merge", branch]);

    let output = cmd.output().map_err(GitError::ProcessFailed)?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(GitError::CommandFailed {
            command: format!("git merge {}", branch),
            message: stderr.trim().to_string(),
        });
    }

    Ok(())
}

/// Switches to the specified branch.
pub fn git_checkout(repo_root: &Path, branch: &str) -> Result<(), GitError> {
    let mut cmd = Command::new("git");
    cmd.current_dir(repo_root);
    cmd.args(["checkout", branch]);

    let output = cmd.output().map_err(GitError::ProcessFailed)?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(GitError::CommandFailed {
            command: format!("git checkout {}", branch),
            message: stderr.trim().to_string(),
        });
    }

    Ok(())
}

/// Resolves the abbreviated HEAD commit hash for a worktree.
pub fn git_head_commit(worktree_path: &Path) -> Result<String, GitError> {
    let mut cmd = Command::new("git");
    cmd.current_dir(worktree_path);
    cmd.args(["rev-parse", "--short", "HEAD"]);

    let output = cmd.output().map_err(GitError::ProcessFailed)?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(GitError::CommandFailed {
            command: "git rev-parse --short HEAD".to_string(),
            message: stderr.trim().to_string(),
        });
    }

    Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
}

/// Creates an annotated Git tag on `target_ref`.
pub fn git_create_annotated_tag(
    repo_root: &Path,
    tag: &str,
    target_ref: &str,
    message: &str,
) -> Result<(), GitError> {
    let mut cmd = Command::new("git");
    cmd.current_dir(repo_root);
    cmd.args(["tag", "-a", tag, target_ref, "-m", message]);

    let output = cmd.output().map_err(GitError::ProcessFailed)?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(GitError::CommandFailed {
            command: format!("git tag -a {} {} -m {}", tag, target_ref, message),
            message: stderr.trim().to_string(),
        });
    }

    Ok(())
}

/// Checks if a branch exists locally in the repository.
///
/// # Example
///
/// ```no_run
/// use std::path::Path;
/// use git_claw::infra::git::git_branch_exists;
///
/// # fn run() -> Result<(), git_claw::infra::error::GitError> {
/// let exists = git_branch_exists(Path::new("."), "main")?;
/// assert!(exists);
/// # Ok(())
/// # }
/// ```
pub fn git_branch_exists(repo_root: &Path, branch: &str) -> Result<bool, GitError> {
    let mut cmd = Command::new("git");
    cmd.current_dir(repo_root);
    let ref_spec = if branch.starts_with("refs/heads/") {
        branch.to_string()
    } else {
        format!("refs/heads/{}", branch)
    };
    cmd.args(["rev-parse", "--verify", &ref_spec]);

    let output = cmd.output().map_err(GitError::ProcessFailed)?;
    Ok(output.status.success())
}

/// Returns the list of configured Git remotes in the repository.
///
/// # Example
///
/// ```no_run
/// use std::path::Path;
/// use git_claw::infra::git::git_get_remotes;
///
/// # fn run() -> Result<(), git_claw::infra::error::GitError> {
/// let remotes = git_get_remotes(Path::new("."))?;
/// assert!(remotes.contains(&"origin".to_string()));
/// # Ok(())
/// # }
/// ```
pub fn git_get_remotes(repo_root: &Path) -> Result<Vec<String>, GitError> {
    let mut cmd = Command::new("git");
    cmd.current_dir(repo_root);
    cmd.arg("remote");

    let output = cmd.output().map_err(GitError::ProcessFailed)?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(GitError::CommandFailed {
            command: "git remote".to_string(),
            message: stderr.trim().to_string(),
        });
    }

    let remotes = String::from_utf8_lossy(&output.stdout)
        .lines()
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .collect();

    Ok(remotes)
}

/// Pushes the branch to the specified remote repository and configures upstream tracking.
///
/// Executes `git push -u <remote> <branch>`.
///
/// # Example
///
/// ```no_run
/// use std::path::Path;
/// use git_claw::infra::git::git_push_upstream;
///
/// # fn run() -> Result<(), git_claw::infra::error::GitError> {
/// git_push_upstream(Path::new("."), "origin", "feature/login")?;
/// # Ok(())
/// # }
/// ```
pub fn git_push_upstream(repo_root: &Path, remote: &str, branch: &str) -> Result<(), GitError> {
    let mut cmd = Command::new("git");
    cmd.current_dir(repo_root);
    cmd.args(["push", "-u", remote, branch]);

    let output = cmd.output().map_err(GitError::ProcessFailed)?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(GitError::CommandFailed {
            command: format!("git push -u {} {}", remote, branch),
            message: stderr.trim().to_string(),
        });
    }

    Ok(())
}

/// Checks whether a branch exists on the specified remote repository.
///
/// Executes `git ls-remote --heads <remote> <branch>`.
///
/// # Example
///
/// ```no_run
/// use std::path::Path;
/// use git_claw::infra::git::git_remote_branch_exists;
///
/// # fn run() -> Result<(), git_claw::infra::error::GitError> {
/// let exists = git_remote_branch_exists(Path::new("."), "origin", "feature/login")?;
/// assert!(exists);
/// # Ok(())
/// # }
/// ```
pub fn git_remote_branch_exists(
    repo_root: &Path,
    remote: &str,
    branch: &str,
) -> Result<bool, GitError> {
    let mut cmd = Command::new("git");
    cmd.current_dir(repo_root);
    cmd.args(["ls-remote", "--heads", remote, branch]);

    let output = cmd.output().map_err(GitError::ProcessFailed)?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(GitError::CommandFailed {
            command: format!("git ls-remote --heads {} {}", remote, branch),
            message: stderr.trim().to_string(),
        });
    }

    let expected_ref = if branch.starts_with("refs/heads/") {
        branch.to_string()
    } else {
        format!("refs/heads/{}", branch)
    };

    let stdout = String::from_utf8_lossy(&output.stdout);
    let exists = stdout
        .lines()
        .any(|line| line.split_whitespace().nth(1) == Some(&expected_ref));

    Ok(exists)
}

/// Deletes a branch from the specified remote repository.
///
/// Executes `git push <remote> --delete <branch>`.
///
/// # Example
///
/// ```no_run
/// use std::path::Path;
/// use git_claw::infra::git::git_delete_remote_branch;
///
/// # fn run() -> Result<(), git_claw::infra::error::GitError> {
/// git_delete_remote_branch(Path::new("."), "origin", "feature/login")?;
/// # Ok(())
/// # }
/// ```
pub fn git_delete_remote_branch(
    repo_root: &Path,
    remote: &str,
    branch: &str,
) -> Result<(), GitError> {
    let mut cmd = Command::new("git");
    cmd.current_dir(repo_root);
    let branch_clean = branch.strip_prefix("refs/heads/").unwrap_or(branch);
    cmd.args(["push", remote, "--delete", branch_clean]);

    let output = cmd.output().map_err(GitError::ProcessFailed)?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(GitError::CommandFailed {
            command: format!("git push {} --delete {}", remote, branch_clean),
            message: stderr.trim().to_string(),
        });
    }

    Ok(())
}

/// Adds specified files to the Git index and records a commit with the given message.
///
/// Executes `git add <files...>` followed by `git commit -m <message>`.
///
/// # Arguments
///
/// * `repo_root` - Path to the repository root directory.
/// * `files` - List of file paths relative to `repo_root` to stage and commit.
/// * `message` - Commit message text.
///
/// # Example
///
/// ```no_run
/// use std::path::Path;
/// use git_claw::infra::git::git_commit_files;
///
/// # fn run() -> Result<(), git_claw::infra::error::GitError> {
/// git_commit_files(Path::new("."), &["Cargo.toml"], "chore: release 0.2.0")?;
/// # Ok(())
/// # }
/// ```
pub fn git_commit_files(repo_root: &Path, files: &[&str], message: &str) -> Result<(), GitError> {
    if files.is_empty() {
        return Ok(());
    }

    let mut add_cmd = Command::new("git");
    add_cmd.current_dir(repo_root);
    add_cmd.arg("add");
    add_cmd.args(files);

    let add_output = add_cmd.output().map_err(GitError::ProcessFailed)?;
    if !add_output.status.success() {
        let stderr = String::from_utf8_lossy(&add_output.stderr);
        return Err(GitError::CommandFailed {
            command: format!("git add {}", files.join(" ")),
            message: stderr.trim().to_string(),
        });
    }

    let mut commit_cmd = Command::new("git");
    commit_cmd.current_dir(repo_root);
    commit_cmd.args(["commit", "-m", message]);

    let commit_output = commit_cmd.output().map_err(GitError::ProcessFailed)?;
    if !commit_output.status.success() {
        let stderr = String::from_utf8_lossy(&commit_output.stderr);
        return Err(GitError::CommandFailed {
            command: format!("git commit -m {}", message),
            message: stderr.trim().to_string(),
        });
    }

    Ok(())
}