Skip to content

Commit fe72b8b

Browse files
committed
Add OwnershipError converter.
This adds a function that will convert an OwnershipError to a message explaining to the user what happened and how to fix it. This will be shared by both the config validation and the manifest validation.
1 parent b2d8a44 commit fe72b8b

File tree

1 file changed

+59
-2
lines changed

1 file changed

+59
-2
lines changed

src/cargo/util/errors.rs

Lines changed: 59 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,12 @@
22

33
use crate::core::{TargetKind, Workspace};
44
use crate::ops::CompileOptions;
5-
use anyhow::Error;
5+
use crate::Config;
6+
use anyhow::{format_err, Error};
67
use cargo_util::ProcessError;
8+
use std::borrow::Cow;
79
use std::fmt;
8-
use std::path::PathBuf;
10+
use std::path::{Path, PathBuf};
911

1012
pub type CargoResult<T> = anyhow::Result<T>;
1113

@@ -345,3 +347,58 @@ impl From<std::io::Error> for CliError {
345347
pub fn internal<S: fmt::Display>(error: S) -> anyhow::Error {
346348
InternalError::new(anyhow::format_err!("{}", error)).into()
347349
}
350+
351+
/// Converts an `OwnershipError` into an `anyhow::Error` with a human-readable
352+
/// explanation of what to do.
353+
pub fn ownership_error(
354+
e: &cargo_util::paths::OwnershipError,
355+
what: &str,
356+
to_add: &Path,
357+
config: &Config,
358+
) -> anyhow::Error {
359+
let to_approve = if std::env::var_os("RUSTUP_TOOLCHAIN").is_some() {
360+
// FIXME: shell_escape doesn't handle powershell (and possibly other shells)
361+
let escaped = shell_escape::escape(Cow::Borrowed(to_add.to_str().expect("utf-8 path")));
362+
format!(
363+
"To approve this directory, run:\n\
364+
\n \
365+
rustup set safe-directories add {escaped}\n\
366+
\n\
367+
See https://rust-lang.github.io/rustup/safe-directories.html for more information.",
368+
)
369+
} else {
370+
let home = config.home().clone().into_path_unlocked();
371+
let home_config = if home.join("config").exists() {
372+
home.join("config")
373+
} else {
374+
home.join("config.toml")
375+
};
376+
format!(
377+
"To approve this directory, set the CARGO_SAFE_DIRECTORIES environment\n\
378+
variable to \"{}\" or edit\n\
379+
`{}` and add:\n\
380+
\n \
381+
[safe]\n \
382+
directories = [{}]\n\
383+
\n\
384+
See https://doc.rust-lang.org/nightly/cargo/reference/config.html#safedirectories\n\
385+
for more information.",
386+
to_add.display(),
387+
home_config.display(),
388+
toml_edit::easy::Value::String(to_add.to_str().expect("utf-8 path").to_string())
389+
)
390+
};
391+
format_err!(
392+
"`{}` is owned by a different user\n\
393+
For safety reasons, Cargo does not allow opening {what} by\n\
394+
a different user, unless explicitly approved.\n\
395+
\n\
396+
{to_approve}\n\
397+
\n\
398+
Current user: {}\n\
399+
Owner of file: {}",
400+
e.path.display(),
401+
e.current_user,
402+
e.owner
403+
)
404+
}

0 commit comments

Comments
 (0)