Use relative paths for user display (#2559)

## Summary

This PR changes our user-facing representation for paths to use relative
paths, when the path is within the current working directory. This
mirrors what we do in Ruff. (If the path is _outside_ the current
working directory, we print an absolute path.)

Before:

```shell
❯ uv venv .venv2
Using Python 3.12.2 interpreter at: /Users/crmarsh/workspace/uv/.venv/bin/python3
Creating virtualenv at: .venv2
Activate with: source .venv2/bin/activate
```

After:

```shell
❯ cargo run venv .venv2
    Finished dev [unoptimized + debuginfo] target(s) in 0.15s
     Running `target/debug/uv venv .venv2`
Using Python 3.12.2 interpreter at: .venv/bin/python3
Creating virtualenv at: .venv2
Activate with: source .venv2/bin/activate
```

Note that we still want to use the existing `.simplified_display()`
anywhere that the path is being simplified, but _still_ intended for
machine consumption (e.g., when passing to `.current_dir()`).
This commit is contained in:
Charlie Marsh 2024-03-20 09:52:50 -04:00 committed by GitHub
parent 204b159cf4
commit 00fc44012c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
30 changed files with 149 additions and 183 deletions

View file

@ -1,17 +1,26 @@
use std::borrow::Cow;
use std::path::{Component, Path, PathBuf};
use once_cell::sync::Lazy;
pub static CWD: Lazy<PathBuf> = Lazy::new(|| std::env::current_dir().unwrap());
pub trait Simplified {
/// Simplify a [`Path`].
///
/// On Windows, this will strip the `\\?\` prefix from paths. On other platforms, it's a no-op.
fn simplified(&self) -> &Path;
/// Render a [`Path`] for user-facing display.
/// Render a [`Path`] for display.
///
/// On Windows, this will strip the `\\?\` prefix from paths. On other platforms, it's
/// equivalent to [`std::path::Display`].
fn simplified_display(&self) -> std::path::Display;
/// Render a [`Path`] for user-facing display.
///
/// Like [`simplified_display`], but relativizes the path against the current working directory.
fn user_display(&self) -> std::path::Display;
}
impl<T: AsRef<Path>> Simplified for T {
@ -22,6 +31,11 @@ impl<T: AsRef<Path>> Simplified for T {
fn simplified_display(&self) -> std::path::Display {
dunce::simplified(self.as_ref()).display()
}
fn user_display(&self) -> std::path::Display {
let path = dunce::simplified(self.as_ref());
path.strip_prefix(&*CWD).unwrap_or(path).display()
}
}
pub trait PythonExt {