|
2 | 2 |
|
3 | 3 | use crate::core::{TargetKind, Workspace};
|
4 | 4 | use crate::ops::CompileOptions;
|
5 |
| -use anyhow::Error; |
| 5 | +use crate::Config; |
| 6 | +use anyhow::{format_err, Error}; |
6 | 7 | use cargo_util::ProcessError;
|
| 8 | +use std::borrow::Cow; |
7 | 9 | use std::fmt;
|
8 |
| -use std::path::PathBuf; |
| 10 | +use std::path::{Path, PathBuf}; |
9 | 11 |
|
10 | 12 | pub type CargoResult<T> = anyhow::Result<T>;
|
11 | 13 |
|
@@ -345,3 +347,58 @@ impl From<std::io::Error> for CliError {
|
345 | 347 | pub fn internal<S: fmt::Display>(error: S) -> anyhow::Error {
|
346 | 348 | InternalError::new(anyhow::format_err!("{}", error)).into()
|
347 | 349 | }
|
| 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