1use 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::billing::{self, billing_use, Billing, BillingUse, ResolvedBilling};
13use crate::components::gateway::GatewayPlan;
14use crate::components::{
15 bazaar, gateway as gateway_checks, tracing, CheckContext, CredentialState,
16};
17use crate::config::{self, RepoConfig, UserConfig};
18use crate::finding::{command_line, needs_attention, render_text, Finding, Fix, FixAction};
19use crate::fixes::{apply_fixes, FixExecutor, FixOutcome, FixPolicy};
20use crate::gateway;
21use crate::instructions::{self, Facts, Told};
22use crate::mode::{configured_mode, effective_mode, ResolvedMode, TracingMode, MODE_ENV};
23use crate::subscription::{self, KeyState};
24use crate::suite::{self, PolicyState, SuiteMap};
25
26fn first_set(candidates: [Option<String>; 3]) -> Option<String> {
28 candidates
29 .into_iter()
30 .flatten()
31 .map(|v| v.trim().trim_end_matches('/').to_string())
32 .find(|v| !v.is_empty())
33}
34
35pub fn git_toplevel(from: &Path) -> Option<PathBuf> {
37 let output = Command::new("git")
38 .args(["rev-parse", "--show-toplevel"])
39 .current_dir(from)
40 .stderr(Stdio::null())
41 .output()
42 .ok()
43 .filter(|o| o.status.success())?;
44 let path = PathBuf::from(String::from_utf8(output.stdout).ok()?.trim());
45 Some(path.canonicalize().unwrap_or(path))
46}
47
48pub fn settings_dir(cwd: &Path) -> Option<PathBuf> {
52 git_toplevel(cwd).or_else(|| {
53 cwd.ancestors()
54 .find(|dir| config::repo_config_path_in(dir).is_file())
55 .map(Path::to_path_buf)
56 })
57}
58
59pub const GATEWAY_URL_ENV: &str = "VISDOM_GATEWAY_URL";
60pub const GATEWAY_PROJECT_ENV: &str = "VISDOM_GATEWAY_PROJECT";
61pub const GATEWAY_MODEL_ENV: &str = "VISDOM_GATEWAY_MODEL";
62
63#[derive(Clone, Debug, Default, PartialEq, Eq)]
67pub struct GatewaySources {
68 pub console_url: Option<String>,
69 pub project: Option<String>,
70 pub model: Option<String>,
71}
72
73fn first_from<const N: usize>(
75 candidates: [(Option<String>, String); N],
76) -> (Option<String>, Option<String>) {
77 candidates
78 .into_iter()
79 .find_map(|(value, source)| {
80 value
81 .filter(|v| !v.trim().is_empty())
82 .map(|v| (Some(v), Some(source)))
83 })
84 .unwrap_or((None, None))
85}
86
87pub struct Environment {
89 pub cwd: PathBuf,
90 pub home: PathBuf,
91 pub config_root: PathBuf,
93 pub codex_home: PathBuf,
94 pub agent: Option<String>,
96 pub bazaar_url: Option<String>,
98 pub mode: Option<String>,
100 pub gateway_url: Option<String>,
102 pub control_plane_url: Option<String>,
104 pub gateway_project: Option<String>,
106 pub gateway_model: Option<String>,
108 pub gateway_billing: Option<String>,
110}
111
112impl Environment {
113 pub fn current() -> Self {
114 let home = dirs::home_dir().unwrap_or_default();
115 let set = |name: &str| std::env::var(name).ok().filter(|v| !v.trim().is_empty());
116 Environment {
117 cwd: std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
118 config_root: dirs::config_dir().unwrap_or_else(|| home.join(".config")),
119 codex_home: set("CODEX_HOME")
120 .map(PathBuf::from)
121 .unwrap_or_else(|| home.join(".codex")),
122 agent: set("VISDOM_AGENT"),
123 bazaar_url: set("VISDOM_BAZAAR_URL"),
124 mode: set(MODE_ENV),
125 gateway_url: set("VISDOM_GATEWAY_URL"),
126 control_plane_url: set("VISDOM_CONTROL_PLANE_URL"),
127 gateway_project: set(GATEWAY_PROJECT_ENV),
128 gateway_model: set(GATEWAY_MODEL_ENV),
129 gateway_billing: set(billing::BILLING_ENV),
130 home,
131 }
132 }
133}
134
135pub struct Session {
137 pub ctx: CheckContext,
138 pub adapter: Box<dyn AgentAdapter>,
139 pub bazaar_url: Result<Option<String>, String>,
141 pub user_config_path: PathBuf,
142 pub warnings: Vec<String>,
144 pub mode: ResolvedMode,
146 pub policy: PolicyState,
147 pub gateway: Option<Result<GatewayPlan, String>>,
149 pub suite: SuiteMap,
151 pub token: Option<String>,
154 pub gateway_model: Option<String>,
156 pub mcp_scope: McpScope,
159 pub console_url: Option<String>,
161 pub gateway_sources: GatewaySources,
163 pub config_root: PathBuf,
165 pub agent_instructions: bool,
168 pub billing: ResolvedBilling,
170 pub billing_use: BillingUse,
172 pub subscription: Vec<Finding>,
174}
175
176impl Session {
177 pub fn gather(
181 env: &Environment,
182 agent_flag: Option<Agent>,
183 mode_flag: Option<TracingMode>,
184 billing_flag: Option<Billing>,
185 runtime: &tokio::runtime::Runtime,
186 ) -> Result<Session, String> {
187 let mut warnings = Vec::new();
188 let project_dir = git_toplevel(&env.cwd);
189 let user: UserConfig = config::load_user_config_in(&env.config_root).unwrap_or_else(|e| {
190 warnings.push(e);
191 UserConfig::default()
192 });
193 let repo = settings_dir(&env.cwd)
194 .as_deref()
195 .map(config::load_repo_config_in)
196 .transpose()
197 .unwrap_or_else(|e| {
198 warnings.push(e);
199 None
200 })
201 .unwrap_or_default();
202 let repo: RepoConfig = repo;
203 let agent = config::resolve_agent(agent_flag, env.agent.as_deref(), &repo, &user)?;
204 let chosen = configured_mode(
205 mode_flag,
206 env.mode.as_deref(),
207 repo.tracing_mode,
208 user.tracing_mode,
209 )?;
210 let billing = billing::configured_billing(
211 billing_flag,
212 env.gateway_billing.as_deref(),
213 repo.gateway.billing,
214 user.gateway.billing,
215 &config::user_config_path_in(&env.config_root)
216 .display()
217 .to_string(),
218 )?;
219
220 let tracing_root = project_dir
221 .as_deref()
222 .map(|dir| tracevault_cli::paths::resolve_project_root(dir).root);
223 let credential_root = tracing_root.as_deref().unwrap_or(&env.cwd);
224 let (server_url, credential, session) =
225 match tracevault_cli::credentials::resolve_credentials_quiet(credential_root) {
226 Ok((url, Some(credential))) => {
227 let session = match credential {
228 Credential::Keycloak(_) => Some(credential),
229 Credential::ApiKey(_) => None,
230 };
231 (url, CredentialState::Present, session)
232 }
233 Ok((url, None)) => (url, missing_or_unreadable(), None),
234 Err(e) => (None, CredentialState::Unusable(e.to_string()), None),
235 };
236
237 let http = http_client();
238 let published = match &server_url {
240 Some(url) => runtime.block_on(suite::fetch_suite_map(&http, url)),
241 None => Ok(SuiteMap::default()),
242 };
243 let bazaar_url = bazaar::resolve_bazaar_url(env.bazaar_url.clone(), &user, &published);
244 let suite_map = match &server_url {
247 Some(url) => suite::suite_map_or_remembered(
248 &published,
249 url,
250 &suite::suite_cache_path_in(&env.config_root),
251 ),
252 None => SuiteMap::default(),
253 };
254
255 let token = match (&server_url, session) {
258 (Some(url), Some(session)) => runtime
259 .block_on(
260 tracevault_cli::api_client::ApiClient::with_credential(url, Some(session))
261 .bearer_valid_for(MIN_TOKEN_SECONDS),
262 )
263 .ok()
264 .flatten(),
265 _ => None,
266 };
267 let control_plane_url = first_set([
268 env.control_plane_url.clone(),
269 user.control_plane_url.clone(),
270 suite_map.control_plane_url.clone(),
271 ]);
272 let policy = runtime.block_on(suite::resolve_policy(
273 &http,
274 control_plane_url.as_deref(),
275 token.as_deref(),
276 &suite::policy_cache_path_in(&env.config_root),
277 ));
278 let mode = effective_mode(chosen, policy.policy());
279 let billing_use = billing_use(&billing, &mode, agent);
280 let user_file = config::user_config_path_in(&env.config_root);
283 let in_env = |name: &str| format!("{name} in the environment");
284 let in_user = |key: &str| format!("{key} in {}", user_file.display());
285 let (console_url, console_source) = first_from([
286 (env.gateway_url.clone(), in_env(GATEWAY_URL_ENV)),
287 (user.gateway.url.clone(), in_user("url under [gateway]")),
288 (
289 suite_map.ai_gateway_url.clone(),
290 "published by the tracing server".to_string(),
291 ),
292 ]);
293 let (project, project_source) = first_from([
294 (env.gateway_project.clone(), in_env(GATEWAY_PROJECT_ENV)),
295 (
296 repo.gateway.project.clone(),
297 "project under [gateway] in .visdom/config.toml".to_string(),
298 ),
299 (
300 user.gateway.project.clone(),
301 in_user("project under [gateway]"),
302 ),
303 ]);
304 let (gateway_model, model_source) = first_from([
305 (env.gateway_model.clone(), in_env(GATEWAY_MODEL_ENV)),
306 (
307 user.gateway.model_for(agent),
308 in_user(&format!(
309 "{}_model under [gateway]",
310 config::agent_config_key(agent)
311 )),
312 ),
313 ]);
314 let gateway = (mode.mode == TracingMode::Gateway).then(|| {
315 runtime.block_on(plan_gateway(
316 &http,
317 console_url.clone(),
318 token.as_deref(),
319 project.as_deref(),
320 ))
321 });
322
323 let paths = AgentPaths {
324 home: env.home.clone(),
325 codex_home: env.codex_home.clone(),
326 };
327 let adapter = adapter_for(agent, paths, user.agents.program_for(agent))
328 .ok_or_else(|| format!("visdom cannot launch {}", agent.tool_name()))?;
329 Ok(Session {
330 ctx: CheckContext {
331 mode: mode.mode,
332 workdir: Workdir {
333 start_dir: env.cwd.clone(),
334 checkout: project_dir,
335 primary: tracing_root,
336 },
337 home: env.home.clone(),
338 codex_home: env.codex_home.clone(),
339 agent,
340 server_url,
341 credential,
342 },
343 adapter,
344 bazaar_url,
345 user_config_path: config::user_config_path_in(&env.config_root),
346 warnings,
347 mode,
348 policy,
349 gateway,
350 suite: suite_map,
351 token,
352 gateway_model,
353 mcp_scope: McpScope::Local,
354 console_url,
355 gateway_sources: GatewaySources {
356 console_url: console_source,
357 project: project_source,
358 model: model_source,
359 },
360 config_root: env.config_root.clone(),
361 agent_instructions: user.agent_instructions.unwrap_or(true),
362 billing,
363 billing_use,
364 subscription: Vec::new(),
365 })
366 }
367
368 pub fn on_subscription(&self) -> bool {
371 self.mode.mode == TracingMode::Gateway
372 && self.billing_use == BillingUse::Applies
373 && self.billing.billing == Billing::Subscription
374 }
375
376 pub fn subscription_model(&self) -> Option<String> {
380 let eligible = match &self.gateway {
381 Some(Ok(plan)) => plan.project.subscription_aliases().unwrap_or_default(),
382 _ => Vec::new(),
383 };
384 gateway::pick_model(self.ctx.agent, self.gateway_model.as_deref(), &eligible)
385 }
386
387 pub fn check_subscription(
394 &mut self,
395 model: Option<&str>,
396 agent_args: &[String],
397 key: Option<&KeyState>,
398 ) {
399 self.subscription.clear();
400 if !self.on_subscription() {
401 return;
402 }
403 if let Some(Ok(plan)) = &self.gateway {
404 self.subscription
405 .push(subscription::traffic_finding(plan.subscription_traffic));
406 }
407 self.subscription
408 .push(subscription::login_finding(&subscription::claude_login(
409 self.adapter.program(),
410 agent_args,
411 &crate::launch::private_dir(&self.config_root),
412 )));
413 let project_dir = self
416 .ctx
417 .workdir
418 .checkout
419 .clone()
420 .unwrap_or_else(|| self.ctx.workdir.start_dir.clone());
421 if let Some(Ok(plan)) = &self.gateway {
422 let claude_env = subscription::ClaudeEnv::read(
426 &subscription::managed_settings_path(),
427 &self.ctx.home,
428 Some(&project_dir),
429 agent_args,
430 );
431 let uses = subscription::models_in_use(model, agent_args, &|name| {
432 claude_env.get(name, &|name| std::env::var(name).ok())
433 });
434 self.subscription.push(subscription::model_finding(
435 &uses,
436 self.gateway_sources.model.as_deref(),
437 &plan.project,
438 &format!("{}_model", config::agent_config_key(self.ctx.agent)),
439 ));
440 }
441 if let Some(key) = key {
442 self.subscription.push(subscription::key_finding(key));
443 }
444 self.subscription.push(subscription::settings_finding(
445 &subscription::managed_settings_path(),
446 &self.ctx.home,
447 Some(&project_dir),
448 ));
449 }
450
451 pub fn kept_subscription_key(&self, runtime: &tokio::runtime::Runtime, now: i64) -> KeyState {
456 let (Some(Ok(plan)), Some(token)) = (&self.gateway, &self.token) else {
457 return KeyState::NoneKept;
458 };
459 let store = gateway::KeyStore::at(gateway::key_store_path_in(&self.config_root));
460 let kept = store.unexpired(
461 &plan.console_url,
462 &plan.project.id,
463 &gateway::account_of(token),
464 Billing::Subscription,
465 now,
466 );
467 let Some(key) = kept else {
468 return KeyState::NoneKept;
469 };
470 match runtime.block_on(gateway::models(&http_client(), &plan.llm_url, &key.secret)) {
471 Ok(_) => KeyState::Accepted {
472 expires_at: key.expires_at,
473 },
474 Err(refusal) if refusal.rejected => KeyState::KeptRefused,
475 Err(refusal) => KeyState::Failed(refusal.why),
476 }
477 }
478
479 pub fn subscription_blocked(&self) -> bool {
482 self.subscription
483 .iter()
484 .any(|f| f.severity == crate::finding::Severity::Error)
485 }
486
487 pub fn facts(&self, through_gateway: bool) -> Facts {
490 Facts {
491 tracing: tracing::working(&self.ctx),
492 bazaar: bazaar::registered_name(
493 self.bazaar_url.as_ref().ok().and_then(|url| url.as_deref()),
494 self.adapter.as_ref(),
495 &self.ctx.workdir,
496 ),
497 gateway: through_gateway,
498 }
499 }
500
501 pub fn agent_args(&self, args: &[String], through_gateway: bool) -> Told {
504 if !self.agent_instructions {
505 return Told::Nothing(args.to_vec());
506 }
507 let mut facts = self.facts(through_gateway);
508 let agent = self.ctx.agent;
511 if agent == Agent::Codex && instructions::codex_works_elsewhere(args) {
514 return Told::Nothing(args.to_vec());
515 }
516 facts.tracing &= !instructions::without_hooks(agent, args);
517 let profile_changes_mcp = agent == Agent::Codex
518 && instructions::codex_profile_changes_mcp(args, &self.ctx.codex_home);
519 facts.bazaar = facts.bazaar.filter(|name| {
520 !profile_changes_mcp && !instructions::without_registered_mcp(agent, args, name)
521 });
522 match instructions::compose(&facts) {
523 Some(text) => instructions::agent_args(
524 self.ctx.agent,
525 &text,
526 args,
527 &self.ctx.codex_home,
528 &self.ctx.workdir.start_dir,
529 ),
530 None => Told::Nothing(args.to_vec()),
531 }
532 }
533
534 pub fn collect(&self) -> Vec<Finding> {
536 let mut findings = tracing::check(&self.ctx);
537 findings.extend(gateway_checks::check(
538 &self.mode,
539 &self.policy,
540 self.gateway.as_ref(),
541 self.ctx.agent,
542 ));
543 findings.extend(gateway_checks::billing_finding(
544 &self.billing,
545 &self.billing_use,
546 ));
547 findings.extend(self.subscription.iter().cloned());
548 findings.extend(bazaar::check(
549 self.bazaar_url
550 .as_ref()
551 .map(|url| url.as_deref())
552 .map_err(String::as_str),
553 self.adapter.as_ref(),
554 &self.ctx.workdir,
555 &self.user_config_path,
556 self.mcp_scope,
557 ));
558 findings
559 }
560}
561
562pub fn person_token(start: &Path, runtime: &tokio::runtime::Runtime) -> Result<String, String> {
565 let root = git_toplevel(start)
566 .map(|dir| tracevault_cli::paths::resolve_project_root(&dir).root)
567 .unwrap_or_else(|| start.to_path_buf());
568 let login = "the AI Gateway needs a Visdom account login: run `visdom login`";
569 match tracevault_cli::credentials::resolve_credentials_quiet(&root) {
570 Ok((Some(url), Some(session @ Credential::Keycloak(_)))) => runtime
571 .block_on(
572 tracevault_cli::api_client::ApiClient::with_credential(&url, Some(session))
573 .bearer_valid_for(MIN_TOKEN_SECONDS),
574 )
575 .map_err(|e| format!("your Visdom login could not be used ({e}): run `visdom login`"))?
576 .ok_or_else(|| login.to_string()),
577 Ok(_) => Err(login.to_string()),
578 Err(e) => Err(e.to_string()),
579 }
580}
581
582pub fn stored_account(start: &Path) -> Option<String> {
586 let root = git_toplevel(start)
587 .map(|dir| tracevault_cli::paths::resolve_project_root(&dir).root)
588 .unwrap_or_else(|| start.to_path_buf());
589 match tracevault_cli::credentials::resolve_credentials_quiet(&root) {
590 Ok((_, Some(Credential::Keycloak(session)))) => {
591 Some(gateway::account_of(&session.access_token))
592 }
593 _ => None,
594 }
595}
596
597const MIN_TOKEN_SECONDS: i64 = 60;
600
601pub fn http_client() -> reqwest::Client {
604 reqwest::Client::builder()
605 .timeout(std::time::Duration::from_secs(3))
606 .build()
607 .unwrap_or_default()
608}
609
610pub async fn plan_gateway(
613 http: &reqwest::Client,
614 console_url: Option<String>,
615 token: Option<&str>,
616 project: Option<&str>,
617) -> Result<GatewayPlan, String> {
618 let console_url = console_url.ok_or(
619 "this installation names no AI Gateway: set url under [gateway] in your visdom config, \
620 or VISDOM_GATEWAY_URL, to the gateway console's address",
621 )?;
622 if !bazaar::is_http_url(&console_url) {
623 return Err(format!(
624 "the AI Gateway address `{console_url}` is not an http(s) URL"
625 ));
626 }
627 let token = token.ok_or(
628 "the AI Gateway needs a Visdom account login (an API key does not work there): run \
629 `visdom login`",
630 )?;
631 let settings = gateway::console_settings(http, &console_url, token).await?;
632 let open = gateway::open_projects(http, &console_url, token).await?;
633 let project = gateway::pick_project(project, &open)?;
634 Ok(GatewayPlan {
635 console_url,
636 llm_url: settings.llm_url,
637 project,
638 subscription_traffic: settings.subscription_traffic,
639 })
640}
641
642fn missing_or_unreadable() -> CredentialState {
645 use tracevault_cli::credentials::Credentials;
646 match Credentials::existing_path() {
647 Ok(path) if path.exists() && Credentials::load().is_none() => {
648 CredentialState::Unreadable(path.display().to_string())
649 }
650 _ => CredentialState::Missing,
651 }
652}
653
654pub struct RealExecutor {
657 pub visdom: PathBuf,
659 pub stdout_to_stderr: bool,
661 pub no_questions: bool,
664}
665
666impl RealExecutor {
667 pub fn new(stdout_to_stderr: bool, policy: FixPolicy) -> Self {
668 RealExecutor {
669 visdom: std::env::current_exe().unwrap_or_else(|_| PathBuf::from("visdom")),
670 stdout_to_stderr,
671 no_questions: policy == FixPolicy::All,
672 }
673 }
674
675 fn run(&self, program: &str, args: &[String], cwd: Option<&Path>) -> Result<(), String> {
676 let line = command_line(program, args);
677 let mut cmd = Command::new(program);
678 cmd.args(args);
679 if let Some(dir) = cwd {
680 cmd.current_dir(dir);
681 }
682 if self.stdout_to_stderr {
683 cmd.stdout(Stdio::from(std::io::stderr()));
684 }
685 if self.no_questions {
686 cmd.stdin(Stdio::null());
687 }
688 match cmd.status() {
689 Ok(status) if status.success() => Ok(()),
690 Ok(status) => Err(format!("`{line}` failed ({status})")),
691 Err(e) => Err(format!("cannot run `{line}`: {e}")),
692 }
693 }
694}
695
696impl FixExecutor for RealExecutor {
697 fn execute(&mut self, action: &FixAction) -> Result<(), String> {
698 let visdom = self.visdom.to_string_lossy().into_owned();
699 match action {
700 FixAction::TracingInit { agent, dir } => self.run(
701 &visdom,
702 &["trace", "init", "--agent", agent.tool_name()].map(String::from),
703 Some(dir),
704 ),
705 FixAction::Login { server_url } => self.run(
706 &visdom,
707 &["login", "--server-url", server_url].map(String::from),
708 None,
709 ),
710 FixAction::RunCommand { program, args, cwd } => self.run(program, args, cwd.as_deref()),
711 FixAction::Sequence { steps } => steps.iter().try_for_each(|step| self.execute(step)),
712 }
713 }
714}
715
716pub fn is_yes(read: std::io::Result<usize>, line: &str) -> bool {
719 match read {
720 Ok(0) | Err(_) => false,
721 Ok(_) => matches!(line.trim(), "" | "y" | "Y" | "yes"),
722 }
723}
724
725pub fn ask_on_terminal(fix: &Fix) -> bool {
727 eprint!("Apply: {}? [Y/n] ", fix.description);
728 let _ = std::io::stderr().flush();
729 let mut answer = String::new();
730 let read = std::io::stdin().lock().read_line(&mut answer);
731 is_yes(read, &answer)
732}
733
734#[derive(Clone, Copy, Debug, PartialEq, Eq)]
736pub struct FixSummary {
737 pub applied: bool,
739 pub failed: bool,
741}
742
743pub fn fix(findings: &[Finding], policy: FixPolicy, exec: &mut dyn FixExecutor) -> FixSummary {
746 if policy == FixPolicy::All {
747 let mut shown: Vec<&str> = Vec::new();
748 for fix in findings.iter().filter_map(|f| f.fix.as_ref()) {
749 if !shown.contains(&fix.description.as_str()) {
750 eprintln!("visdom: applying: {}", fix.description);
751 shown.push(&fix.description);
752 }
753 }
754 }
755 let outcomes: Vec<FixOutcome> = apply_fixes(findings, policy, &mut ask_on_terminal, exec);
756 let mut reported: Vec<&str> = Vec::new();
757 for error in outcomes.iter().filter_map(|o| o.error.as_deref()) {
758 if !reported.contains(&error) {
759 eprintln!("visdom: fix failed: {error}");
760 reported.push(error);
761 }
762 }
763 FixSummary {
764 applied: outcomes.iter().any(|o| o.applied),
765 failed: outcomes.iter().any(|o| o.error.is_some()),
766 }
767}
768
769pub fn print_attention(findings: &[Finding]) {
772 let attention = needs_attention(findings);
773 if !attention.is_empty() {
774 eprint!("{}", render_text(&attention));
775 }
776}
777
778#[cfg(test)]
779mod tests {
780 use super::*;
781
782 #[test]
783 fn end_of_input_at_the_prompt_is_a_no() {
784 assert!(is_yes(Ok(1), "\n"));
785 assert!(is_yes(Ok(2), "y\n"));
786 assert!(is_yes(Ok(4), "yes\n"));
787 assert!(!is_yes(Ok(2), "n\n"));
788 assert!(!is_yes(Ok(6), "maybe\n"));
789 assert!(!is_yes(Ok(0), ""));
791 assert!(!is_yes(Err(std::io::Error::other("closed")), ""));
792 }
793
794 #[test]
796 fn no_questions_gives_commands_an_empty_stdin() {
797 let tmp = tempfile::tempdir().unwrap();
798 let out = tmp.path().join("read");
799 let mut exec = RealExecutor {
800 visdom: PathBuf::from("visdom"),
801 stdout_to_stderr: true,
802 no_questions: true,
803 };
804 let script = format!("cat > '{}'", out.display());
805 let result = exec.execute(&FixAction::RunCommand {
806 program: "sh".to_string(),
807 args: vec!["-c".to_string(), script],
808 cwd: None,
809 });
810 assert_eq!(result, Ok(()));
811 assert_eq!(std::fs::read(&out).unwrap(), b"");
812 assert!(RealExecutor::new(false, FixPolicy::All).no_questions);
813 assert!(!RealExecutor::new(false, FixPolicy::Ask).no_questions);
814 }
815
816 #[test]
817 fn settings_outside_a_checkout_are_the_nearest_folders_above() {
818 let tmp = tempfile::tempdir().unwrap();
819 let below = tmp.path().join("a").join("b");
820 std::fs::create_dir_all(&below).unwrap();
821 assert_eq!(settings_dir(&below), None);
822 std::fs::create_dir_all(tmp.path().join(".visdom")).unwrap();
823 std::fs::write(config::repo_config_path_in(tmp.path()), "").unwrap();
824 assert_eq!(settings_dir(&below).as_deref(), Some(tmp.path()));
825 let status = Command::new("git")
827 .args(["init", "-q"])
828 .current_dir(&below)
829 .status()
830 .unwrap();
831 assert!(status.success());
832 assert_eq!(settings_dir(&below), git_toplevel(&below));
833 }
834
835 #[test]
836 fn git_toplevel_is_none_outside_a_repository() {
837 let tmp = tempfile::tempdir().unwrap();
838 assert_eq!(git_toplevel(tmp.path()), None);
839 }
840
841 #[test]
842 fn git_toplevel_from_a_subdirectory() {
843 let tmp = tempfile::tempdir().unwrap();
844 let status = Command::new("git")
845 .args(["init", "-q"])
846 .current_dir(tmp.path())
847 .status()
848 .unwrap();
849 assert!(status.success());
850 let sub = tmp.path().join("a/b");
851 std::fs::create_dir_all(&sub).unwrap();
852 assert_eq!(git_toplevel(&sub), Some(tmp.path().canonicalize().unwrap()));
853 }
854
855 #[test]
856 fn executor_reports_a_failing_and_a_missing_command() {
857 let mut exec = RealExecutor {
858 visdom: PathBuf::from("visdom"),
859 stdout_to_stderr: true,
860 no_questions: false,
861 };
862 let run = |program: &str, args: &[&str]| FixAction::RunCommand {
863 program: program.to_string(),
864 args: args.iter().map(|a| a.to_string()).collect(),
865 cwd: None,
866 };
867 assert_eq!(exec.execute(&run("true", &[])), Ok(()));
868 let err = exec.execute(&run("false", &[])).unwrap_err();
869 assert!(err.contains("`false` failed"), "{err}");
870 let err = exec
871 .execute(&run("/nonexistent/visdom-test-program", &["x"]))
872 .unwrap_err();
873 assert!(err.contains("cannot run"), "{err}");
874 }
875
876 #[test]
877 fn sequence_stops_at_the_first_failure() {
878 let tmp = tempfile::tempdir().unwrap();
879 let marker = tmp.path().join("ran");
880 let mut exec = RealExecutor {
881 visdom: PathBuf::from("visdom"),
882 stdout_to_stderr: true,
883 no_questions: false,
884 };
885 let step = |program: &str, args: Vec<String>| FixAction::RunCommand {
886 program: program.to_string(),
887 args,
888 cwd: None,
889 };
890 let result = exec.execute(&FixAction::Sequence {
891 steps: vec![
892 step("false", vec![]),
893 step("touch", vec![marker.to_string_lossy().into_owned()]),
894 ],
895 });
896 assert!(result.is_err());
897 assert!(!marker.exists(), "the step after a failure must not run");
898 }
899
900 #[test]
901 fn run_command_uses_its_directory() {
902 let tmp = tempfile::tempdir().unwrap();
903 let mut exec = RealExecutor {
904 visdom: PathBuf::from("visdom"),
905 stdout_to_stderr: true,
906 no_questions: false,
907 };
908 let result = exec.execute(&FixAction::RunCommand {
909 program: "touch".to_string(),
910 args: vec!["here".to_string()],
911 cwd: Some(tmp.path().to_path_buf()),
912 });
913 assert_eq!(result, Ok(()));
914 assert!(tmp.path().join("here").exists());
915 }
916}