uv_command_support/
update_shell.rs1#![cfg_attr(windows, allow(unreachable_code))]
2
3use std::fmt::Write;
4use std::path::Path;
5
6use anyhow::Result;
7use owo_colors::OwoColorize;
8use tracing::debug;
9
10use uv_fs::Simplified;
11use uv_shell::{ConfigurationUpdate, Shell, update_configuration_file};
12
13use crate::ExitStatus;
14use crate::Printer;
15
16pub async fn update_shell(executable_directory: &Path, printer: Printer) -> Result<ExitStatus> {
18 debug!(
19 "Ensuring that the executable directory is in PATH: {}",
20 executable_directory.simplified_display()
21 );
22
23 #[cfg(windows)]
24 {
25 if uv_shell::prepend_path(executable_directory)? {
26 writeln!(
27 printer.stderr(),
28 "Updated PATH to include executable directory {}",
29 executable_directory.simplified_display().cyan()
30 )?;
31 writeln!(printer.stderr(), "Restart your shell to apply changes")?;
32 } else {
33 writeln!(
34 printer.stderr(),
35 "Executable directory {} is already in PATH",
36 executable_directory.simplified_display().cyan()
37 )?;
38 }
39
40 return Ok(ExitStatus::Success);
41 }
42
43 if Shell::contains_path(executable_directory) {
44 writeln!(
45 printer.stderr(),
46 "Executable directory {} is already in PATH",
47 executable_directory.simplified_display().cyan()
48 )?;
49 return Ok(ExitStatus::Success);
50 }
51
52 let Some(shell) = Shell::from_env() else {
54 return Err(anyhow::anyhow!(
55 "The executable directory `{}` is not in PATH, but the current shell could not be determined",
56 executable_directory.simplified_display().cyan()
57 ));
58 };
59
60 let files = shell.configuration_files();
62 if files.is_empty() {
63 return Err(anyhow::anyhow!(
64 "The executable directory `{}` is not in PATH, but updating {shell} is currently unsupported",
65 executable_directory.simplified_display().cyan()
66 ));
67 }
68
69 let Some(command) = shell.prepend_path(executable_directory) else {
71 return Err(anyhow::anyhow!(
72 "The executable directory `{}` is not in PATH, but the necessary command to update {shell} could not be determined",
73 executable_directory.simplified_display().cyan()
74 ));
75 };
76
77 let mut updated = false;
79 for file in files {
80 match update_configuration_file(&file, &command).await? {
81 ConfigurationUpdate::Updated => {
82 writeln!(
83 printer.stderr(),
84 "Updated configuration file: {}",
85 file.simplified_display().cyan()
86 )?;
87 updated = true;
88 }
89 ConfigurationUpdate::Created => {
90 writeln!(
91 printer.stderr(),
92 "Created configuration file: {}",
93 file.simplified_display().cyan()
94 )?;
95 updated = true;
96 }
97 ConfigurationUpdate::Unchanged => {}
98 }
99 }
100
101 if updated {
102 writeln!(printer.stderr(), "Restart your shell to apply changes")?;
103 Ok(ExitStatus::Success)
104 } else {
105 Err(anyhow::anyhow!(
106 "The executable directory `{}` is not in PATH, but the {shell} configuration files are already up-to-date",
107 executable_directory.simplified_display().cyan()
108 ))
109 }
110}