Skip to main content

tracevault_cli/commands/
commit_push.rs

1use crate::api_client::{resolve_credentials, ApiClient};
2use crate::config::TracevaultConfig;
3use serde_json::json;
4use std::path::Path;
5use std::process::Command;
6use tracevault_core::streaming::CommitPushRequest;
7
8pub async fn run_commit_push(
9    project_root: &Path,
10    cwd: &Path,
11) -> Result<(), Box<dyn std::error::Error>> {
12    // Config / credentials come from the PRIMARY root (the only place
13    // .tracevault/ exists); git state comes from the invoking worktree (cwd).
14    let config = TracevaultConfig::load(project_root).ok_or("config not found")?;
15    let org_slug = config.org_slug.ok_or("org_slug not configured")?;
16    let repo_id = config.repo_id.ok_or("repo_id not configured")?;
17
18    let (server_url, token) = resolve_credentials(project_root);
19    let server_url = server_url.ok_or("server_url not configured")?;
20    let client = ApiClient::new(&server_url, token.as_deref());
21
22    let req = collect_commit_request(cwd)?;
23
24    match client.push_commit(&org_slug, &repo_id, &req).await {
25        Ok(resp) => {
26            println!(
27                "Commit pushed: {} ({} attributions)",
28                resp.commit_db_id, resp.attributions_count
29            );
30        }
31        Err(e) => {
32            eprintln!("Warning: commit push failed: {e}");
33            // Don't fail — post-commit hook should not block
34        }
35    }
36
37    Ok(())
38}
39
40/// Gather the commit metadata for the HEAD of the worktree at `cwd`.
41/// All git commands run in `cwd` so a sibling worktree reports its own commit.
42fn collect_commit_request(cwd: &Path) -> Result<CommitPushRequest, String> {
43    let run_git = |args: &[&str]| -> Option<String> {
44        Command::new("git")
45            .args(args)
46            .current_dir(cwd)
47            .output()
48            .ok()
49            .filter(|o| o.status.success())
50            .and_then(|o| String::from_utf8(o.stdout).ok())
51            .map(|s| s.trim().to_string())
52    };
53
54    let commit_sha = run_git(&["rev-parse", "HEAD"]).ok_or("failed to get HEAD sha")?;
55    let branch = run_git(&["rev-parse", "--abbrev-ref", "HEAD"]);
56    let author = run_git(&["log", "-1", "--format=%ae"]).unwrap_or_default();
57    let message = run_git(&["log", "-1", "--format=%B"]);
58    let diff_output = run_git(&["diff", "HEAD~1..HEAD", "--unified=3"]);
59    let diff_data = diff_output.map(|diff| parse_diff_to_json(&diff));
60
61    Ok(CommitPushRequest {
62        commit_sha,
63        branch,
64        author,
65        message,
66        diff_data,
67        committed_at: Some(chrono::Utc::now()),
68    })
69}
70
71fn parse_diff_to_json(diff: &str) -> serde_json::Value {
72    let mut files: Vec<serde_json::Value> = Vec::new();
73    let mut current_file: Option<String> = None;
74    let mut current_hunks: Vec<serde_json::Value> = Vec::new();
75    let mut current_hunk_lines: Vec<String> = Vec::new();
76    let mut current_new_start: i64 = 0;
77    let mut current_new_count: i64 = 0;
78
79    let flush_hunk =
80        |hunks: &mut Vec<serde_json::Value>, lines: &mut Vec<String>, start: i64, count: i64| {
81            if !lines.is_empty() {
82                hunks.push(json!({
83                    "new_start": start,
84                    "new_count": count,
85                    "added_lines": lines.clone(),
86                }));
87                lines.clear();
88            }
89        };
90
91    let flush_file = |files: &mut Vec<serde_json::Value>,
92                      file: &Option<String>,
93                      hunks: &mut Vec<serde_json::Value>| {
94        if let Some(path) = file {
95            if !hunks.is_empty() {
96                files.push(json!({
97                    "path": path,
98                    "hunks": hunks.clone(),
99                }));
100                hunks.clear();
101            }
102        }
103    };
104
105    for line in diff.lines() {
106        if let Some(path) = line.strip_prefix("+++ b/") {
107            // Flush previous hunk and file
108            flush_hunk(
109                &mut current_hunks,
110                &mut current_hunk_lines,
111                current_new_start,
112                current_new_count,
113            );
114            flush_file(&mut files, &current_file, &mut current_hunks);
115            current_file = Some(path.to_string());
116        } else if line.starts_with("@@ ") {
117            // Flush previous hunk
118            flush_hunk(
119                &mut current_hunks,
120                &mut current_hunk_lines,
121                current_new_start,
122                current_new_count,
123            );
124            // Parse @@ -old_start,old_count +new_start,new_count @@
125            if let Some(plus_part) = line.split('+').nth(1) {
126                let nums: Vec<&str> = plus_part
127                    .split(' ')
128                    .next()
129                    .unwrap_or("")
130                    .split(',')
131                    .collect();
132                current_new_start = nums.first().and_then(|s| s.parse().ok()).unwrap_or(0);
133                current_new_count = nums.get(1).and_then(|s| s.parse().ok()).unwrap_or(1);
134            }
135        } else if let Some(added) = line.strip_prefix('+') {
136            current_hunk_lines.push(added.to_string());
137        }
138    }
139
140    // Flush remaining
141    flush_hunk(
142        &mut current_hunks,
143        &mut current_hunk_lines,
144        current_new_start,
145        current_new_count,
146    );
147    flush_file(&mut files, &current_file, &mut current_hunks);
148
149    json!({ "files": files })
150}
151
152#[cfg(test)]
153mod tests {
154    use super::*;
155    use crate::test_helpers::{add_worktree, init_git_repo};
156
157    #[test]
158    fn collect_commit_request_reads_sibling_worktree_head() {
159        let tmp = tempfile::tempdir().unwrap();
160        let repo = tmp.path().join("repo");
161        let wt = tmp.path().join("sibling-wt");
162        std::fs::create_dir_all(&repo).unwrap();
163        init_git_repo(&repo);
164        add_worktree(&repo, &wt);
165
166        // Make a commit in the sibling worktree only.
167        std::fs::write(wt.join("f.txt"), "hi").unwrap();
168        for args in [
169            vec!["-C", wt.to_str().unwrap(), "add", "."],
170            vec!["-C", wt.to_str().unwrap(), "commit", "-m", "sibling change"],
171        ] {
172            std::process::Command::new("git")
173                .args(args)
174                .status()
175                .unwrap();
176        }
177
178        let sibling_head = String::from_utf8(
179            std::process::Command::new("git")
180                .args(["-C", wt.to_str().unwrap(), "rev-parse", "HEAD"])
181                .output()
182                .unwrap()
183                .stdout,
184        )
185        .unwrap()
186        .trim()
187        .to_string();
188
189        let req = collect_commit_request(&wt).unwrap();
190        assert_eq!(
191            req.commit_sha, sibling_head,
192            "commit_sha must be the sibling worktree's HEAD, not the primary's"
193        );
194        // run_git trims, so %B ("sibling change\n") arrives trimmed.
195        assert_eq!(req.message.as_deref(), Some("sibling change"));
196    }
197
198    #[test]
199    fn parse_diff_empty() {
200        let result = parse_diff_to_json("");
201        assert!(result["files"].as_array().unwrap().is_empty());
202    }
203
204    #[test]
205    fn parse_diff_single_file() {
206        let diff = "\
207diff --git a/src/main.rs b/src/main.rs
208--- a/src/main.rs
209+++ b/src/main.rs
210@@ -1,3 +1,4 @@
211 fn main() {
212+    println!(\"hello\");
213     other();
214 }
215";
216        let result = parse_diff_to_json(diff);
217        let files = result["files"].as_array().unwrap();
218        assert_eq!(files.len(), 1);
219    }
220
221    #[test]
222    fn parse_diff_extracts_added_lines() {
223        let diff = "\
224diff --git a/a.rs b/a.rs
225--- a/a.rs
226+++ b/a.rs
227@@ -1,2 +1,3 @@
228 existing
229+new_line
230-removed
231";
232        let result = parse_diff_to_json(diff);
233        let files = result["files"].as_array().unwrap();
234        let hunks = files[0]["hunks"].as_array().unwrap();
235        let added = hunks[0]["added_lines"].as_array().unwrap();
236        assert!(added.iter().any(|l| l.as_str().unwrap() == "new_line"));
237    }
238
239    #[test]
240    fn parse_diff_multiple_files() {
241        let diff = "\
242diff --git a/a.rs b/a.rs
243--- a/a.rs
244+++ b/a.rs
245@@ -1 +1,2 @@
246 a
247+b
248diff --git a/c.rs b/c.rs
249--- a/c.rs
250+++ b/c.rs
251@@ -1 +1,2 @@
252 c
253+d
254";
255        let result = parse_diff_to_json(diff);
256        let files = result["files"].as_array().unwrap();
257        assert_eq!(files.len(), 2);
258    }
259}