Skip to main content

tracevault_cli/commands/
repo.rs

1//! `tracevault repo` — workspace/detached-mode repo binding commands.
2
3use std::path::Path;
4
5use crate::api_client::{resolve_credentials, ApiClient, RepoListItem};
6use crate::resolution::{
7    binding_from_config, effective_binding, org_slug_for, resolve_path_to_binding, BindingSource,
8    ResolveInputs,
9};
10use crate::session_state::{self, RepoBinding, SessionState};
11
12/// Sub-actions for `tracevault repo` (workspace/detached mode).
13#[derive(clap::Subcommand)]
14pub enum RepoCmd {
15    /// Bind tracing to a registered repo for the current session and print its
16    /// policies. Give a checkout <path> OR --name; exactly one is required.
17    #[command(group(clap::ArgGroup::new("target").required(true).multiple(false)))]
18    Switch {
19        /// Path to a checkout of a registered repo (resolves via its git origin remote).
20        #[arg(group = "target")]
21        path: Option<String>,
22        /// Bind by the repo's registered name instead of a checkout path (no checkout needed).
23        #[arg(long, group = "target")]
24        name: Option<String>,
25        /// Session to target; defaults to $TRACEVAULT_SESSION_ID.
26        #[arg(long)]
27        session_id: Option<String>,
28    },
29    /// Show the repo the current session is bound to.
30    Status {
31        /// Session to target; defaults to $TRACEVAULT_SESSION_ID.
32        #[arg(long)]
33        session_id: Option<String>,
34        /// One-off: resolve this checkout path instead of the session binding.
35        #[arg(long)]
36        path: Option<String>,
37    },
38    /// Clear the current session's binding.
39    Reset {
40        /// Session to target; defaults to $TRACEVAULT_SESSION_ID.
41        #[arg(long)]
42        session_id: Option<String>,
43    },
44}
45
46/// Resolve the current session id: the explicit flag wins, else
47/// `$TRACEVAULT_SESSION_ID` (set by the SessionStart hook of `init --global`).
48pub fn resolve_session_id(explicit: Option<&str>) -> Result<String, Box<dyn std::error::Error>> {
49    if let Some(s) = explicit {
50        return Ok(s.to_string());
51    }
52    std::env::var("TRACEVAULT_SESSION_ID")
53        .ok()
54        .filter(|s| !s.is_empty())
55        .ok_or_else(|| {
56            "no session id available: pass --session-id or set TRACEVAULT_SESSION_ID \
57             (installed by `tracevault init --global`)"
58                .into()
59        })
60}
61
62pub async fn run(
63    cmd: RepoCmd,
64    project_root: &Path,
65    cwd: &Path,
66) -> Result<(), Box<dyn std::error::Error>> {
67    match cmd {
68        RepoCmd::Status { session_id, path } => {
69            status(session_id.as_deref(), path.as_deref(), project_root, cwd).await
70        }
71        RepoCmd::Switch {
72            path,
73            name,
74            session_id,
75        } => {
76            switch(
77                path.as_deref(),
78                name.as_deref(),
79                session_id.as_deref(),
80                project_root,
81            )
82            .await
83        }
84        RepoCmd::Reset { session_id } => reset(session_id.as_deref()),
85    }
86}
87
88/// Resolve a path to a binding for `repo switch`, turning "unregistered" into
89/// a clear error (switch should fail loudly, unlike the best-effort `--path`
90/// status override).
91async fn resolve_switch_binding(
92    path: &Path,
93    org_slug: &str,
94    client: &ApiClient,
95) -> Result<RepoBinding, Box<dyn std::error::Error>> {
96    resolve_path_to_binding(path, org_slug, client)
97        .await?
98        .ok_or_else(|| {
99            format!(
100                "repo at {} is not registered with TraceVault (org {org_slug}); nothing to bind",
101                path.display()
102            )
103            .into()
104        })
105}
106
107/// Build the "no repo named …" error. An empty org is called out explicitly
108/// (rather than a dangling "available: "); long lists are capped so a single
109/// typo can't dump hundreds of names to stderr.
110fn name_not_found_error(name: &str, org_slug: &str, repos: &[RepoListItem]) -> String {
111    if repos.is_empty() {
112        return format!("no repo named '{name}': org {org_slug} has no registered repos");
113    }
114    const MAX: usize = 20;
115    let mut names: Vec<&str> = repos.iter().map(|r| r.name.as_str()).collect();
116    names.sort_unstable();
117    let shown = names.len().min(MAX);
118    let mut list = names[..shown].join(", ");
119    if names.len() > MAX {
120        list.push_str(&format!(", … and {} more", names.len() - MAX));
121    }
122    format!("no repo named '{name}' in org {org_slug} (available: {list})")
123}
124
125/// Resolve a registered repo by its NAME (no git checkout) to a binding.
126/// Exact, case-sensitive match on `repos.name`; on no match, errors listing
127/// the available names so a typo self-corrects. Resolution lists the org's
128/// repos and matches client-side (unlike the git-URL path's server-side
129/// `/repos/resolve`); this is safe because the server returns all repos
130/// unpaginated and `(org, name)` is unique, and it keeps the endpoint
131/// surface small.
132async fn resolve_name_to_binding(
133    name: &str,
134    org_slug: &str,
135    client: &ApiClient,
136) -> Result<RepoBinding, Box<dyn std::error::Error>> {
137    let repos = client.list_repos(org_slug).await?;
138    match repos.iter().find(|r| r.name == name) {
139        Some(repo) => Ok(RepoBinding {
140            org_slug: org_slug.to_string(),
141            repo_id: repo.id.to_string(),
142            git_url: repo.github_url.clone(),
143            updated_at: chrono::Utc::now().to_rfc3339(),
144        }),
145        None => Err(name_not_found_error(name, org_slug, &repos).into()),
146    }
147}
148
149/// Apply a switch to session state (session-level active binding). Pure.
150fn apply_switch(state: &mut SessionState, binding: RepoBinding) {
151    state.active = Some(binding);
152}
153
154/// Clear the session's workspace binding (session-level reset). Pure.
155fn apply_reset(state: &mut SessionState) {
156    *state = SessionState::default();
157}
158
159fn reset(session_id: Option<&str>) -> Result<(), Box<dyn std::error::Error>> {
160    let id = resolve_session_id(session_id)?;
161    let mut state = session_state::load(&id);
162    apply_reset(&mut state);
163    session_state::save(&id, &state)?;
164    // NOTE: subagent worktree-scoped reset-to-parent is handled in sub-plan C.
165    println!("cleared workspace repo binding for session {id}");
166    Ok(())
167}
168
169/// Which target `repo switch` should resolve to a binding: a checkout path
170/// or a registered repo name. Exactly one of `path`/`name` must be given;
171/// see `switch_target`.
172#[derive(Debug)]
173enum SwitchTarget<'a> {
174    Path(&'a str),
175    Name(&'a str),
176}
177
178/// Pure exactly-one-of guard for `repo switch`'s `<path>` / `--name`
179/// arguments. Kept separate from `switch` so it can be unit-tested without
180/// spinning up a server or session state (also a safety net if the clap
181/// `ArgGroup` on the `Switch` variant is ever loosened).
182fn switch_target<'a>(
183    path: Option<&'a str>,
184    name: Option<&'a str>,
185) -> Result<SwitchTarget<'a>, Box<dyn std::error::Error>> {
186    match (path, name) {
187        (Some(p), None) if p.trim().is_empty() => {
188            Err("repo path (<path>) must not be empty".into())
189        }
190        (Some(p), None) => Ok(SwitchTarget::Path(p)),
191        (None, Some(n)) if n.trim().is_empty() => {
192            Err("repo name (--name) must not be empty".into())
193        }
194        (None, Some(n)) => Ok(SwitchTarget::Name(n)),
195        _ => Err("provide exactly one of <path> or --name".into()),
196    }
197}
198
199async fn switch(
200    path: Option<&str>,
201    name: Option<&str>,
202    session_id: Option<&str>,
203    project_root: &Path,
204) -> Result<(), Box<dyn std::error::Error>> {
205    let id = resolve_session_id(session_id)?;
206    let org_slug = org_slug_for(project_root).ok_or(
207        "no org configured: set TRACEVAULT_ORG_SLUG, log in, or run inside a bound repo checkout",
208    )?;
209
210    let (server_url, token) = resolve_credentials(project_root);
211    let server_url = server_url.ok_or("not logged in / no server_url; run `tracevault login`")?;
212    let client = ApiClient::new(&server_url, token.as_deref());
213
214    let binding = match switch_target(path, name)? {
215        SwitchTarget::Path(p) => resolve_switch_binding(Path::new(p), &org_slug, &client).await?,
216        SwitchTarget::Name(n) => resolve_name_to_binding(n, &org_slug, &client).await?,
217    };
218
219    // Validate the repo id BEFORE persisting anything: a malformed repo_id
220    // must not leave a persisted session binding behind.
221    let repo_uuid = binding.repo_id.parse::<uuid::Uuid>().map_err(|e| {
222        format!(
223            "server returned an invalid repo id {:?}: {e}",
224            binding.repo_id
225        )
226    })?;
227
228    // NOTE: subagent worktree-override writes are handled in sub-plan C.
229    let mut state = session_state::load(&id);
230    apply_switch(&mut state, binding.clone());
231    session_state::save(&id, &state)?;
232
233    println!(
234        "bound session {id} to repo {} (org {})",
235        binding.repo_id, binding.org_slug
236    );
237
238    // The binding was already saved above — that's the primary effect of
239    // `switch`. A failure to fetch policies afterward shouldn't make the
240    // whole command report as an error.
241    match client
242        .get_agent_instructions(&binding.org_slug, &repo_uuid)
243        .await
244    {
245        Ok(policies) => println!("{}", policies.content),
246        Err(e) => eprintln!("warning: bound, but could not fetch policies: {e}"),
247    }
248    Ok(())
249}
250
251/// Resolve a `--path <path>` override into a live `RepoBinding`, if possible.
252/// Best-effort: prints a clear message and returns `None` on any failure
253/// (missing org slug / credentials, or a server error) rather than failing
254/// the whole `status` inspector.
255async fn resolve_repo_flag(
256    repo_flag_path: Option<&str>,
257    project_root: &Path,
258) -> Option<RepoBinding> {
259    let path = repo_flag_path?;
260
261    let Some(org_slug) = org_slug_for(project_root) else {
262        eprintln!(
263            "--path {path}: no org slug configured (set TRACEVAULT_ORG_SLUG, log in, or bind \
264             the repo); showing binding without the --path override"
265        );
266        return None;
267    };
268
269    let (server_url, token) = resolve_credentials(project_root);
270    let Some(server_url) = server_url else {
271        eprintln!(
272            "--path {path}: no server URL configured (run `tracevault login`); showing binding \
273             without the --path override"
274        );
275        return None;
276    };
277
278    let client = ApiClient::new(&server_url, token.as_deref());
279    match resolve_path_to_binding(Path::new(path), &org_slug, &client).await {
280        Ok(Some(binding)) => Some(binding),
281        Ok(None) => {
282            eprintln!(
283                "--path {path}: no registered repo found for this path's git remote; showing \
284                 binding without the --path override"
285            );
286            None
287        }
288        Err(e) => {
289            eprintln!(
290                "--path {path}: failed to resolve ({e}); showing binding without the --path \
291                 override"
292            );
293            None
294        }
295    }
296}
297
298/// Pure formatter for `repo status`'s output: which repo is bound, and via
299/// which precedence tier. Kept separate from I/O so it can be unit-tested.
300fn format_status(binding: Option<(&RepoBinding, BindingSource)>) -> String {
301    match binding {
302        Some((b, source)) => format!(
303            "bound to repo {} (org {}) via {source}",
304            b.repo_id, b.org_slug
305        ),
306        None => {
307            "not bound to any repo (workspace mode; run `tracevault repo switch <path>` or `tracevault repo switch --name <project>`)".into()
308        }
309    }
310}
311
312async fn status(
313    session_id: Option<&str>,
314    repo_flag_path: Option<&str>,
315    project_root: &Path,
316    cwd: &Path,
317) -> Result<(), Box<dyn std::error::Error>> {
318    // Session state is best-effort: if a session id resolves, load it; else
319    // warn and fall back to an empty SessionState rather than silently
320    // reporting "not bound" without the user knowing why.
321    let session = match resolve_session_id(session_id) {
322        Ok(id) => session_state::load(&id),
323        Err(_) => {
324            eprintln!(
325                "warning: no session id (pass --session-id or set TRACEVAULT_SESSION_ID); \
326                 showing binding without session context"
327            );
328            SessionState::default()
329        }
330    };
331    let worktree = crate::paths::worktree_toplevel(cwd);
332    let bound = crate::config::TracevaultConfig::load(project_root)
333        .as_ref()
334        .and_then(binding_from_config);
335
336    // A --path override on status resolves live (needs org_slug + server).
337    let repo_flag = resolve_repo_flag(repo_flag_path, project_root).await;
338
339    let effective = effective_binding(ResolveInputs {
340        repo_flag,
341        session: &session,
342        worktree_path: Some(&worktree),
343        bound,
344    });
345    println!(
346        "{}",
347        format_status(effective.as_ref().map(|(b, s)| (b, *s)))
348    );
349    Ok(())
350}
351
352#[cfg(test)]
353mod tests {
354    use super::*;
355    use std::io::{BufRead, BufReader, Write};
356    use std::net::TcpListener;
357    use std::thread;
358
359    #[test]
360    fn resolve_session_id_prefers_explicit() {
361        assert_eq!(resolve_session_id(Some("sess-x")).unwrap(), "sess-x");
362    }
363
364    #[test]
365    fn resolve_session_id_errors_when_absent() {
366        // No explicit id and (in this test process) no env var set → error.
367        // Guard against a leaked env var from another test by checking the
368        // message only when the var is genuinely absent.
369        if std::env::var("TRACEVAULT_SESSION_ID").is_err() {
370            assert!(resolve_session_id(None).is_err());
371        }
372    }
373
374    #[test]
375    fn switch_target_rejects_neither() {
376        assert!(switch_target(None, None).is_err());
377    }
378
379    #[test]
380    fn switch_target_rejects_both() {
381        assert!(switch_target(Some("/p"), Some("x")).is_err());
382    }
383
384    #[test]
385    fn switch_target_accepts_path_only() {
386        assert!(matches!(
387            switch_target(Some("/p"), None),
388            Ok(SwitchTarget::Path("/p"))
389        ));
390    }
391
392    #[test]
393    fn switch_target_accepts_name_only() {
394        assert!(matches!(
395            switch_target(None, Some("proj")),
396            Ok(SwitchTarget::Name("proj"))
397        ));
398    }
399
400    fn binding(id: &str) -> RepoBinding {
401        RepoBinding {
402            org_slug: "org".into(),
403            repo_id: id.into(),
404            git_url: None,
405            updated_at: "t".into(),
406        }
407    }
408
409    #[test]
410    fn apply_switch_sets_session_active() {
411        let mut state = SessionState::default();
412        apply_switch(&mut state, binding("new-repo"));
413        assert_eq!(state.active.unwrap().repo_id, "new-repo");
414    }
415
416    #[test]
417    fn apply_reset_clears_active_and_subagents() {
418        let mut state = SessionState {
419            active: Some(binding("r")),
420            subagents: std::collections::HashMap::from([("/wt/a".to_string(), binding("r2"))]),
421            ..Default::default()
422        };
423        apply_reset(&mut state);
424        assert_eq!(state, SessionState::default());
425    }
426
427    #[test]
428    fn apply_switch_overwrites_existing_active() {
429        let mut state = SessionState {
430            active: Some(binding("old-repo")),
431            subagents: Default::default(),
432            ..Default::default()
433        };
434        apply_switch(&mut state, binding("new-repo"));
435        assert_eq!(state.active.unwrap().repo_id, "new-repo");
436    }
437
438    #[test]
439    fn format_status_none() {
440        assert_eq!(
441            format_status(None),
442            "not bound to any repo (workspace mode; run `tracevault repo switch <path>` or `tracevault repo switch --name <project>`)"
443        );
444    }
445
446    #[test]
447    fn format_status_repo_flag() {
448        let b = binding("r1");
449        assert_eq!(
450            format_status(Some((&b, BindingSource::RepoFlag))),
451            "bound to repo r1 (org org) via --path override"
452        );
453    }
454
455    #[test]
456    fn format_status_subagent() {
457        let b = binding("r2");
458        assert_eq!(
459            format_status(Some((&b, BindingSource::Subagent))),
460            "bound to repo r2 (org org) via subagent worktree override"
461        );
462    }
463
464    #[test]
465    fn format_status_session_active() {
466        let b = binding("r3");
467        assert_eq!(
468            format_status(Some((&b, BindingSource::SessionActive))),
469            "bound to repo r3 (org org) via session (repo switch)"
470        );
471    }
472
473    #[test]
474    fn format_status_bound() {
475        let b = binding("r4");
476        assert_eq!(
477            format_status(Some((&b, BindingSource::Bound))),
478            "bound to repo r4 (org org) via bound .tracevault/config.toml"
479        );
480    }
481
482    fn add_origin_remote(dir: &std::path::Path, url: &str) {
483        let ok = std::process::Command::new("git")
484            .args(["-C", &dir.to_string_lossy(), "remote", "add", "origin", url])
485            .status()
486            .expect("git remote add failed")
487            .success();
488        assert!(ok, "git remote add must succeed");
489    }
490
491    /// Spawn a one-shot raw-HTTP server that returns `response` to the first
492    /// request it accepts (mirrors `tests/resolve_repo_test.rs`).
493    fn spawn_once(response: &'static str) -> String {
494        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
495        let addr = listener.local_addr().unwrap();
496        thread::spawn(move || {
497            if let Ok((stream, _)) = listener.accept() {
498                let mut reader = BufReader::new(stream);
499                let mut request_line = String::new();
500                let _ = reader.read_line(&mut request_line);
501                let mut stream = reader.into_inner();
502                let _ = stream.write_all(response.as_bytes());
503                let _ = stream.flush();
504            }
505        });
506        format!("http://{addr}")
507    }
508
509    #[tokio::test]
510    async fn resolve_switch_binding_ok_for_registered_repo() {
511        let tmp = tempfile::tempdir().unwrap();
512        crate::test_helpers::init_git_repo(tmp.path());
513        add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
514
515        let repo_id = "44000761-8d22-4256-bd2c-27a0ba278c6f";
516        let body = format!(r#"{{"repo_id":"{repo_id}"}}"#);
517        let resp = format!(
518            "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
519            body.len(),
520            body
521        );
522        let base = spawn_once(Box::leak(resp.into_boxed_str()));
523        let client = ApiClient::new(&base, Some("tok"));
524
525        let got = resolve_switch_binding(tmp.path(), "org", &client)
526            .await
527            .expect("expected Ok binding");
528        assert_eq!(got.repo_id, repo_id);
529        assert_eq!(got.org_slug, "org");
530    }
531
532    #[tokio::test]
533    async fn resolve_switch_binding_errors_for_unregistered_repo() {
534        let tmp = tempfile::tempdir().unwrap();
535        crate::test_helpers::init_git_repo(tmp.path());
536        add_origin_remote(tmp.path(), "git@github.com:org/unregistered.git");
537
538        let resp = "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
539        let base = spawn_once(resp);
540        let client = ApiClient::new(&base, Some("tok"));
541
542        let err = resolve_switch_binding(tmp.path(), "org", &client)
543            .await
544            .expect_err("expected Err for unregistered repo");
545        assert!(
546            err.to_string().contains("not registered"),
547            "unexpected error message: {err}"
548        );
549    }
550
551    #[tokio::test]
552    async fn resolve_name_to_binding_finds_by_name() {
553        let body = r#"[{"id":"11111111-1111-4111-8111-111111111111","name":"visdom-orchestrator","github_url":null,"clone_status":null},{"id":"22222222-2222-4222-8222-222222222222","name":"visdom-web","github_url":"https://github.com/o/web.git","clone_status":null}]"#;
554        let resp = format!(
555            "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
556            body.len(),
557            body
558        );
559        let base = spawn_once(Box::leak(resp.into_boxed_str()));
560        let client = ApiClient::new(&base, Some("tok"));
561        let b = resolve_name_to_binding("visdom-orchestrator", "acme", &client)
562            .await
563            .expect("expected Ok binding");
564        assert_eq!(b.repo_id, "11111111-1111-4111-8111-111111111111");
565        assert_eq!(b.org_slug, "acme");
566    }
567
568    #[tokio::test]
569    async fn resolve_name_to_binding_errors_when_absent_listing_names() {
570        let body = r#"[{"id":"22222222-2222-4222-8222-222222222222","name":"visdom-web","github_url":null,"clone_status":null}]"#;
571        let resp = format!(
572            "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
573            body.len(),
574            body
575        );
576        let base = spawn_once(Box::leak(resp.into_boxed_str()));
577        let client = ApiClient::new(&base, Some("tok"));
578        let err = resolve_name_to_binding("visdom-orch", "acme", &client)
579            .await
580            .expect_err("expected Err for missing name")
581            .to_string();
582        assert!(err.contains("no repo named"), "got: {err}");
583        assert!(
584            err.contains("visdom-web"),
585            "error should list available names, got: {err}"
586        );
587    }
588
589    #[test]
590    fn name_not_found_error_empty_org_is_explicit() {
591        let msg = name_not_found_error("x", "acme", &[]);
592        assert!(msg.contains("has no registered repos"), "got: {msg}");
593        assert!(
594            !msg.contains("available:"),
595            "empty org must not print a dangling list: {msg}"
596        );
597    }
598
599    #[test]
600    fn name_not_found_error_caps_long_lists() {
601        let repos: Vec<RepoListItem> = (0..25)
602            .map(|i| RepoListItem {
603                id: uuid::Uuid::nil(),
604                name: format!("repo-{i:02}"),
605                github_url: None,
606                clone_status: None,
607            })
608            .collect();
609        let msg = name_not_found_error("zzz", "acme", &repos);
610        assert!(
611            msg.contains("… and 5 more"),
612            "should cap at 20 and note the remainder: {msg}"
613        );
614    }
615
616    #[test]
617    fn switch_target_rejects_empty_name() {
618        assert!(switch_target(None, Some("")).is_err());
619        assert!(switch_target(None, Some("   ")).is_err());
620        let err = switch_target(None, Some(" ")).unwrap_err().to_string();
621        assert!(err.contains("must not be empty"), "got: {err}");
622    }
623
624    #[test]
625    fn switch_target_rejects_empty_path() {
626        assert!(switch_target(Some(""), None).is_err());
627        assert!(switch_target(Some("   "), None).is_err());
628        let err = switch_target(Some(" "), None).unwrap_err().to_string();
629        assert!(err.contains("must not be empty"), "got: {err}");
630    }
631
632    #[tokio::test]
633    async fn resolve_name_to_binding_is_case_sensitive() {
634        let body = r#"[{"id":"11111111-1111-4111-8111-111111111111","name":"visdom-web","github_url":null,"clone_status":null}]"#;
635        let resp = format!(
636            "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
637            body.len(),
638            body
639        );
640        let base = spawn_once(Box::leak(resp.into_boxed_str()));
641        let client = ApiClient::new(&base, Some("tok"));
642        let err = resolve_name_to_binding("Visdom-Web", "acme", &client)
643            .await
644            .unwrap_err()
645            .to_string();
646        assert!(
647            err.contains("no repo named 'Visdom-Web'"),
648            "case must not match: {err}"
649        );
650    }
651
652    /// `list_repos` maps any non-2xx status (including 500) to an `Err`
653    /// (never `Ok(vec![])`), so this exercises `resolve_name_to_binding`
654    /// propagating that transport/server error via `?`, not the "no repos
655    /// registered" branch of `name_not_found_error`.
656    #[tokio::test]
657    async fn resolve_name_to_binding_propagates_list_error() {
658        let resp =
659            "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
660        let base = spawn_once(resp);
661        let client = ApiClient::new(&base, Some("tok"));
662        assert!(resolve_name_to_binding("anything", "acme", &client)
663            .await
664            .is_err());
665    }
666}