Skip to content

Commit d419903

Browse files
committed
Add uv python update-shell
1 parent 405ef66 commit d419903

File tree

7 files changed

+255
-7
lines changed

7 files changed

+255
-7
lines changed

crates/uv-cli/src/lib.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4856,6 +4856,19 @@ pub enum PythonCommand {
48564856

48574857
/// Uninstall Python versions.
48584858
Uninstall(PythonUninstallArgs),
4859+
4860+
/// Ensure that the Python executable directory is on the `PATH`.
4861+
///
4862+
/// If the Python executable directory is not present on the `PATH`, uv will attempt to add it to
4863+
/// the relevant shell configuration files.
4864+
///
4865+
/// If the shell configuration files already include a blurb to add the executable directory to
4866+
/// the path, but the directory is not present on the `PATH`, uv will exit with an error.
4867+
///
4868+
/// The Python executable directory is determined according to the XDG standard and can be
4869+
/// retrieved with `uv python dir --bin`.
4870+
#[command(alias = "ensurepath")]
4871+
UpdateShell,
48594872
}
48604873

48614874
#[derive(Args)]

crates/uv/src/commands/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ pub(crate) use python::install::install as python_install;
3838
pub(crate) use python::list::list as python_list;
3939
pub(crate) use python::pin::pin as python_pin;
4040
pub(crate) use python::uninstall::uninstall as python_uninstall;
41+
pub(crate) use python::update_shell::update_shell as python_update_shell;
4142
#[cfg(feature = "self-update")]
4243
pub(crate) use self_update::self_update;
4344
pub(crate) use tool::dir::dir as tool_dir;

