Skip to main content

tracevault_cli/commands/
init.rs

1use crate::api_client::ApiClient;
2use crate::config::TracevaultConfig;
3use std::fs;
4use std::io;
5use std::path::Path;
6
7pub fn git_remote_url(project_root: &Path) -> Option<String> {
8    std::process::Command::new("git")
9        .args(["remote", "get-url", "origin"])
10        .current_dir(project_root)
11        .output()
12        .ok()
13        .filter(|o| o.status.success())
14        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
15        .filter(|s| !s.is_empty())
16}
17
18fn parse_github_org(remote_url: &str) -> Option<String> {
19    // SSH: git@github.com:softwaremill/tracevault.git
20    if let Some(path) = remote_url.strip_prefix("git@github.com:") {
21        return path.split('/').next().map(String::from);
22    }
23    // HTTPS: https://github.com/softwaremill/tracevault.git
24    if let Some(path) = remote_url
25        .strip_prefix("https://github.com/")
26        .or_else(|| remote_url.strip_prefix("http://github.com/"))
27    {
28        return path.split('/').next().map(String::from);
29    }
30    None
31}
32
33pub async fn init_in_directory(
34    project_root: &Path,
35    server_url: Option<&str>,
36) -> Result<(), io::Error> {
37    // Check for git repository
38    if !project_root.join(".git").exists() {
39        return Err(io::Error::new(
40            io::ErrorKind::NotFound,
41            "Not a git repository. Run 'git init' first.",
42        ));
43    }
44
45    // Create .tracevault/ directory
46    let config_dir = TracevaultConfig::config_dir(project_root);
47    fs::create_dir_all(&config_dir)?;
48    fs::create_dir_all(config_dir.join("sessions"))?;
49    fs::create_dir_all(config_dir.join("cache"))?;
50
51    // Keep all tracevault files local — update root .gitignore
52    update_root_gitignore(project_root)?;
53
54    // Register repo on server if authenticated, server URL known, and git remote available
55    let remote_url = git_remote_url(project_root);
56    if remote_url.is_none() {
57        eprintln!("Warning: no git remote 'origin' configured. Skipping server registration.");
58        eprintln!("Run 'git remote add origin <url>' then 'tracevault sync' to register.");
59    }
60
61    // Extract org slug from GitHub remote URL
62    let org_slug = remote_url.as_deref().and_then(parse_github_org);
63
64    // Write config (include server_url and org_slug if available)
65    let mut config = TracevaultConfig::default();
66    if let Some(url) = server_url {
67        config.server_url = Some(url.to_string());
68    }
69    config.org_slug = org_slug.clone();
70    fs::write(
71        TracevaultConfig::config_path(project_root),
72        config.to_toml(),
73    )?;
74
75    // Install Claude Code hooks into .claude/settings.json
76    install_claude_hooks(project_root)?;
77
78    // Install git hooks
79    install_git_hook(project_root)?;
80    install_post_commit_hook(project_root)?;
81
82    // Detect AI tools in the project
83    let detected = crate::hooks::detect_tools(project_root);
84    for tool in &detected {
85        println!("  Detected: {}", tool.name());
86    }
87
88    let (resolved_url, resolved_token) = crate::api_client::resolve_credentials(project_root);
89    let effective_url = server_url.map(String::from).or(resolved_url);
90
91    if resolved_token.is_none() {
92        eprintln!("Not logged in. Run 'tracevault login' to register this repo with the server.");
93    } else if let (Some(url), Some(remote), Some(slug)) = (effective_url, remote_url, org_slug) {
94        let client = ApiClient::new(&url, resolved_token.as_deref());
95        let repo_name = git_repo_name(project_root);
96
97        match client
98            .register_repo(
99                &slug,
100                crate::api_client::RegisterRepoRequest {
101                    repo_name,
102                    github_url: Some(remote),
103                },
104            )
105            .await
106        {
107            Ok(resp) => {
108                println!("Repo registered on server (id: {})", resp.repo_id);
109                // Save repo_id to config
110                if let Some(mut cfg) = TracevaultConfig::load(project_root) {
111                    cfg.repo_id = Some(resp.repo_id.to_string());
112                    let _ = fs::write(TracevaultConfig::config_path(project_root), cfg.to_toml());
113                }
114            }
115            Err(e) => {
116                let msg = e.to_string();
117                if msg.contains("404") {
118                    eprintln!("Warning: organization '{}' not found on the server.", slug);
119                    eprintln!(
120                        "Create it first at your TraceVault instance, then run 'tracevault sync'."
121                    );
122                } else if msg.contains("403") {
123                    eprintln!("Warning: you are not a member of organization '{}'.", slug);
124                } else {
125                    eprintln!("Warning: could not register repo on server: {e}");
126                }
127            }
128        }
129    }
130
131    Ok(())
132}
133
134fn update_root_gitignore(project_root: &Path) -> Result<(), io::Error> {
135    let path = project_root.join(".gitignore");
136    let existing = if path.exists() {
137        fs::read_to_string(&path)?
138    } else {
139        String::new()
140    };
141
142    let needed: Vec<&str> = [".tracevault/", ".claude/settings.json"]
143        .iter()
144        .copied()
145        .filter(|entry| !existing.lines().any(|line| line.trim() == *entry))
146        .collect();
147
148    if needed.is_empty() {
149        return Ok(());
150    }
151
152    let mut content = existing;
153    if !content.is_empty() && !content.ends_with('\n') {
154        content.push('\n');
155    }
156    content.push_str("\n# TraceVault — local only, do not commit\n");
157    for entry in needed {
158        content.push_str(entry);
159        content.push('\n');
160    }
161
162    fs::write(path, content)
163}
164
165fn git_repo_name(project_root: &Path) -> String {
166    std::process::Command::new("git")
167        .args(["rev-parse", "--show-toplevel"])
168        .current_dir(project_root)
169        .output()
170        .ok()
171        .filter(|o| o.status.success())
172        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
173        .as_deref()
174        .and_then(|p| p.rsplit('/').next())
175        .map(String::from)
176        .unwrap_or_else(|| "unknown".into())
177}
178
179const HOOK_MARKER: &str = "# tracevault:enforce";
180const OLD_HOOK_MARKER: &str = "# tracevault:auto-push";
181
182fn install_git_hook(project_root: &Path) -> Result<(), io::Error> {
183    let hooks_dir = project_root.join(".git/hooks");
184    fs::create_dir_all(&hooks_dir)?;
185
186    let hook_path = hooks_dir.join("pre-push");
187    let tracevault_block = format!(
188        "{HOOK_MARKER}\ntracevault sync 2>/dev/null || true\ntracevault check || {{ echo \"tracevault: policy check failed\"; exit 1; }}\n"
189    );
190
191    if hook_path.exists() {
192        let existing = fs::read_to_string(&hook_path)?;
193
194        // Already has new-style hook
195        if existing.contains(HOOK_MARKER) {
196            return Ok(());
197        }
198
199        // Replace old-style hook block if present
200        if existing.contains(OLD_HOOK_MARKER) {
201            let mut new_content = String::new();
202            let mut skip = false;
203            for line in existing.lines() {
204                if line.contains(OLD_HOOK_MARKER) {
205                    skip = true;
206                    continue;
207                }
208                if skip {
209                    // Skip old tracevault lines (they start with "tracevault " or are empty continuations)
210                    if line.starts_with("tracevault ") {
211                        continue;
212                    }
213                    skip = false;
214                }
215                new_content.push_str(line);
216                new_content.push('\n');
217            }
218            if !new_content.ends_with('\n') {
219                new_content.push('\n');
220            }
221            new_content.push_str(&tracevault_block);
222            fs::write(&hook_path, new_content)?;
223        } else {
224            // Append to existing hook
225            let mut content = existing;
226            if !content.ends_with('\n') {
227                content.push('\n');
228            }
229            content.push_str(&tracevault_block);
230            fs::write(&hook_path, content)?;
231        }
232    } else {
233        let content = format!("#!/bin/sh\n{tracevault_block}");
234        fs::write(&hook_path, content)?;
235    }
236
237    // Make executable
238    #[cfg(unix)]
239    {
240        use std::os::unix::fs::PermissionsExt;
241        let mut perms = fs::metadata(&hook_path)?.permissions();
242        perms.set_mode(0o755);
243        fs::set_permissions(&hook_path, perms)?;
244    }
245
246    Ok(())
247}
248
249const POST_COMMIT_MARKER: &str = "# tracevault:post-commit";
250
251fn install_post_commit_hook(project_root: &Path) -> Result<(), io::Error> {
252    let hooks_dir = project_root.join(".git/hooks");
253    fs::create_dir_all(&hooks_dir)?;
254
255    let hook_path = hooks_dir.join("post-commit");
256    let tracevault_block = format!("{POST_COMMIT_MARKER}\ntracevault commit-push 2>/dev/null &\n");
257
258    if hook_path.exists() {
259        let existing = fs::read_to_string(&hook_path)?;
260
261        if existing.contains(POST_COMMIT_MARKER) {
262            return Ok(());
263        }
264
265        let mut content = existing;
266        if !content.ends_with('\n') {
267            content.push('\n');
268        }
269        content.push_str(&tracevault_block);
270        fs::write(&hook_path, content)?;
271    } else {
272        let content = format!("#!/bin/sh\n{tracevault_block}");
273        fs::write(&hook_path, content)?;
274    }
275
276    #[cfg(unix)]
277    {
278        use std::os::unix::fs::PermissionsExt;
279        let mut perms = fs::metadata(&hook_path)?.permissions();
280        perms.set_mode(0o755);
281        fs::set_permissions(&hook_path, perms)?;
282    }
283
284    Ok(())
285}
286
287fn install_claude_hooks(project_root: &Path) -> Result<(), io::Error> {
288    let claude_dir = project_root.join(".claude");
289    fs::create_dir_all(&claude_dir)?;
290
291    let settings_path = claude_dir.join("settings.json");
292    let mut settings: serde_json::Value = if settings_path.exists() {
293        let content = fs::read_to_string(&settings_path)?;
294        serde_json::from_str(&content).map_err(|e| {
295            io::Error::new(
296                io::ErrorKind::InvalidData,
297                format!("Failed to parse .claude/settings.json: {e}"),
298            )
299        })?
300    } else {
301        serde_json::json!({})
302    };
303
304    let hooks = tracevault_hooks();
305
306    // Merge hooks into existing settings
307    let settings_obj = settings.as_object_mut().ok_or_else(|| {
308        io::Error::new(
309            io::ErrorKind::InvalidData,
310            ".claude/settings.json is not a JSON object",
311        )
312    })?;
313
314    settings_obj.insert("hooks".to_string(), hooks);
315
316    let formatted = serde_json::to_string_pretty(&settings)
317        .map_err(|e| io::Error::other(format!("Failed to serialize settings: {e}")))?;
318    fs::write(&settings_path, formatted)?;
319
320    Ok(())
321}
322
323pub fn tracevault_hooks() -> serde_json::Value {
324    serde_json::json!({
325        "PreToolUse": [{
326            "matcher": "Write|Edit|Bash",
327            "hooks": [{
328                "type": "command",
329                "command": "tracevault stream --event pre-tool-use",
330                "timeout": 10,
331                "statusMessage": "TraceVault: streaming pre-tool event"
332            }]
333        }],
334        "PostToolUse": [{
335            "matcher": "",
336            "hooks": [{
337                "type": "command",
338                "command": "tracevault stream --event post-tool-use",
339                "timeout": 10,
340                "statusMessage": "TraceVault: streaming post-tool event"
341            }]
342        }],
343        "Notification": [{
344            "matcher": "",
345            "hooks": [{
346                "type": "command",
347                "command": "tracevault stream --event notification",
348                "timeout": 10,
349                "statusMessage": "TraceVault: streaming notification"
350            }]
351        }],
352        "Stop": [{
353            "matcher": "",
354            "hooks": [{
355                "type": "command",
356                "command": "tracevault stream --event stop",
357                "timeout": 10,
358                "statusMessage": "TraceVault: finalizing session"
359            }]
360        }]
361    })
362}
363
364#[cfg(test)]
365mod tests {
366    use super::*;
367
368    #[test]
369    fn parse_github_org_ssh() {
370        assert_eq!(
371            parse_github_org("git@github.com:myorg/myrepo.git"),
372            Some("myorg".into())
373        );
374    }
375
376    #[test]
377    fn parse_github_org_https() {
378        assert_eq!(
379            parse_github_org("https://github.com/myorg/myrepo"),
380            Some("myorg".into())
381        );
382    }
383
384    #[test]
385    fn parse_github_org_non_github_returns_none() {
386        assert_eq!(parse_github_org("https://gitlab.com/org/repo"), None);
387    }
388
389    #[test]
390    fn parse_github_org_invalid() {
391        assert_eq!(parse_github_org("not-a-url"), None);
392    }
393}