Skip to main content

uv_tool/
lib.rs

1use std::io::{self, Write};
2use std::path::{Path, PathBuf};
3use std::str::FromStr;
4
5use fs_err as fs;
6use fs_err::File;
7use owo_colors::OwoColorize;
8use thiserror::Error;
9use tracing::{debug, warn};
10
11use uv_cache::Cache;
12use uv_dirs::user_executable_directory;
13use uv_fs::{LockedFile, LockedFileError, LockedFileMode, Simplified};
14use uv_install_wheel::read_record;
15use uv_installer::SitePackages;
16use uv_normalize::PackageName;
17use uv_pep440::Version;
18use uv_python_interpreter::{BrokenLink, Interpreter, PythonEnvironment};
19use uv_state::{StateBucket, StateStore};
20use uv_static::EnvVars;
21use uv_virtualenv::UpgradePolicy;
22use uv_warnings::warn_user;
23
24pub(crate) use receipt::ToolReceipt;
25pub use tool::{Tool, ToolEntrypoint};
26
27mod receipt;
28mod tool;
29
30/// A wrapper around [`PythonEnvironment`] for tools that provides additional functionality.
31#[derive(Debug, Clone)]
32pub struct ToolEnvironment {
33    environment: PythonEnvironment,
34    name: PackageName,
35}
36
37impl ToolEnvironment {
38    fn new(environment: PythonEnvironment, name: PackageName) -> Self {
39        Self { environment, name }
40    }
41
42    /// Return the [`Version`] of the tool package in this environment.
43    pub fn version(&self) -> Result<Version, Error> {
44        let site_packages = SitePackages::from_environment(&self.environment).map_err(|err| {
45            Error::EnvironmentRead(self.environment.root().to_path_buf(), err.to_string())
46        })?;
47        let packages = site_packages.get_packages(&self.name);
48        let package = packages
49            .first()
50            .ok_or_else(|| Error::MissingToolPackage(self.name.clone()))?;
51        Ok(package.version().clone())
52    }
53
54    /// Get the underlying [`PythonEnvironment`].
55    pub fn into_environment(self) -> PythonEnvironment {
56        self.environment
57    }
58
59    /// Get a reference to the underlying [`PythonEnvironment`].
60    pub fn environment(&self) -> &PythonEnvironment {
61        &self.environment
62    }
63}
64
65#[derive(Error, Debug)]
66pub enum Error {
67    #[error(transparent)]
68    Io(#[from] io::Error),
69    #[error(transparent)]
70    LockedFile(#[from] LockedFileError),
71    #[error("Failed to update `uv-receipt.toml` at `{0}`")]
72    ReceiptWrite(PathBuf, #[source] Box<toml_edit::ser::Error>),
73    #[error("Failed to read `uv-receipt.toml` at `{0}`")]
74    ReceiptRead(PathBuf, #[source] Box<toml::de::Error>),
75    #[error(transparent)]
76    VirtualEnvError(#[from] uv_virtualenv::Error),
77    #[error("Failed to read package entry points {0}")]
78    EntrypointRead(#[from] uv_install_wheel::Error),
79    #[error("Failed to find a directory to install executables into")]
80    NoExecutableDirectory,
81    #[error(transparent)]
82    EnvironmentError(#[from] uv_python_interpreter::PythonEnvironmentError),
83    #[error("Failed to find a receipt for tool `{0}` at `{1}`")]
84    MissingToolReceipt(String, PathBuf),
85    #[error("Failed to read tool environment packages at `{0}`: {1}")]
86    EnvironmentRead(PathBuf, String),
87    #[error("Failed find package `{0}` in tool environment")]
88    MissingToolPackage(PackageName),
89    #[error("Tool `{0}` environment not found at `{1}`")]
90    ToolEnvironmentNotFound(PackageName, PathBuf),
91}
92
93impl Error {
94    pub fn as_io_error(&self) -> Option<&io::Error> {
95        match self {
96            Self::Io(err) => Some(err),
97            Self::LockedFile(err) => err.as_io_error(),
98            Self::VirtualEnvError(uv_virtualenv::Error::Io(err)) => Some(err),
99            Self::ReceiptWrite(_, _)
100            | Self::ReceiptRead(_, _)
101            | Self::VirtualEnvError(_)
102            | Self::EntrypointRead(_)
103            | Self::NoExecutableDirectory
104            | Self::EnvironmentError(_)
105            | Self::MissingToolReceipt(_, _)
106            | Self::EnvironmentRead(_, _)
107            | Self::MissingToolPackage(_)
108            | Self::ToolEnvironmentNotFound(_, _) => None,
109        }
110    }
111}
112
113/// A collection of uv-managed tools installed on the current system.
114#[derive(Debug, Clone)]
115pub struct InstalledTools {
116    /// The path to the top-level directory of the tools.
117    root: PathBuf,
118}
119
120impl InstalledTools {
121    /// A directory for tools at `root`.
122    fn from_path(root: impl Into<PathBuf>) -> Self {
123        Self { root: root.into() }
124    }
125
126    /// Create a new [`InstalledTools`] from settings.
127    ///
128    /// Prefer, in order:
129    ///
130    /// 1. The specific tool directory specified by the user, i.e., `UV_TOOL_DIR`
131    /// 2. A directory in the system-appropriate user-level data directory, e.g., `~/.local/uv/tools`
132    /// 3. A directory in the local data directory, e.g., `./.uv/tools`
133    pub fn from_settings() -> Result<Self, Error> {
134        if let Some(tool_dir) = std::env::var_os(EnvVars::UV_TOOL_DIR).filter(|s| !s.is_empty()) {
135            Ok(Self::from_path(std::path::absolute(tool_dir)?))
136        } else {
137            Ok(Self::from_path(
138                StateStore::from_settings(None)?.bucket(StateBucket::Tools),
139            ))
140        }
141    }
142
143    /// Return the expected directory for a tool with the given [`PackageName`].
144    pub fn tool_dir(&self, name: &PackageName) -> PathBuf {
145        self.root.join(name.to_string())
146    }
147
148    /// Return the metadata for all installed tools.
149    ///
150    /// Directories with invalid package names are skipped with a warning.
151    ///
152    /// If a tool is present, but is missing a receipt or the receipt is invalid, the tool will be
153    /// included with an error.
154    ///
155    /// Note it is generally incorrect to use this without [`Self::acquire_lock`].
156    #[expect(clippy::type_complexity)]
157    pub fn tools(&self) -> Result<Vec<(PackageName, Result<Tool, Error>)>, Error> {
158        let mut tools = Vec::new();
159        for directory in uv_fs::directories(self.root())? {
160            let Some(name) = directory
161                .file_name()
162                .and_then(|file_name| file_name.to_str())
163            else {
164                continue;
165            };
166            let Ok(name) = PackageName::from_str(name) else {
167                warn_user!(
168                    "Ignoring tool directory `{}` with an invalid package name; move it outside the tool directory, or remove it if no longer needed",
169                    directory.user_display()
170                );
171                continue;
172            };
173            let path = directory.join("uv-receipt.toml");
174            let contents = match fs_err::read_to_string(&path) {
175                Ok(contents) => contents,
176                Err(err) if err.kind() == io::ErrorKind::NotFound => {
177                    let err = Error::MissingToolReceipt(name.to_string(), path);
178                    tools.push((name, Err(err)));
179                    continue;
180                }
181                Err(err) => return Err(err.into()),
182            };
183            match ToolReceipt::from_string(contents) {
184                Ok(tool_receipt) => tools.push((name, Ok(tool_receipt.tool))),
185                Err(err) => {
186                    let err = Error::ReceiptRead(path, Box::new(err));
187                    tools.push((name, Err(err)));
188                }
189            }
190        }
191        Ok(tools)
192    }
193
194    /// Get the receipt for the given tool.
195    ///
196    /// If the tool is not installed, returns `Ok(None)`. If the receipt is invalid, returns an
197    /// error.
198    ///
199    /// Note it is generally incorrect to use this without [`Self::acquire_lock`].
200    pub fn get_tool_receipt(&self, name: &PackageName) -> Result<Option<Tool>, Error> {
201        let path = self.tool_dir(name).join("uv-receipt.toml");
202        match ToolReceipt::from_path(&path) {
203            Ok(tool_receipt) => Ok(Some(tool_receipt.tool)),
204            Err(Error::Io(err)) if err.kind() == io::ErrorKind::NotFound => Ok(None),
205            Err(err) => Err(err),
206        }
207    }
208
209    /// Grab a file lock for the tools directory to prevent concurrent access across processes.
210    pub async fn lock(&self) -> Result<LockedFile, Error> {
211        Ok(LockedFile::acquire(
212            self.root.join(".lock"),
213            LockedFileMode::Exclusive,
214            self.root.user_display(),
215        )
216        .await?)
217    }
218
219    /// Add a receipt for a tool.
220    ///
221    /// Any existing receipt will be replaced.
222    ///
223    /// Note it is generally incorrect to use this without [`Self::acquire_lock`].
224    pub fn add_tool_receipt(&self, name: &PackageName, tool: Tool) -> Result<(), Error> {
225        let tool_receipt = ToolReceipt::from(tool);
226        let path = self.tool_dir(name).join("uv-receipt.toml");
227
228        debug!(
229            "Adding metadata entry for tool `{name}` at `{}`",
230            path.user_display()
231        );
232
233        let doc = tool_receipt
234            .to_toml()
235            .map_err(|err| Error::ReceiptWrite(path.clone(), Box::new(err)))?;
236
237        // Save the modified `uv-receipt.toml`.
238        fs_err::write(&path, doc)?;
239
240        Ok(())
241    }
242
243    /// Remove the environment for a tool.
244    ///
245    /// Does not remove the tool's entrypoints.
246    ///
247    /// Note it is generally incorrect to use this without [`Self::acquire_lock`].
248    ///
249    /// # Errors
250    ///
251    /// If no such environment exists for the tool.
252    pub fn remove_environment(&self, name: &PackageName) -> Result<(), Error> {
253        let environment_path = self.tool_dir(name);
254
255        debug!(
256            "Deleting environment for tool `{name}` at `{}`",
257            environment_path.user_display()
258        );
259
260        uv_fs::remove_virtualenv(environment_path.as_path()).map_err(uv_virtualenv::Error::from)?;
261
262        Ok(())
263    }
264
265    /// Return the [`PythonEnvironment`] for a given tool, if it exists.
266    ///
267    /// Returns `Ok(None)` if the environment does not exist or is linked to a non-existent
268    /// interpreter.
269    ///
270    /// Note it is generally incorrect to use this without [`Self::acquire_lock`].
271    pub fn get_environment(
272        &self,
273        name: &PackageName,
274        cache: &Cache,
275    ) -> Result<Option<ToolEnvironment>, Error> {
276        let environment_path = self.tool_dir(name);
277
278        match PythonEnvironment::from_root(&environment_path, cache) {
279            Ok(venv) => {
280                debug!(
281                    "Found existing environment for tool `{name}`: {}",
282                    environment_path.user_display()
283                );
284                Ok(Some(ToolEnvironment::new(venv, name.clone())))
285            }
286            Err(uv_python_interpreter::PythonEnvironmentError::MissingEnvironment(_)) => Ok(None),
287            Err(uv_python_interpreter::PythonEnvironmentError::Query(
288                uv_python_interpreter::InterpreterError::NotFound(interpreter_path),
289            )) => {
290                warn!(
291                    "Ignoring existing virtual environment with missing Python interpreter: {}",
292                    interpreter_path.user_display()
293                );
294
295                Ok(None)
296            }
297            Err(uv_python_interpreter::PythonEnvironmentError::Query(
298                uv_python_interpreter::InterpreterError::BrokenLink(BrokenLink {
299                    path,
300                    unix,
301                    venv: _,
302                }),
303            )) => {
304                if unix {
305                    let target_path = fs_err::read_link(&path)?;
306                    warn!(
307                        "Ignoring existing virtual environment linked to non-existent Python interpreter: `{}` -> `{}`",
308                        path.user_display().cyan(),
309                        target_path.user_display().cyan(),
310                    );
311                } else {
312                    warn!(
313                        "Ignoring existing virtual environment linked to non-existent Python interpreter: {}",
314                        path.user_display().cyan(),
315                    );
316                }
317
318                Ok(None)
319            }
320            Err(err) => Err(err.into()),
321        }
322    }
323
324    /// Create the [`PythonEnvironment`] for a given tool, removing any existing environments.
325    ///
326    /// Note it is generally incorrect to use this without [`Self::acquire_lock`].
327    pub fn create_environment(
328        &self,
329        name: &PackageName,
330        interpreter: Interpreter,
331        cache: &Cache,
332    ) -> Result<PythonEnvironment, Error> {
333        let environment_path = self.tool_dir(name);
334
335        // Remove any existing environment.
336        match uv_fs::remove_virtualenv(&environment_path) {
337            Ok(()) => {
338                debug!(
339                    "Removed existing environment for tool `{name}`: {}",
340                    environment_path.user_display()
341                );
342            }
343            Err(err) if err.kind() == io::ErrorKind::NotFound => (),
344            Err(err) => return Err(uv_virtualenv::Error::from(err).into()),
345        }
346
347        debug!(
348            "Creating environment for tool `{name}`: {}",
349            environment_path.user_display()
350        );
351
352        // Create a virtual environment.
353        let venv = uv_virtualenv::create_venv(
354            &environment_path,
355            interpreter,
356            uv_virtualenv::Prompt::None,
357            false,
358            uv_virtualenv::OnExisting::Remove(uv_virtualenv::RemovalReason::ManagedEnvironment),
359            false,
360            uv_virtualenv::Seed::Disabled,
361            UpgradePolicy::Fixed,
362        )?;
363        venv.cache_virtualenv(false, cache)?;
364
365        Ok(venv)
366    }
367
368    /// Initialize the tools directory.
369    ///
370    /// Ensures the directory is created.
371    pub fn init(self) -> Result<Self, Error> {
372        let root = &self.root;
373
374        // Create the tools directory, if it doesn't exist.
375        fs::create_dir_all(root)?;
376
377        // Add a .gitignore.
378        match fs::OpenOptions::new()
379            .write(true)
380            .create_new(true)
381            .open(root.join(".gitignore"))
382        {
383            Ok(mut file) => file.write_all(b"*")?,
384            Err(err) if err.kind() == io::ErrorKind::AlreadyExists => (),
385            Err(err) => return Err(err.into()),
386        }
387
388        Ok(self)
389    }
390
391    /// Return the path of the tools directory.
392    pub fn root(&self) -> &Path {
393        &self.root
394    }
395}
396
397/// Find the tool executable directory.
398pub fn tool_executable_dir() -> Result<PathBuf, Error> {
399    user_executable_directory(Some(EnvVars::UV_TOOL_BIN_DIR)).ok_or(Error::NoExecutableDirectory)
400}
401
402/// Find the `.dist-info` directory for a package in an environment.
403fn find_dist_info<'a>(
404    site_packages: &'a SitePackages,
405    package_name: &PackageName,
406    package_version: &Version,
407) -> Result<&'a Path, Error> {
408    site_packages
409        .get_packages(package_name)
410        .iter()
411        .find(|package| package.version() == package_version)
412        .map(|dist| dist.install_path())
413        .ok_or_else(|| Error::MissingToolPackage(package_name.clone()))
414}
415
416/// Find the paths to the entry points provided by a package in an environment.
417///
418/// Entry points can either be true Python entrypoints (defined in `entrypoints.txt`) or scripts in
419/// the `.data` directory.
420///
421/// Returns a list of `(name, path)` tuples.
422pub fn entrypoint_paths(
423    site_packages: &SitePackages,
424    package_name: &PackageName,
425    package_version: &Version,
426) -> Result<Vec<(String, PathBuf)>, Error> {
427    // Find the `.dist-info` directory in the installed environment.
428    let dist_info_path = find_dist_info(site_packages, package_name, package_version)?;
429    debug!(
430        "Looking at `.dist-info` at: {}",
431        dist_info_path.user_display()
432    );
433
434    // Read the RECORD file.
435    let record = read_record(File::open(dist_info_path.join("RECORD"))?)?;
436
437    // The RECORD file uses relative paths, so we're looking for the relative path to be a prefix.
438    let layout = site_packages.interpreter().layout();
439    let script_relative = pathdiff::diff_paths(&layout.scheme.scripts, &layout.scheme.purelib)
440        .ok_or_else(|| {
441            io::Error::other(format!(
442                "Could not find relative path for: {}",
443                layout.scheme.scripts.simplified_display()
444            ))
445        })?;
446
447    // Identify any installed binaries (both entrypoints and scripts from the `.data` directory).
448    let mut entrypoints = vec![];
449    for entry in record {
450        let relative_path = PathBuf::from(&entry.path);
451        let Ok(path_in_scripts) = relative_path.strip_prefix(&script_relative) else {
452            continue;
453        };
454
455        let absolute_path = layout.scheme.scripts.join(path_in_scripts);
456        let script_name = relative_path
457            .file_name()
458            .and_then(|filename| filename.to_str())
459            .map(ToString::to_string)
460            .unwrap_or(entry.path);
461        entrypoints.push((script_name, absolute_path));
462    }
463
464    Ok(entrypoints)
465}