crates/uv/src/commands/python/install.rs

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -908,20 +908,29 @@ fn warn_if_not_on_path(bin: &Path) {
908908
if !Shell::contains_path(bin) {
909909
if let Some(shell) = Shell::from_env() {
910910
if let Some(command) = shell.prepend_path(bin) {
911-
warn_user!(
912-
"`{}` is not on your PATH. To use the installed Python executable, run `{}`.",
913-
bin.simplified_display().cyan(),
914-
command.green(),
915-
);
911+
if shell.supports_update() {
912+
warn_user!(
913+
"`{}` is not on your PATH. To use installed Python executables, run `{}` or `{}`.",
914+
bin.simplified_display().cyan(),
915+
command.green(),
916+
"uv python update-shell".green()
917+
);
918+
} else {
919+
warn_user!(
920+
"`{}` is not on your PATH. To use installed Python executables, run `{}`.",
921+
bin.simplified_display().cyan(),
922+
command.green()
923+
);
924+
}
916925
} else {
917926
warn_user!(
918-
"`{}` is not on your PATH. To use the installed Python executable, add the directory to your PATH.",
927+
"`{}` is not on your PATH. To use installed Python executables, add the directory to your PATH.",
919928
bin.simplified_display().cyan(),
920929
);
921930
}
922931
} else {
923932
warn_user!(
924-
"`{}` is not on your PATH. To use the installed Python executable, add the directory to your PATH.",
933+
"`{}` is not on your PATH. To use installed Python executables, add the directory to your PATH.",
925934
bin.simplified_display().cyan(),
926935
);
927936
}

crates/uv/src/commands/python/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ pub(crate) mod install;
44
pub(crate) mod list;
55
pub(crate) mod pin;
66
pub(crate) mod uninstall;
7+
pub(crate) mod update_shell;
78

89
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
910
pub(super) enum ChangeEventKind {
Lines changed: 153 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,153 @@
1+
#![cfg_attr(windows, allow(unreachable_code))]
2+
3+
use std::fmt::Write;
4+
5+
use anyhow::Result;
6+
use owo_colors::OwoColorize;
7+
use tokio::io::AsyncWriteExt;
8+
use tracing::debug;
9+
10+
use uv_fs::Simplified;
11+
use uv_python::managed::python_executable_dir;
12+
use uv_shell::Shell;
13+
14+
use crate::commands::ExitStatus;
15+
use crate::printer::Printer;
16+
17+
/// Ensure that the executable directory is in PATH.
18+
pub(crate) async fn update_shell(printer: Printer) -> Result<ExitStatus> {
19+
let executable_directory = python_executable_dir()?;
20+
debug!(
21+
"Ensuring that the executable directory is in PATH: {}",
22+
executable_directory.simplified_display()
23+
);
24+
25+
#[cfg(windows)]
26+
{
27+
if uv_shell::windows::prepend_path(&executable_directory)? {
28+
writeln!(
29+
printer.stderr(),
30+
"Updated PATH to include executable directory {}",
31+
executable_directory.simplified_display().cyan()
32+
)?;
33+
writeln!(printer.stderr(), "Restart your shell to apply changes")?;
34+
} else {
35+
writeln!(
36+
printer.stderr(),
37+
"Executable directory {} is already in PATH",
38+
executable_directory.simplified_display().cyan()
39+
)?;
40+
}
41+
42+
return Ok(ExitStatus::Success);
43+
}
44+
45+
if Shell::contains_path(&executable_directory) {
46+
writeln!(
47+
printer.stderr(),
48+
"Executable directory {} is already in PATH",
49+
executable_directory.simplified_display().cyan()
50+
)?;
51+
return Ok(ExitStatus::Success);
52+
}
53+
54+
// Determine the current shell.
55+
let Some(shell) = Shell::from_env() else {
56+
return Err(anyhow::anyhow!(
57+
"The executable directory {} is not in PATH, but the current shell could not be determined",
58+
executable_directory.simplified_display().cyan()
59+
));
60+
};
61+
62+
// Look up the configuration files (e.g., `.bashrc`, `.zshrc`) for the shell.
63+
let files = shell.configuration_files();
64+
if files.is_empty() {
65+
return Err(anyhow::anyhow!(
66+
"The executable directory {} is not in PATH, but updating {shell} is currently unsupported",
67+
executable_directory.simplified_display().cyan()
68+
));
69+
}
70+
71+
// Prepare the command (e.g., `export PATH="$HOME/.cargo/bin:$PATH"`).
72+
let Some(command) = shell.prepend_path(&executable_directory) else {
73+
return Err(anyhow::anyhow!(
74+
"The executable directory {} is not in PATH, but the necessary command to update {shell} could not be determined",
75+
executable_directory.simplified_display().cyan()
76+
));
77+
};
78+
79+
// Update each file, as necessary.
80+
let mut updated = false;
81+
for file in files {
82+
// Search for the command in the file, to avoid redundant updates.
83+
match fs_err::tokio::read_to_string(&file).await {
84+
Ok(contents) => {
85+
if contents
86+
.lines()
87+
.map(str::trim)
88+
.filter(|line| !line.starts_with('#'))
89+
.any(|line| line.contains(&command))
90+
{
91+
debug!(
92+
"Skipping already-updated configuration file: {}",
93+
file.simplified_display()
94+
);
95+
continue;
96+
}
97+
98+
// Append the command to the file.
99+
fs_err::tokio::OpenOptions::new()
100+
.create(true)
101+
.truncate(true)
102+
.write(true)
103+
.open(&file)
104+
.await?
105+
.write_all(format!("{contents}\n# uv\n{command}\n").as_bytes())
106+
.await?;
107+
108+
writeln!(
109+
printer.stderr(),
110+
"Updated configuration file: {}",
111+
file.simplified_display().cyan()
112+
)?;
113+
updated = true;
114+
}
115+
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
116+
// Ensure that the directory containing the file exists.
117+
if let Some(parent) = file.parent() {
118+
fs_err::tokio::create_dir_all(&parent).await?;
119+
}
120+
121+
// Append the command to the file.
122+
fs_err::tokio::OpenOptions::new()
123+
.create(true)
124+
.truncate(true)
125+
.write(true)
126+
.open(&file)
127+
.await?
128+
.write_all(format!("# uv\n{command}\n").as_bytes())
129+
.await?;
130+
131+
writeln!(
132+
printer.stderr(),
133+
"Created configuration file: {}",
134+
file.simplified_display().cyan()
135+
)?;
136+
updated = true;
137+
}
138+
Err(err) => {
139+
return Err(err.into());
140+
}
141+
}
142+
}
143+
144+
if updated {
145+
writeln!(printer.stderr(), "Restart your shell to apply changes")?;
146+
Ok(ExitStatus::Success)
147+
} else {
148+
Err(anyhow::anyhow!(
149+
"The executable directory {} is not in PATH, but the {shell} configuration files are already up-to-date",
150+
executable_directory.simplified_display().cyan()
151+
))
152+
}
153+
}

crates/uv/src/lib.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1533,6 +1533,12 @@ async fn run(mut cli: Cli) -> Result<ExitStatus> {
15331533
commands::python_dir(args.bin)?;
15341534
Ok(ExitStatus::Success)
15351535
}
1536+
Commands::Python(PythonNamespace {
1537+
command: PythonCommand::UpdateShell,
1538+
}) => {
1539+
commands::python_update_shell(printer).await?;
1540+
Ok(ExitStatus::Success)
1541+
}
15361542
Commands::Publish(args) => {
15371543
show_settings!(args);
15381544

docs/reference/cli.md

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2633,6 +2633,7 @@ uv python [OPTIONS] <COMMAND>
26332633
<dt><a href="#uv-python-pin"><code>uv python pin</code></a></dt><dd><p>Pin to a specific Python version</p></dd>
26342634
<dt><a href="#uv-python-dir"><code>uv python dir</code></a></dt><dd><p>Show the uv Python installation directory</p></dd>
26352635
<dt><a href="#uv-python-uninstall"><code>uv python uninstall</code></a></dt><dd><p>Uninstall Python versions</p></dd>
2636+
<dt><a href="#uv-python-update-shell"><code>uv python update-shell</code></a></dt><dd><p>Ensure that the Python executable directory is on the <code>PATH</code></p></dd>
26362637
</dl>
26372638

26382639
### uv python list
@@ -3204,6 +3205,70 @@ uv python uninstall [OPTIONS] <TARGETS>...
32043205
<p>You can configure fine-grained logging using the <code>RUST_LOG</code> environment variable. (<a href="https://docs.rs/tracing-subscriber/latest/tracing_subscriber/filter/struct.EnvFilter.html#directives">https://docs.rs/tracing-subscriber/latest/tracing_subscriber/filter/struct.EnvFilter.html#directives</a>)</p>
32053206
</dd></dl>
32063207

3208+
### uv python update-shell
3209+
3210+
Ensure that the Python executable directory is on the `PATH`.
3211+
3212+
If the Python executable directory is not present on the `PATH`, uv will attempt to add it to the relevant shell configuration files.
3213+
3214+
If the shell configuration files already include a blurb to add the executable directory to the path, but the directory is not present on the `PATH`, uv will exit with an error.
3215+
3216+
The Python executable directory is determined according to the XDG standard and can be retrieved with `uv python dir --bin`.
3217+
3218+
<h3 class="cli-reference">Usage</h3>
3219+
3220+
```
3221+
uv python update-shell [OPTIONS]
3222+
```
3223+
3224+
<h3 class="cli-reference">Options</h3>
3225+
3226+
<dl class="cli-reference"><dt id="uv-python-update-shell--allow-insecure-host"><a href="#uv-python-update-shell--allow-insecure-host"><code>--allow-insecure-host</code></a>, <code>--trusted-host</code> <i>allow-insecure-host</i></dt><dd><p>Allow insecure connections to a host.</p>
3227+
<p>Can be provided multiple times.</p>
3228+
<p>Expects to receive either a hostname (e.g., <code>localhost</code>), a host-port pair (e.g., <code>localhost:8080</code>), or a URL (e.g., <code>https://localhost</code>).</p>
3229+
<p>WARNING: Hosts included in this list will not be verified against the system's certificate store. Only use <code>--allow-insecure-host</code> in a secure network with verified sources, as it bypasses SSL verification and could expose you to MITM attacks.</p>
3230+
<p>May also be set with the <code>UV_INSECURE_HOST</code> environment variable.</p></dd><dt id="uv-python-update-shell--cache-dir"><a href="#uv-python-update-shell--cache-dir"><code>--cache-dir</code></a> <i>cache-dir</i></dt><dd><p>Path to the cache directory.</p>
3231+
<p>Defaults to <code>$XDG_CACHE_HOME/uv</code> or <code>$HOME/.cache/uv</code> on macOS and Linux, and <code>%LOCALAPPDATA%\uv\cache</code> on Windows.</p>
3232+
<p>To view the location of the cache directory, run <code>uv cache dir</code>.</p>
3233+
<p>May also be set with the <code>UV_CACHE_DIR</code> environment variable.</p></dd><dt id="uv-python-update-shell--color"><a href="#uv-python-update-shell--color"><code>--color</code></a> <i>color-choice</i></dt><dd><p>Control the use of color in output.</p>
3234+
<p>By default, uv will automatically detect support for colors when writing to a terminal.</p>
3235+
<p>Possible values:</p>
3236+
<ul>
3237+
<li><code>auto</code>: Enables colored output only when the output is going to a terminal or TTY with support</li>
3238+
<li><code>always</code>: Enables colored output regardless of the detected environment</li>
3239+
<li><code>never</code>: Disables colored output</li>
3240+
</ul></dd><dt id="uv-python-update-shell--config-file"><a href="#uv-python-update-shell--config-file"><code>--config-file</code></a> <i>config-file</i></dt><dd><p>The path to a <code>uv.toml</code> file to use for configuration.</p>
3241+
<p>While uv configuration can be included in a <code>pyproject.toml</code> file, it is not allowed in this context.</p>
3242+
<p>May also be set with the <code>UV_CONFIG_FILE</code> environment variable.</p></dd><dt id="uv-python-update-shell--directory"><a href="#uv-python-update-shell--directory"><code>--directory</code></a> <i>directory</i></dt><dd><p>Change to the given directory prior to running the command.</p>
3243+
<p>Relative paths are resolved with the given directory as the base.</p>
3244+
<p>See <code>--project</code> to only change the project root directory.</p>
3245+
</dd><dt id="uv-python-update-shell--help"><a href="#uv-python-update-shell--help"><code>--help</code></a>, <code>-h</code></dt><dd><p>Display the concise help for this command</p>
3246+
</dd><dt id="uv-python-update-shell--managed-python"><a href="#uv-python-update-shell--managed-python"><code>--managed-python</code></a></dt><dd><p>Require use of uv-managed Python versions.</p>
3247+
<p>By default, uv prefers using Python versions it manages. However, it will use system Python versions if a uv-managed Python is not installed. This option disables use of system Python versions.</p>
3248+
<p>May also be set with the <code>UV_MANAGED_PYTHON</code> environment variable.</p></dd><dt id="uv-python-update-shell--native-tls"><a href="#uv-python-update-shell--native-tls"><code>--native-tls</code></a></dt><dd><p>Whether to load TLS certificates from the platform's native certificate store.</p>
3249+
<p>By default, uv loads certificates from the bundled <code>webpki-roots</code> crate. The <code>webpki-roots</code> are a reliable set of trust roots from Mozilla, and including them in uv improves portability and performance (especially on macOS).</p>
3250+
<p>However, in some cases, you may want to use the platform's native certificate store, especially if you're relying on a corporate trust root (e.g., for a mandatory proxy) that's included in your system's certificate store.</p>
3251+
<p>May also be set with the <code>UV_NATIVE_TLS</code> environment variable.</p></dd><dt id="uv-python-update-shell--no-cache"><a href="#uv-python-update-shell--no-cache"><code>--no-cache</code></a>, <code>--no-cache-dir</code>, <code>-n</code></dt><dd><p>Avoid reading from or writing to the cache, instead using a temporary directory for the duration of the operation</p>
3252+
<p>May also be set with the <code>UV_NO_CACHE</code> environment variable.</p></dd><dt id="uv-python-update-shell--no-config"><a href="#uv-python-update-shell--no-config"><code>--no-config</code></a></dt><dd><p>Avoid discovering configuration files (<code>pyproject.toml</code>, <code>uv.toml</code>).</p>
3253+
<p>Normally, configuration files are discovered in the current directory, parent directories, or user configuration directories.</p>
3254+
<p>May also be set with the <code>UV_NO_CONFIG</code> environment variable.</p></dd><dt id="uv-python-update-shell--no-managed-python"><a href="#uv-python-update-shell--no-managed-python"><code>--no-managed-python</code></a></dt><dd><p>Disable use of uv-managed Python versions.</p>
3255+
<p>Instead, uv will search for a suitable Python version on the system.</p>
3256+
<p>May also be set with the <code>UV_NO_MANAGED_PYTHON</code> environment variable.</p></dd><dt id="uv-python-update-shell--no-progress"><a href="#uv-python-update-shell--no-progress"><code>--no-progress</code></a></dt><dd><p>Hide all progress outputs.</p>
3257+
<p>For example, spinners or progress bars.</p>
3258+
<p>May also be set with the <code>UV_NO_PROGRESS</code> environment variable.</p></dd><dt id="uv-python-update-shell--no-python-downloads"><a href="#uv-python-update-shell--no-python-downloads"><code>--no-python-downloads</code></a></dt><dd><p>Disable automatic downloads of Python.</p>
3259+
</dd><dt id="uv-python-update-shell--offline"><a href="#uv-python-update-shell--offline"><code>--offline</code></a></dt><dd><p>Disable network access.</p>
3260+
<p>When disabled, uv will only use locally cached data and locally available files.</p>
3261+
<p>May also be set with the <code>UV_OFFLINE</code> environment variable.</p></dd><dt id="uv-python-update-shell--project"><a href="#uv-python-update-shell--project"><code>--project</code></a> <i>project</i></dt><dd><p>Run the command within the given project directory.</p>
3262+
<p>All <code>pyproject.toml</code>, <code>uv.toml</code>, and <code>.python-version</code> files will be discovered by walking up the directory tree from the project root, as will the project's virtual environment (<code>.venv</code>).</p>
3263+
<p>Other command-line arguments (such as relative paths) will be resolved relative to the current working directory.</p>
3264+
<p>See <code>--directory</code> to change the working directory entirely.</p>
3265+
<p>This setting has no effect when used in the <code>uv pip</code> interface.</p>
3266+
<p>May also be set with the <code>UV_PROJECT</code> environment variable.</p></dd><dt id="uv-python-update-shell--quiet"><a href="#uv-python-update-shell--quiet"><code>--quiet</code></a>, <code>-q</code></dt><dd><p>Use quiet output.</p>
3267+
<p>Repeating this option, e.g., <code>-qq</code>, will enable a silent mode in which uv will write no output to stdout.</p>
3268+
</dd><dt id="uv-python-update-shell--verbose"><a href="#uv-python-update-shell--verbose"><code>--verbose</code></a>, <code>-v</code></dt><dd><p>Use verbose output.</p>
3269+
<p>You can configure fine-grained logging using the <code>RUST_LOG</code> environment variable. (<a href="https://docs.rs/tracing-subscriber/latest/tracing_subscriber/filter/struct.EnvFilter.html#directives">https://docs.rs/tracing-subscriber/latest/tracing_subscriber/filter/struct.EnvFilter.html#directives</a>)</p>
3270+
</dd></dl>
3271+
32073272
## uv pip
32083273

32093274
Manage Python packages with a pip-compatible interface

0 commit comments

Comments
 (0)