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