Skip to main content

tracevault_cli/commands/
sync.rs

1use crate::api_client::ApiClient;
2use crate::commands::init::persist_repo_binding;
3use crate::config::TracevaultConfig;
4use crate::credentials::resolve_credentials;
5use crate::resolution::{git_remote_url, git_repo_name, plan_registration, RegistrationPlan};
6use std::path::Path;
7
8pub async fn sync_repo(project_root: &Path) -> Result<(), Box<dyn std::error::Error>> {
9    let (server_url, credential) = resolve_credentials(project_root)?;
10
11    let server_url = match server_url {
12        Some(url) => url,
13        None => {
14            eprintln!("No server_url configured. Skipping sync.");
15            return Ok(());
16        }
17    };
18
19    if credential.is_none() {
20        eprintln!("Not logged in. Run 'tracevault login' to sync.");
21        return Ok(());
22    }
23
24    let remote = match git_remote_url(project_root) {
25        Some(url) => url,
26        None => {
27            eprintln!("No git remote 'origin' configured. Skipping sync.");
28            return Ok(());
29        }
30    };
31
32    let client = ApiClient::with_credential(&server_url, credential);
33
34    let repo_name = git_repo_name(project_root);
35
36    // Same guard as `init`: a remote whose codebase already has a repo record
37    // must not get a second one under this checkout's directory name.
38    let preferred = TracevaultConfig::load(project_root)
39        .and_then(|c| c.repo_id)
40        .and_then(|id| id.parse::<uuid::Uuid>().ok());
41    match plan_registration(&client, &remote, &repo_name, preferred).await {
42        Ok(RegistrationPlan::Register) => {}
43        Ok(RegistrationPlan::Existing(codebase, repo_id)) => {
44            let bound = persist_repo_binding(project_root, repo_id, Some(&codebase.remote));
45            println!(
46                "Repo already registered (id: {repo_id}, codebase: {}); {}",
47                codebase.display_name(),
48                if bound {
49                    "bound .tracevault/config.toml to it"
50                } else {
51                    "no .tracevault/config.toml here to bind (run `tracevault init` to create one)"
52                }
53            );
54            return Ok(());
55        }
56        Ok(RegistrationPlan::Ambiguous(codebase)) => {
57            eprintln!(
58                "Warning: codebase {} already has {} repo records ({}) and none is named \
59                 '{repo_name}'; not registering another.",
60                codebase.display_name(),
61                codebase.repos.len(),
62                codebase.repo_list()
63            );
64            return Ok(());
65        }
66        Err(e) => {
67            eprintln!(
68                "Warning: could not check the server for an existing repo of this remote ({e}); \
69                 not registering."
70            );
71            return Ok(());
72        }
73    }
74
75    match client
76        .register_repo(crate::api_client::RegisterRepoRequest {
77            repo_name,
78            github_url: Some(remote.clone()),
79        })
80        .await
81    {
82        Ok(resp) => {
83            persist_repo_binding(project_root, resp.repo_id, None);
84            println!(
85                "Repo synced with server (id: {}, remote: {})",
86                resp.repo_id, remote
87            );
88        }
89        Err(e) => {
90            eprintln!("Warning: could not sync repo with server: {e}");
91        }
92    }
93
94    Ok(())
95}
96
97#[cfg(test)]
98mod tests {
99    use super::*;
100    use crate::test_helpers::http_json;
101
102    /// `sync` on a checkout whose remote already has a repo record (e.g. after
103    /// an `init` that ran logged out) binds that record in config.toml instead
104    /// of registering a second one (VIS-1018).
105    #[tokio::test]
106    async fn sync_binds_the_existing_repo_of_a_known_remote() {
107        let _env_lock = crate::test_helpers::lock_env_mutation().await;
108        let tmp = tempfile::tempdir().unwrap();
109        let root = tmp.path();
110        crate::test_helpers::init_git_repo(root);
111        let ok = std::process::Command::new("git")
112            .args(["-C", &root.to_string_lossy()])
113            .args(["remote", "add", "origin", "git@github.com:org/repo.git"])
114            .status()
115            .unwrap()
116            .success();
117        assert!(ok);
118        let repo_id = "44000761-0000-4000-8000-000000000001";
119        let (base, rx) = crate::test_helpers::spawn_seq(vec![
120            http_json(
121                "200 OK",
122                r#"{"remote_id":"2280a1c9-0000-4000-8000-000000000003","name":"tracing","normalized_url":"github.com/org/repo","clone_status":"ready"}"#,
123            ),
124            http_json(
125                "200 OK",
126                &format!(
127                    r#"{{"name":"tracing","normalized_url":"github.com/org/repo","clone_status":"ready","repos":[{{"id":"{repo_id}","name":"tracevault"}}]}}"#
128                ),
129            ),
130        ]);
131        std::fs::create_dir_all(root.join(".tracevault")).unwrap();
132        std::fs::write(
133            TracevaultConfig::config_path(root),
134            format!("server_url = \"{base}\"\n"),
135        )
136        .unwrap();
137        let mut guard = crate::test_helpers::EnvVarGuard::new();
138        guard.set("XDG_CONFIG_HOME", root);
139        guard.set("TRACEVAULT_API_KEY", "tok");
140        guard.remove("TRACEVAULT_SERVER_URL");
141
142        sync_repo(root).await.unwrap();
143
144        let cfg = TracevaultConfig::load(root).unwrap();
145        assert_eq!(cfg.repo_id.as_deref(), Some(repo_id));
146        assert_eq!(cfg.codebase_name.as_deref(), Some("tracing"));
147        let requests: Vec<String> = rx.try_iter().collect();
148        assert!(
149            !requests.iter().any(|r| r.starts_with("POST /api/v1/repos")),
150            "requests: {requests:?}"
151        );
152    }
153}