Enable global configuration files (#3049)

## Summary

Enables `uv` to read configuration from (e.g.)
`/Users/crmarsh/.config/uv/uv.toml` on macOS and Linux, and
`C:\Users\Charlie\AppData\Roaming\uv\uv.toml` on Windows.

This differs slightly from Ruff, which uses the `Application Support`
directory on macOS. But I've deviated here. based on the preferences
expressed in https://github.com/astral-sh/ruff/issues/10739.
This commit is contained in:
Charlie Marsh 2024-04-17 13:59:50 -04:00 committed by GitHub
parent c6e75f8b35
commit dfccdb0e39
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 44 additions and 2 deletions

View file

@ -15,6 +15,19 @@ pub struct Workspace {
}
impl Workspace {
/// Load the user [`Workspace`].
pub fn user() -> Result<Option<Self>, WorkspaceError> {
let Some(dir) = config_dir() else {
return Ok(None);
};
let root = dir.join("uv");
let file = root.join("uv.toml");
Ok(Some(Self {
options: find_in_directory(&file)?.unwrap_or_default(),
root,
}))
}
/// Find the [`Workspace`] for the given path.
///
/// The search starts at the given path and goes up the directory tree until a workspace is
@ -53,6 +66,27 @@ impl Workspace {
}
}
/// Returns the path to the user configuration directory.
///
/// This is similar to the `config_dir()` returned by the `dirs` crate, but it uses the
/// `XDG_CONFIG_HOME` environment variable on both Linux _and_ macOS, rather than the
/// `Application Support` directory on macOS.
fn config_dir() -> Option<PathBuf> {
// On Windows, use, e.g., C:\Users\Alice\AppData\Roaming
#[cfg(windows)]
{
dirs_sys::known_folder_roaming_app_data()
}
// On Linux and macOS, use, e.g., /home/alice/.config.
#[cfg(not(windows))]
{
std::env::var_os("XDG_CONFIG_HOME")
.and_then(dirs_sys::is_absolute_path)
.or_else(|| dirs_sys::home_dir().map(|path| path.join(".config")))
}
}
/// Read a `uv.toml` or `pyproject.toml` file in the given directory.
fn find_in_directory(dir: &Path) -> Result<Option<Options>, WorkspaceError> {
// Read a `uv.toml` file in the current directory.