Skip to main content

visdom_cli/
doctor.rs

1//! Gathering what the checks need from this machine, running them, and
2//! carrying out the fixes the user agreed to.
3
4use std::io::{BufRead, Write};
5use std::path::{Path, PathBuf};
6use std::process::{Command, Stdio};
7
8use tracevault_cli::agent::Agent;
9use tracevault_cli::credentials::Credential;
10
11use crate::agents::{adapter_for, AgentAdapter, AgentPaths, McpScope, Workdir};
12use crate::components::gateway::GatewayPlan;
13use crate::components::{
14    bazaar, gateway as gateway_checks, tracing, CheckContext, CredentialState,
15};
16use crate::config::{self, RepoConfig, UserConfig};
17use crate::finding::{command_line, needs_attention, render_text, Finding, Fix, FixAction};
18use crate::fixes::{apply_fixes, FixExecutor, FixOutcome, FixPolicy};
19use crate::gateway;
20use crate::instructions::{self, Facts, Told};
21use crate::mode::{configured_mode, effective_mode, ResolvedMode, TracingMode, MODE_ENV};
22use crate::suite::{self, PolicyState, SuiteMap};
23
24/// The first of `candidates` that is set to something.
25fn first_set(candidates: [Option<String>; 3]) -> Option<String> {
26    candidates
27        .into_iter()
28        .flatten()
29        .map(|v| v.trim().trim_end_matches('/').to_string())
30        .find(|v| !v.is_empty())
31}
32
33/// The canonical top level of the git checkout containing `from`.
34pub fn git_toplevel(from: &Path) -> Option<PathBuf> {
35    let output = Command::new("git")
36        .args(["rev-parse", "--show-toplevel"])
37        .current_dir(from)
38        .stderr(Stdio::null())
39        .output()
40        .ok()
41        .filter(|o| o.status.success())?;
42    let path = PathBuf::from(String::from_utf8(output.stdout).ok()?.trim());
43    Some(path.canonicalize().unwrap_or(path))
44}
45
46/// The directory whose `.visdom/config.toml` applies in `cwd`: the top of the
47/// git checkout, else — outside any checkout, in a folder of checkouts set up
48/// as a workspace — the nearest directory above that has the file.
49pub fn settings_dir(cwd: &Path) -> Option<PathBuf> {
50    git_toplevel(cwd).or_else(|| {
51        cwd.ancestors()
52            .find(|dir| config::repo_config_path_in(dir).is_file())
53            .map(Path::to_path_buf)
54    })
55}
56
57pub const GATEWAY_URL_ENV: &str = "VISDOM_GATEWAY_URL";
58pub const GATEWAY_PROJECT_ENV: &str = "VISDOM_GATEWAY_PROJECT";
59pub const GATEWAY_MODEL_ENV: &str = "VISDOM_GATEWAY_MODEL";
60
61/// Where the gateway settings of a session come from, each said as a person
62/// would read it (`VISDOM_GATEWAY_URL in the environment`, a config file's
63/// key, `published by the tracing server`). `None`: nobody set it.
64#[derive(Clone, Debug, Default, PartialEq, Eq)]
65pub struct GatewaySources {
66    pub console_url: Option<String>,
67    pub project: Option<String>,
68    pub model: Option<String>,
69}
70
71/// The first value that is set, and where it was found.
72fn first_from<const N: usize>(
73    candidates: [(Option<String>, String); N],
74) -> (Option<String>, Option<String>) {
75    candidates
76        .into_iter()
77        .find_map(|(value, source)| {
78            value
79                .filter(|v| !v.trim().is_empty())
80                .map(|v| (Some(v), Some(source)))
81        })
82        .unwrap_or((None, None))
83}
84
85/// The process environment a [`Session`] is gathered from.
86pub struct Environment {
87    pub cwd: PathBuf,
88    pub home: PathBuf,
89    /// The platform config directory (`~/.config` on Linux).
90    pub config_root: PathBuf,
91    pub codex_home: PathBuf,
92    /// `VISDOM_AGENT`.
93    pub agent: Option<String>,
94    /// `VISDOM_BAZAAR_URL`.
95    pub bazaar_url: Option<String>,
96    /// `VISDOM_TRACING_MODE`.
97    pub mode: Option<String>,
98    /// `VISDOM_GATEWAY_URL`: the AI Gateway console.
99    pub gateway_url: Option<String>,
100    /// `VISDOM_CONTROL_PLANE_URL`.
101    pub control_plane_url: Option<String>,
102    /// `VISDOM_GATEWAY_PROJECT`: the gateway project (slug, id or name).
103    pub gateway_project: Option<String>,
104    /// `VISDOM_GATEWAY_MODEL`: the model alias the agent asks the gateway for.
105    pub gateway_model: Option<String>,
106}
107
108impl Environment {
109    pub fn current() -> Self {
110        let home = dirs::home_dir().unwrap_or_default();
111        let set = |name: &str| std::env::var(name).ok().filter(|v| !v.trim().is_empty());
112        Environment {
113            cwd: std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
114            config_root: dirs::config_dir().unwrap_or_else(|| home.join(".config")),
115            codex_home: set("CODEX_HOME")
116                .map(PathBuf::from)
117                .unwrap_or_else(|| home.join(".codex")),
118            agent: set("VISDOM_AGENT"),
119            bazaar_url: set("VISDOM_BAZAAR_URL"),
120            mode: set(MODE_ENV),
121            gateway_url: set("VISDOM_GATEWAY_URL"),
122            control_plane_url: set("VISDOM_CONTROL_PLANE_URL"),
123            gateway_project: set(GATEWAY_PROJECT_ENV),
124            gateway_model: set(GATEWAY_MODEL_ENV),
125            home,
126        }
127    }
128}
129
130/// One run's view of the project: which agent, and everything the checks read.
131pub struct Session {
132    pub ctx: CheckContext,
133    pub adapter: Box<dyn AgentAdapter>,
134    /// `Err`: the server that should know it could not be asked (the reason).
135    pub bazaar_url: Result<Option<String>, String>,
136    pub user_config_path: PathBuf,
137    /// Problems reading visdom's own config files; the run goes on without them.
138    pub warnings: Vec<String>,
139    /// How this session is traced, and who decided.
140    pub mode: ResolvedMode,
141    pub policy: PolicyState,
142    /// In gateway mode: what the session will use, or why it cannot.
143    pub gateway: Option<Result<GatewayPlan, String>>,
144    /// The suite's other products, as far as the tracing server says.
145    pub suite: SuiteMap,
146    /// The developer's Keycloak access token, for the suite's other products.
147    /// Never an API key: that is the tracing server's alone.
148    pub token: Option<String>,
149    /// The model alias configured for this agent through the gateway.
150    pub gateway_model: Option<String>,
151    /// Where a missing bazaar registration is made: for this project
152    /// directory, or (a machine-wide setup) for all of the user's.
153    pub mcp_scope: McpScope,
154    /// The gateway console's address, as far as anybody names one.
155    pub console_url: Option<String>,
156    /// Who set the gateway's address, project and model.
157    pub gateway_sources: GatewaySources,
158    /// Where visdom keeps its own state (`<config dir>`).
159    pub config_root: PathBuf,
160    /// Whether the agent is told about Visdom's tools (`agent_instructions`
161    /// in the user config; yes unless that says no).
162    pub agent_instructions: bool,
163}
164
165impl Session {
166    /// Read the config files, choose the agent and gather the check context.
167    /// The only error is an agent that cannot be chosen or launched.
168    pub fn gather(
169        env: &Environment,
170        agent_flag: Option<Agent>,
171        mode_flag: Option<TracingMode>,
172        runtime: &tokio::runtime::Runtime,
173    ) -> Result<Session, String> {
174        let mut warnings = Vec::new();
175        let project_dir = git_toplevel(&env.cwd);
176        let user: UserConfig = config::load_user_config_in(&env.config_root).unwrap_or_else(|e| {
177            warnings.push(e);
178            UserConfig::default()
179        });
180        let repo = settings_dir(&env.cwd)
181            .as_deref()
182            .map(config::load_repo_config_in)
183            .transpose()
184            .unwrap_or_else(|e| {
185                warnings.push(e);
186                None
187            })
188            .unwrap_or_default();
189        let repo: RepoConfig = repo;
190        let agent = config::resolve_agent(agent_flag, env.agent.as_deref(), &repo, &user)?;
191        let chosen = configured_mode(
192            mode_flag,
193            env.mode.as_deref(),
194            repo.tracing_mode,
195            user.tracing_mode,
196        )?;
197
198        let tracing_root = project_dir
199            .as_deref()
200            .map(|dir| tracevault_cli::paths::resolve_project_root(dir).root);
201        let credential_root = tracing_root.as_deref().unwrap_or(&env.cwd);
202        let (server_url, credential, session) =
203            match tracevault_cli::credentials::resolve_credentials_quiet(credential_root) {
204                Ok((url, Some(credential))) => {
205                    let session = match credential {
206                        Credential::Keycloak(_) => Some(credential),
207                        Credential::ApiKey(_) => None,
208                    };
209                    (url, CredentialState::Present, session)
210                }
211                Ok((url, None)) => (url, missing_or_unreadable(), None),
212                Err(e) => (None, CredentialState::Unusable(e.to_string()), None),
213            };
214
215        let http = http_client();
216        // One question to the tracing server tells where everything else is.
217        let published = match &server_url {
218            Some(url) => runtime.block_on(suite::fetch_suite_map(&http, url)),
219            None => Ok(SuiteMap::default()),
220        };
221        let bazaar_url = bazaar::resolve_bazaar_url(env.bazaar_url.clone(), &user, &published);
222        // While that server is away, the rest of the suite is where it last
223        // said: a policy that requires the gateway must not lapse with it.
224        let suite_map = match &server_url {
225            Some(url) => suite::suite_map_or_remembered(
226                &published,
227                url,
228                &suite::suite_cache_path_in(&env.config_root),
229            ),
230            None => SuiteMap::default(),
231        };
232
233        // The developer's own token opens the suite's other products. Only a
234        // Keycloak login has one; an API key is never sent anywhere else.
235        let token = match (&server_url, session) {
236            (Some(url), Some(session)) => runtime
237                .block_on(
238                    tracevault_cli::api_client::ApiClient::with_credential(url, Some(session))
239                        .bearer_valid_for(MIN_TOKEN_SECONDS),
240                )
241                .ok()
242                .flatten(),
243            _ => None,
244        };
245        let control_plane_url = first_set([
246            env.control_plane_url.clone(),
247            user.control_plane_url.clone(),
248            suite_map.control_plane_url.clone(),
249        ]);
250        let policy = runtime.block_on(suite::resolve_policy(
251            &http,
252            control_plane_url.as_deref(),
253            token.as_deref(),
254            &suite::policy_cache_path_in(&env.config_root),
255        ));
256        let mode = effective_mode(chosen, policy.policy());
257        // The environment first, then the files, then what the server says:
258        // a setting left out of the config is taken from the environment.
259        let user_file = config::user_config_path_in(&env.config_root);
260        let in_env = |name: &str| format!("{name} in the environment");
261        let in_user = |key: &str| format!("{key} in {}", user_file.display());
262        let (console_url, console_source) = first_from([
263            (env.gateway_url.clone(), in_env(GATEWAY_URL_ENV)),
264            (user.gateway.url.clone(), in_user("url under [gateway]")),
265            (
266                suite_map.ai_gateway_url.clone(),
267                "published by the tracing server".to_string(),
268            ),
269        ]);
270        let (project, project_source) = first_from([
271            (env.gateway_project.clone(), in_env(GATEWAY_PROJECT_ENV)),
272            (
273                repo.gateway.project.clone(),
274                "project under [gateway] in .visdom/config.toml".to_string(),
275            ),
276            (
277                user.gateway.project.clone(),
278                in_user("project under [gateway]"),
279            ),
280        ]);
281        let (gateway_model, model_source) = first_from([
282            (env.gateway_model.clone(), in_env(GATEWAY_MODEL_ENV)),
283            (
284                user.gateway.model_for(agent),
285                in_user(&format!(
286                    "{}_model under [gateway]",
287                    config::agent_config_key(agent)
288                )),
289            ),
290        ]);
291        let gateway = (mode.mode == TracingMode::Gateway).then(|| {
292            runtime.block_on(plan_gateway(
293                &http,
294                console_url.clone(),
295                token.as_deref(),
296                project.as_deref(),
297            ))
298        });
299
300        let paths = AgentPaths {
301            home: env.home.clone(),
302            codex_home: env.codex_home.clone(),
303        };
304        let adapter = adapter_for(agent, paths, user.agents.program_for(agent))
305            .ok_or_else(|| format!("visdom cannot launch {}", agent.tool_name()))?;
306        Ok(Session {
307            ctx: CheckContext {
308                mode: mode.mode,
309                workdir: Workdir {
310                    start_dir: env.cwd.clone(),
311                    checkout: project_dir,
312                    primary: tracing_root,
313                },
314                home: env.home.clone(),
315                codex_home: env.codex_home.clone(),
316                agent,
317                server_url,
318                credential,
319            },
320            adapter,
321            bazaar_url,
322            user_config_path: config::user_config_path_in(&env.config_root),
323            warnings,
324            mode,
325            policy,
326            gateway,
327            suite: suite_map,
328            token,
329            gateway_model,
330            mcp_scope: McpScope::Local,
331            console_url,
332            gateway_sources: GatewaySources {
333                console_url: console_source,
334                project: project_source,
335                model: model_source,
336            },
337            config_root: env.config_root.clone(),
338            agent_instructions: user.agent_instructions.unwrap_or(true),
339        })
340    }
341
342    /// What an agent started now would have of Visdom's, `through_gateway`
343    /// saying whether its LLM traffic goes through the AI Gateway.
344    pub fn facts(&self, through_gateway: bool) -> Facts {
345        Facts {
346            tracing: tracing::working(&self.ctx),
347            bazaar: bazaar::registered_name(
348                self.bazaar_url.as_ref().ok().and_then(|url| url.as_deref()),
349                self.adapter.as_ref(),
350                &self.ctx.workdir,
351            ),
352            gateway: through_gateway,
353        }
354    }
355
356    /// `args` for the agent, with what it is told about Visdom's tools, if
357    /// it is told anything.
358    pub fn agent_args(&self, args: &[String], through_gateway: bool) -> Told {
359        if !self.agent_instructions {
360            return Told::Nothing(args.to_vec());
361        }
362        let mut facts = self.facts(through_gateway);
363        // The caller's own options may take the registered servers away from
364        // this one session.
365        let agent = self.ctx.agent;
366        // What was found is of the directory `visdom` was run in: a Codex
367        // sent to work in another one is told nothing of it.
368        if agent == Agent::Codex && instructions::codex_works_elsewhere(args) {
369            return Told::Nothing(args.to_vec());
370        }
371        facts.tracing &= !instructions::without_hooks(agent, args);
372        let profile_changes_mcp = agent == Agent::Codex
373            && instructions::codex_profile_changes_mcp(args, &self.ctx.codex_home);
374        facts.bazaar = facts.bazaar.filter(|name| {
375            !profile_changes_mcp && !instructions::without_registered_mcp(agent, args, name)
376        });
377        match instructions::compose(&facts) {
378            Some(text) => instructions::agent_args(
379                self.ctx.agent,
380                &text,
381                args,
382                &self.ctx.codex_home,
383                &self.ctx.workdir.start_dir,
384            ),
385            None => Told::Nothing(args.to_vec()),
386        }
387    }
388
389    /// Tracing, then the mode and the gateway, then bazaar.
390    pub fn collect(&self) -> Vec<Finding> {
391        let mut findings = tracing::check(&self.ctx);
392        findings.extend(gateway_checks::check(
393            &self.mode,
394            &self.policy,
395            self.gateway.as_ref(),
396            self.ctx.agent,
397        ));
398        findings.extend(bazaar::check(
399            self.bazaar_url
400                .as_ref()
401                .map(|url| url.as_deref())
402                .map_err(String::as_str),
403            self.adapter.as_ref(),
404            &self.ctx.workdir,
405            &self.user_config_path,
406            self.mcp_scope,
407        ));
408        findings
409    }
410}
411
412/// The developer's Keycloak access token for the project containing
413/// `start`, refreshed if needed. An error says why there is none.
414pub fn person_token(start: &Path, runtime: &tokio::runtime::Runtime) -> Result<String, String> {
415    let root = git_toplevel(start)
416        .map(|dir| tracevault_cli::paths::resolve_project_root(&dir).root)
417        .unwrap_or_else(|| start.to_path_buf());
418    let login = "the AI Gateway needs a Visdom account login: run `visdom login`";
419    match tracevault_cli::credentials::resolve_credentials_quiet(&root) {
420        Ok((Some(url), Some(session @ Credential::Keycloak(_)))) => runtime
421            .block_on(
422                tracevault_cli::api_client::ApiClient::with_credential(&url, Some(session))
423                    .bearer_valid_for(MIN_TOKEN_SECONDS),
424            )
425            .map_err(|e| format!("your Visdom login could not be used ({e}): run `visdom login`"))?
426            .ok_or_else(|| login.to_string()),
427        Ok(_) => Err(login.to_string()),
428        Err(e) => Err(e.to_string()),
429    }
430}
431
432/// The account of the login stored for the project containing `start`, read
433/// from the token as it is on disk: nobody is asked. `None` without a Visdom
434/// account login.
435pub fn stored_account(start: &Path) -> Option<String> {
436    let root = git_toplevel(start)
437        .map(|dir| tracevault_cli::paths::resolve_project_root(&dir).root)
438        .unwrap_or_else(|| start.to_path_buf());
439    match tracevault_cli::credentials::resolve_credentials_quiet(&root) {
440        Ok((_, Some(Credential::Keycloak(session)))) => {
441            Some(gateway::account_of(&session.access_token))
442        }
443        _ => None,
444    }
445}
446
447/// How long the token handed to the suite's other products must still be
448/// valid: enough for the few calls of one run.
449const MIN_TOKEN_SECONDS: i64 = 60;
450
451/// The HTTP client for the questions asked before an agent starts: nothing
452/// here may hold the developer up for long.
453pub fn http_client() -> reqwest::Client {
454    reqwest::Client::builder()
455        .timeout(std::time::Duration::from_secs(3))
456        .build()
457        .unwrap_or_default()
458}
459
460/// What a session through the gateway will use: the console, the LLM gateway
461/// behind it and the project whose key the agent gets. Nothing is issued.
462pub async fn plan_gateway(
463    http: &reqwest::Client,
464    console_url: Option<String>,
465    token: Option<&str>,
466    project: Option<&str>,
467) -> Result<GatewayPlan, String> {
468    let console_url = console_url.ok_or(
469        "this installation names no AI Gateway: set url under [gateway] in your visdom config, \
470         or VISDOM_GATEWAY_URL, to the gateway console's address",
471    )?;
472    if !bazaar::is_http_url(&console_url) {
473        return Err(format!(
474            "the AI Gateway address `{console_url}` is not an http(s) URL"
475        ));
476    }
477    let token = token.ok_or(
478        "the AI Gateway needs a Visdom account login (an API key does not work there): run \
479         `visdom login`",
480    )?;
481    let llm_url = gateway::llm_gateway_url(http, &console_url, token).await?;
482    let open = gateway::open_projects(http, &console_url, token).await?;
483    let project = gateway::pick_project(project, &open)?;
484    Ok(GatewayPlan {
485        console_url,
486        llm_url,
487        project,
488    })
489}
490
491/// No credential was resolved: either there is none, or the credential file
492/// is there and cannot be read or parsed (the library treats both alike).
493fn missing_or_unreadable() -> CredentialState {
494    use tracevault_cli::credentials::Credentials;
495    match Credentials::existing_path() {
496        Ok(path) if path.exists() && Credentials::load().is_none() => {
497            CredentialState::Unreadable(path.display().to_string())
498        }
499        _ => CredentialState::Missing,
500    }
501}
502
503/// Carries out fixes by running commands: `visdom` itself for tracing and
504/// login, the agent's own CLI for its MCP configuration.
505pub struct RealExecutor {
506    /// This executable.
507    pub visdom: PathBuf,
508    /// Send the commands' stdout to stderr (when stdout carries JSON).
509    pub stdout_to_stderr: bool,
510    /// Give the commands no stdin, so none of them can stop to ask anything:
511    /// with `--yes` the fix shown is applied with its defaults.
512    pub no_questions: bool,
513}
514
515impl RealExecutor {
516    pub fn new(stdout_to_stderr: bool, policy: FixPolicy) -> Self {
517        RealExecutor {
518            visdom: std::env::current_exe().unwrap_or_else(|_| PathBuf::from("visdom")),
519            stdout_to_stderr,
520            no_questions: policy == FixPolicy::All,
521        }
522    }
523
524    fn run(&self, program: &str, args: &[String], cwd: Option<&Path>) -> Result<(), String> {
525        let line = command_line(program, args);
526        let mut cmd = Command::new(program);
527        cmd.args(args);
528        if let Some(dir) = cwd {
529            cmd.current_dir(dir);
530        }
531        if self.stdout_to_stderr {
532            cmd.stdout(Stdio::from(std::io::stderr()));
533        }
534        if self.no_questions {
535            cmd.stdin(Stdio::null());
536        }
537        match cmd.status() {
538            Ok(status) if status.success() => Ok(()),
539            Ok(status) => Err(format!("`{line}` failed ({status})")),
540            Err(e) => Err(format!("cannot run `{line}`: {e}")),
541        }
542    }
543}
544
545impl FixExecutor for RealExecutor {
546    fn execute(&mut self, action: &FixAction) -> Result<(), String> {
547        let visdom = self.visdom.to_string_lossy().into_owned();
548        match action {
549            FixAction::TracingInit { agent, dir } => self.run(
550                &visdom,
551                &["trace", "init", "--agent", agent.tool_name()].map(String::from),
552                Some(dir),
553            ),
554            FixAction::Login { server_url } => self.run(
555                &visdom,
556                &["login", "--server-url", server_url].map(String::from),
557                None,
558            ),
559            FixAction::RunCommand { program, args, cwd } => self.run(program, args, cwd.as_deref()),
560            FixAction::Sequence { steps } => steps.iter().try_for_each(|step| self.execute(step)),
561        }
562    }
563}
564
565/// Whether a line read at the prompt is a yes. Enter alone is; end of input
566/// (nothing read, not even a newline) and a read error are not.
567pub fn is_yes(read: std::io::Result<usize>, line: &str) -> bool {
568    match read {
569        Ok(0) | Err(_) => false,
570        Ok(_) => matches!(line.trim(), "" | "y" | "Y" | "yes"),
571    }
572}
573
574/// Show one fix on the terminal and read the answer.
575pub fn ask_on_terminal(fix: &Fix) -> bool {
576    eprint!("Apply: {}? [Y/n] ", fix.description);
577    let _ = std::io::stderr().flush();
578    let mut answer = String::new();
579    let read = std::io::stdin().lock().read_line(&mut answer);
580    is_yes(read, &answer)
581}
582
583/// How a round of fixes went.
584#[derive(Clone, Copy, Debug, PartialEq, Eq)]
585pub struct FixSummary {
586    /// Something was changed, so the checks are worth running again.
587    pub applied: bool,
588    /// A fix that was meant to be applied failed.
589    pub failed: bool,
590}
591
592/// Offer the fixes of `findings` under `policy`, reporting each failure on
593/// stderr. A fix applied without asking is still shown first.
594pub fn fix(findings: &[Finding], policy: FixPolicy, exec: &mut dyn FixExecutor) -> FixSummary {
595    if policy == FixPolicy::All {
596        let mut shown: Vec<&str> = Vec::new();
597        for fix in findings.iter().filter_map(|f| f.fix.as_ref()) {
598            if !shown.contains(&fix.description.as_str()) {
599                eprintln!("visdom: applying: {}", fix.description);
600                shown.push(&fix.description);
601            }
602        }
603    }
604    let outcomes: Vec<FixOutcome> = apply_fixes(findings, policy, &mut ask_on_terminal, exec);
605    let mut reported: Vec<&str> = Vec::new();
606    for error in outcomes.iter().filter_map(|o| o.error.as_deref()) {
607        if !reported.contains(&error) {
608            eprintln!("visdom: fix failed: {error}");
609            reported.push(error);
610        }
611    }
612    FixSummary {
613        applied: outcomes.iter().any(|o| o.applied),
614        failed: outcomes.iter().any(|o| o.error.is_some()),
615    }
616}
617
618/// What a developer sees before the agent starts (or after `init`): the
619/// findings that need attention, on stderr. Nothing when all is well.
620pub fn print_attention(findings: &[Finding]) {
621    let attention = needs_attention(findings);
622    if !attention.is_empty() {
623        eprint!("{}", render_text(&attention));
624    }
625}
626
627#[cfg(test)]
628mod tests {
629    use super::*;
630
631    #[test]
632    fn end_of_input_at_the_prompt_is_a_no() {
633        assert!(is_yes(Ok(1), "\n"));
634        assert!(is_yes(Ok(2), "y\n"));
635        assert!(is_yes(Ok(4), "yes\n"));
636        assert!(!is_yes(Ok(2), "n\n"));
637        assert!(!is_yes(Ok(6), "maybe\n"));
638        // Ctrl-D: nothing was read.
639        assert!(!is_yes(Ok(0), ""));
640        assert!(!is_yes(Err(std::io::Error::other("closed")), ""));
641    }
642
643    /// With `--yes` a fix must not stop to ask: its command gets no stdin.
644    #[test]
645    fn no_questions_gives_commands_an_empty_stdin() {
646        let tmp = tempfile::tempdir().unwrap();
647        let out = tmp.path().join("read");
648        let mut exec = RealExecutor {
649            visdom: PathBuf::from("visdom"),
650            stdout_to_stderr: true,
651            no_questions: true,
652        };
653        let script = format!("cat > '{}'", out.display());
654        let result = exec.execute(&FixAction::RunCommand {
655            program: "sh".to_string(),
656            args: vec!["-c".to_string(), script],
657            cwd: None,
658        });
659        assert_eq!(result, Ok(()));
660        assert_eq!(std::fs::read(&out).unwrap(), b"");
661        assert!(RealExecutor::new(false, FixPolicy::All).no_questions);
662        assert!(!RealExecutor::new(false, FixPolicy::Ask).no_questions);
663    }
664
665    #[test]
666    fn settings_outside_a_checkout_are_the_nearest_folders_above() {
667        let tmp = tempfile::tempdir().unwrap();
668        let below = tmp.path().join("a").join("b");
669        std::fs::create_dir_all(&below).unwrap();
670        assert_eq!(settings_dir(&below), None);
671        std::fs::create_dir_all(tmp.path().join(".visdom")).unwrap();
672        std::fs::write(config::repo_config_path_in(tmp.path()), "").unwrap();
673        assert_eq!(settings_dir(&below).as_deref(), Some(tmp.path()));
674        // A checkout's own top level wins, with or without the file.
675        let status = Command::new("git")
676            .args(["init", "-q"])
677            .current_dir(&below)
678            .status()
679            .unwrap();
680        assert!(status.success());
681        assert_eq!(settings_dir(&below), git_toplevel(&below));
682    }
683
684    #[test]
685    fn git_toplevel_is_none_outside_a_repository() {
686        let tmp = tempfile::tempdir().unwrap();
687        assert_eq!(git_toplevel(tmp.path()), None);
688    }
689
690    #[test]
691    fn git_toplevel_from_a_subdirectory() {
692        let tmp = tempfile::tempdir().unwrap();
693        let status = Command::new("git")
694            .args(["init", "-q"])
695            .current_dir(tmp.path())
696            .status()
697            .unwrap();
698        assert!(status.success());
699        let sub = tmp.path().join("a/b");
700        std::fs::create_dir_all(&sub).unwrap();
701        assert_eq!(git_toplevel(&sub), Some(tmp.path().canonicalize().unwrap()));
702    }
703
704    #[test]
705    fn executor_reports_a_failing_and_a_missing_command() {
706        let mut exec = RealExecutor {
707            visdom: PathBuf::from("visdom"),
708            stdout_to_stderr: true,
709            no_questions: false,
710        };
711        let run = |program: &str, args: &[&str]| FixAction::RunCommand {
712            program: program.to_string(),
713            args: args.iter().map(|a| a.to_string()).collect(),
714            cwd: None,
715        };
716        assert_eq!(exec.execute(&run("true", &[])), Ok(()));
717        let err = exec.execute(&run("false", &[])).unwrap_err();
718        assert!(err.contains("`false` failed"), "{err}");
719        let err = exec
720            .execute(&run("/nonexistent/visdom-test-program", &["x"]))
721            .unwrap_err();
722        assert!(err.contains("cannot run"), "{err}");
723    }
724
725    #[test]
726    fn sequence_stops_at_the_first_failure() {
727        let tmp = tempfile::tempdir().unwrap();
728        let marker = tmp.path().join("ran");
729        let mut exec = RealExecutor {
730            visdom: PathBuf::from("visdom"),
731            stdout_to_stderr: true,
732            no_questions: false,
733        };
734        let step = |program: &str, args: Vec<String>| FixAction::RunCommand {
735            program: program.to_string(),
736            args,
737            cwd: None,
738        };
739        let result = exec.execute(&FixAction::Sequence {
740            steps: vec![
741                step("false", vec![]),
742                step("touch", vec![marker.to_string_lossy().into_owned()]),
743            ],
744        });
745        assert!(result.is_err());
746        assert!(!marker.exists(), "the step after a failure must not run");
747    }
748
749    #[test]
750    fn run_command_uses_its_directory() {
751        let tmp = tempfile::tempdir().unwrap();
752        let mut exec = RealExecutor {
753            visdom: PathBuf::from("visdom"),
754            stdout_to_stderr: true,
755            no_questions: false,
756        };
757        let result = exec.execute(&FixAction::RunCommand {
758            program: "touch".to_string(),
759            args: vec!["here".to_string()],
760            cwd: Some(tmp.path().to_path_buf()),
761        });
762        assert_eq!(result, Ok(()));
763        assert!(tmp.path().join("here").exists());
764    }
765}