Move paths to cargo-util.

This commit is contained in:
Eric Huss 2021-03-20 13:43:33 -07:00
parent dbfdd49559
commit 1dae5acb7d
44 changed files with 250 additions and 188 deletions

View file

@ -51,7 +51,6 @@ num_cpus = "1.0"
opener = "0.4"
percent-encoding = "2.0"
rustfix = "0.5.0"
same-file = "1"
semver = { version = "0.10", features = ["serde"] }
serde = { version = "1.0.123", features = ["derive"] }
serde_ignored = "0.1.0"
@ -75,9 +74,6 @@ im-rc = "15.0.0"
rustc-workspace-hack = "1.0.0"
rand = "0.8.3"
[target.'cfg(target_os = "macos")'.dependencies]
core-foundation = { version = "0.9.0", features = ["mac_os_10_7_support"] }
[target.'cfg(windows)'.dependencies]
fwdansi = "1.1.0"

View file

@ -9,11 +9,19 @@ repository = "https://github.com/rust-lang/cargo"
description = "Miscellaneous support code used by Cargo."
[dependencies]
anyhow = "1.0"
anyhow = "1.0.34"
filetime = "0.2.9"
jobserver = "0.1.21"
libc = "0.2"
libc = "0.2.88"
log = "0.4.6"
same-file = "1.0.6"
shell-escape = "0.1.4"
tempfile = "3.1.0"
walkdir = "2.3.1"
[target.'cfg(target_os = "macos")'.dependencies]
core-foundation = { version = "0.9.0", features = ["mac_os_10_7_support"] }
[target.'cfg(windows)'.dependencies]
miow = "0.3.6"
winapi = { version = "0.3", features = ["consoleapi", "minwindef"] }
winapi = { version = "0.3.9", features = ["consoleapi", "minwindef"] }

View file

@ -4,6 +4,7 @@ pub use self::read2::read2;
pub use process_builder::ProcessBuilder;
pub use process_error::{exit_status_to_string, is_simple_exit_code, ProcessError};
pub mod paths;
mod process_builder;
mod process_error;
mod read2;

View file

@ -1,3 +1,7 @@
//! Various utilities for working with files and paths.
use anyhow::{Context, Result};
use filetime::FileTime;
use std::env;
use std::ffi::{OsStr, OsString};
use std::fs::{self, File, OpenOptions};
@ -5,19 +9,21 @@ use std::io;
use std::io::prelude::*;
use std::iter;
use std::path::{Component, Path, PathBuf};
use filetime::FileTime;
use tempfile::Builder as TempFileBuilder;
use crate::util::errors::{CargoResult, CargoResultExt};
pub fn join_paths<T: AsRef<OsStr>>(paths: &[T], env: &str) -> CargoResult<OsString> {
/// Joins paths into a string suitable for the `PATH` environment variable.
///
/// This is equivalent to [`std::env::join_paths`], but includes a more
/// detailed error message. The given `env` argument is the name of the
/// environment variable this is will be used for, which is included in the
/// error message.
pub fn join_paths<T: AsRef<OsStr>>(paths: &[T], env: &str) -> Result<OsString> {
env::join_paths(paths.iter())
.chain_err(|| {
.with_context(|| {
let paths = paths.iter().map(Path::new).collect::<Vec<_>>();
format!("failed to join path array: {:?}", paths)
})
.chain_err(|| {
.with_context(|| {
format!(
"failed to join search paths together\n\
Does ${} have an unterminated quote character?",
@ -26,6 +32,8 @@ pub fn join_paths<T: AsRef<OsStr>>(paths: &[T], env: &str) -> CargoResult<OsStri
})
}
/// Returns the name of the environment variable used for searching for
/// dynamic libraries.
pub fn dylib_path_envvar() -> &'static str {
if cfg!(windows) {
"PATH"
@ -51,6 +59,10 @@ pub fn dylib_path_envvar() -> &'static str {
}
}
/// Returns a list of directories that are searched for dynamic libraries.
///
/// Note that some operating systems will have defaults if this is empty that
/// will need to be dealt with.
pub fn dylib_path() -> Vec<PathBuf> {
match env::var_os(dylib_path_envvar()) {
Some(var) => env::split_paths(&var).collect(),
@ -58,6 +70,14 @@ pub fn dylib_path() -> Vec<PathBuf> {
}
}
/// Normalize a path, removing things like `.` and `..`.
///
/// CAUTION: This does not resolve symlinks (unlike
/// [`std::fs::canonicalize`]). This may cause incorrect or surprising
/// behavior at times. This should be used carefully. Unfortunately,
/// [`std::fs::canonicalize`] can be hard to use correctly, since it can often
/// fail, or on Windows returns annoying device paths. This is a problem Cargo
/// needs to improve on.
pub fn normalize_path(path: &Path) -> PathBuf {
let mut components = path.components().peekable();
let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
@ -85,7 +105,11 @@ pub fn normalize_path(path: &Path) -> PathBuf {
ret
}
pub fn resolve_executable(exec: &Path) -> CargoResult<PathBuf> {
/// Returns the absolute path of where the given executable is located based
/// on searching the `PATH` environment variable.
///
/// Returns an error if it cannot be found.
pub fn resolve_executable(exec: &Path) -> Result<PathBuf> {
if exec.components().count() == 1 {
let paths = env::var_os("PATH").ok_or_else(|| anyhow::format_err!("no PATH"))?;
let candidates = env::split_paths(&paths).flat_map(|path| {
@ -111,24 +135,36 @@ pub fn resolve_executable(exec: &Path) -> CargoResult<PathBuf> {
}
}
pub fn read(path: &Path) -> CargoResult<String> {
/// Reads a file to a string.
///
/// Equivalent to [`std::fs::read_to_string`] with better error messages.
pub fn read(path: &Path) -> Result<String> {
match String::from_utf8(read_bytes(path)?) {
Ok(s) => Ok(s),
Err(_) => anyhow::bail!("path at `{}` was not valid utf-8", path.display()),
}
}
pub fn read_bytes(path: &Path) -> CargoResult<Vec<u8>> {
fs::read(path).chain_err(|| format!("failed to read `{}`", path.display()))
/// Reads a file into a bytes vector.
///
/// Equivalent to [`std::fs::read`] with better error messages.
pub fn read_bytes(path: &Path) -> Result<Vec<u8>> {
fs::read(path).with_context(|| format!("failed to read `{}`", path.display()))
}
pub fn write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> CargoResult<()> {
/// Writes a file to disk.
///
/// Equivalent to [`std::fs::write`] with better error messages.
pub fn write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> Result<()> {
let path = path.as_ref();
fs::write(path, contents.as_ref()).chain_err(|| format!("failed to write `{}`", path.display()))
fs::write(path, contents.as_ref())
.with_context(|| format!("failed to write `{}`", path.display()))
}
pub fn write_if_changed<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> CargoResult<()> {
(|| -> CargoResult<()> {
/// Equivalent to [`write`], but does not write anything if the file contents
/// are identical to the given contents.
pub fn write_if_changed<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> Result<()> {
(|| -> Result<()> {
let contents = contents.as_ref();
let mut f = OpenOptions::new()
.read(true)
@ -144,12 +180,14 @@ pub fn write_if_changed<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) ->
}
Ok(())
})()
.chain_err(|| format!("failed to write `{}`", path.as_ref().display()))?;
.with_context(|| format!("failed to write `{}`", path.as_ref().display()))?;
Ok(())
}
pub fn append(path: &Path, contents: &[u8]) -> CargoResult<()> {
(|| -> CargoResult<()> {
/// Equivalent to [`write`], but appends to the end instead of replacing the
/// contents.
pub fn append(path: &Path, contents: &[u8]) -> Result<()> {
(|| -> Result<()> {
let mut f = OpenOptions::new()
.write(true)
.append(true)
@ -159,31 +197,34 @@ pub fn append(path: &Path, contents: &[u8]) -> CargoResult<()> {
f.write_all(contents)?;
Ok(())
})()
.chain_err(|| format!("failed to write `{}`", path.display()))?;
.with_context(|| format!("failed to write `{}`", path.display()))?;
Ok(())
}
/// Creates a new file.
pub fn create<P: AsRef<Path>>(path: P) -> CargoResult<File> {
pub fn create<P: AsRef<Path>>(path: P) -> Result<File> {
let path = path.as_ref();
File::create(path).chain_err(|| format!("failed to create file `{}`", path.display()))
File::create(path).with_context(|| format!("failed to create file `{}`", path.display()))
}
/// Opens an existing file.
pub fn open<P: AsRef<Path>>(path: P) -> CargoResult<File> {
pub fn open<P: AsRef<Path>>(path: P) -> Result<File> {
let path = path.as_ref();
File::open(path).chain_err(|| format!("failed to open file `{}`", path.display()))
File::open(path).with_context(|| format!("failed to open file `{}`", path.display()))
}
pub fn mtime(path: &Path) -> CargoResult<FileTime> {
let meta = fs::metadata(path).chain_err(|| format!("failed to stat `{}`", path.display()))?;
/// Returns the last modification time of a file.
pub fn mtime(path: &Path) -> Result<FileTime> {
let meta =
fs::metadata(path).with_context(|| format!("failed to stat `{}`", path.display()))?;
Ok(FileTime::from_last_modification_time(&meta))
}
/// Returns the maximum mtime of the given path, recursing into
/// subdirectories, and following symlinks.
pub fn mtime_recursive(path: &Path) -> CargoResult<FileTime> {
let meta = fs::metadata(path).chain_err(|| format!("failed to stat `{}`", path.display()))?;
pub fn mtime_recursive(path: &Path) -> Result<FileTime> {
let meta =
fs::metadata(path).with_context(|| format!("failed to stat `{}`", path.display()))?;
if !meta.is_dir() {
return Ok(FileTime::from_last_modification_time(&meta));
}
@ -263,7 +304,7 @@ pub fn mtime_recursive(path: &Path) -> CargoResult<FileTime> {
/// Record the current time on the filesystem (using the filesystem's clock)
/// using a file at the given directory. Returns the current time.
pub fn set_invocation_time(path: &Path) -> CargoResult<FileTime> {
pub fn set_invocation_time(path: &Path) -> Result<FileTime> {
// note that if `FileTime::from_system_time(SystemTime::now());` is determined to be sufficient,
// then this can be removed.
let timestamp = path.join("invoked.timestamp");
@ -276,36 +317,47 @@ pub fn set_invocation_time(path: &Path) -> CargoResult<FileTime> {
Ok(ft)
}
#[cfg(unix)]
pub fn path2bytes(path: &Path) -> CargoResult<&[u8]> {
use std::os::unix::prelude::*;
Ok(path.as_os_str().as_bytes())
}
#[cfg(windows)]
pub fn path2bytes(path: &Path) -> CargoResult<&[u8]> {
match path.as_os_str().to_str() {
Some(s) => Ok(s.as_bytes()),
None => Err(anyhow::format_err!(
"invalid non-unicode path: {}",
path.display()
)),
/// Converts a path to UTF-8 bytes.
pub fn path2bytes(path: &Path) -> Result<&[u8]> {
#[cfg(unix)]
{
use std::os::unix::prelude::*;
Ok(path.as_os_str().as_bytes())
}
#[cfg(windows)]
{
match path.as_os_str().to_str() {
Some(s) => Ok(s.as_bytes()),
None => Err(anyhow::format_err!(
"invalid non-unicode path: {}",
path.display()
)),
}
}
}
#[cfg(unix)]
pub fn bytes2path(bytes: &[u8]) -> CargoResult<PathBuf> {
use std::os::unix::prelude::*;
Ok(PathBuf::from(OsStr::from_bytes(bytes)))
}
#[cfg(windows)]
pub fn bytes2path(bytes: &[u8]) -> CargoResult<PathBuf> {
use std::str;
match str::from_utf8(bytes) {
Ok(s) => Ok(PathBuf::from(s)),
Err(..) => Err(anyhow::format_err!("invalid non-unicode path")),
/// Converts UTF-8 bytes to a path.
pub fn bytes2path(bytes: &[u8]) -> Result<PathBuf> {
#[cfg(unix)]
{
use std::os::unix::prelude::*;
Ok(PathBuf::from(OsStr::from_bytes(bytes)))
}
#[cfg(windows)]
{
use std::str;
match str::from_utf8(bytes) {
Ok(s) => Ok(PathBuf::from(s)),
Err(..) => Err(anyhow::format_err!("invalid non-unicode path")),
}
}
}
/// Returns an iterator that walks up the directory hierarchy towards the root.
///
/// Each item is a [`Path`]. It will start with the given path, finishing at
/// the root. If the `stop_root_at` parameter is given, it will stop at the
/// given path (which will be the last item).
pub fn ancestors<'a>(path: &'a Path, stop_root_at: Option<&Path>) -> PathAncestors<'a> {
PathAncestors::new(path, stop_root_at)
}
@ -349,22 +401,27 @@ impl<'a> Iterator for PathAncestors<'a> {
}
}
pub fn create_dir_all(p: impl AsRef<Path>) -> CargoResult<()> {
/// Equivalent to [`std::fs::create_dir_all`] with better error messages.
pub fn create_dir_all(p: impl AsRef<Path>) -> Result<()> {
_create_dir_all(p.as_ref())
}
fn _create_dir_all(p: &Path) -> CargoResult<()> {
fs::create_dir_all(p).chain_err(|| format!("failed to create directory `{}`", p.display()))?;
fn _create_dir_all(p: &Path) -> Result<()> {
fs::create_dir_all(p)
.with_context(|| format!("failed to create directory `{}`", p.display()))?;
Ok(())
}
pub fn remove_dir_all<P: AsRef<Path>>(p: P) -> CargoResult<()> {
/// Recursively remove all files and directories at the given directory.
///
/// This does *not* follow symlinks.
pub fn remove_dir_all<P: AsRef<Path>>(p: P) -> Result<()> {
_remove_dir_all(p.as_ref())
}
fn _remove_dir_all(p: &Path) -> CargoResult<()> {
fn _remove_dir_all(p: &Path) -> Result<()> {
if p.symlink_metadata()
.chain_err(|| format!("could not get metadata for `{}` to remove", p.display()))?
.with_context(|| format!("could not get metadata for `{}` to remove", p.display()))?
.file_type()
.is_symlink()
{
@ -372,7 +429,7 @@ fn _remove_dir_all(p: &Path) -> CargoResult<()> {
}
let entries = p
.read_dir()
.chain_err(|| format!("failed to read directory `{}`", p.display()))?;
.with_context(|| format!("failed to read directory `{}`", p.display()))?;
for entry in entries {
let entry = entry?;
let path = entry.path();
@ -385,20 +442,25 @@ fn _remove_dir_all(p: &Path) -> CargoResult<()> {
remove_dir(&p)
}
pub fn remove_dir<P: AsRef<Path>>(p: P) -> CargoResult<()> {
/// Equivalent to [`std::fs::remove_dir`] with better error messages.
pub fn remove_dir<P: AsRef<Path>>(p: P) -> Result<()> {
_remove_dir(p.as_ref())
}
fn _remove_dir(p: &Path) -> CargoResult<()> {
fs::remove_dir(p).chain_err(|| format!("failed to remove directory `{}`", p.display()))?;
fn _remove_dir(p: &Path) -> Result<()> {
fs::remove_dir(p).with_context(|| format!("failed to remove directory `{}`", p.display()))?;
Ok(())
}
pub fn remove_file<P: AsRef<Path>>(p: P) -> CargoResult<()> {
/// Equivalent to [`std::fs::remove_file`] with better error messages.
///
/// If the file is readonly, this will attempt to change the permissions to
/// force the file to be deleted.
pub fn remove_file<P: AsRef<Path>>(p: P) -> Result<()> {
_remove_file(p.as_ref())
}
fn _remove_file(p: &Path) -> CargoResult<()> {
fn _remove_file(p: &Path) -> Result<()> {
let mut err = match fs::remove_file(p) {
Ok(()) => return Ok(()),
Err(e) => e,
@ -411,7 +473,7 @@ fn _remove_file(p: &Path) -> CargoResult<()> {
}
}
Err(err).chain_err(|| format!("failed to remove file `{}`", p.display()))?;
Err(err).with_context(|| format!("failed to remove file `{}`", p.display()))?;
Ok(())
}
@ -428,13 +490,13 @@ fn set_not_readonly(p: &Path) -> io::Result<bool> {
/// Hardlink (file) or symlink (dir) src to dst if possible, otherwise copy it.
///
/// If the destination already exists, it is removed before linking.
pub fn link_or_copy(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> CargoResult<()> {
pub fn link_or_copy(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> Result<()> {
let src = src.as_ref();
let dst = dst.as_ref();
_link_or_copy(src, dst)
}
fn _link_or_copy(src: &Path, dst: &Path) -> CargoResult<()> {
fn _link_or_copy(src: &Path, dst: &Path) -> Result<()> {
log::debug!("linking {} to {}", src.display(), dst.display());
if same_file::is_same_file(src, dst).unwrap_or(false) {
return Ok(());
@ -486,7 +548,7 @@ fn _link_or_copy(src: &Path, dst: &Path) -> CargoResult<()> {
log::debug!("link failed {}. falling back to fs::copy", err);
fs::copy(src, dst).map(|_| ())
})
.chain_err(|| {
.with_context(|| {
format!(
"failed to link or copy `{}` to `{}`",
src.display(),
@ -497,11 +559,13 @@ fn _link_or_copy(src: &Path, dst: &Path) -> CargoResult<()> {
}
/// Copies a file from one location to another.
pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> CargoResult<u64> {
///
/// Equivalent to [`std::fs::copy`] with better error messages.
pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> Result<u64> {
let from = from.as_ref();
let to = to.as_ref();
fs::copy(from, to)
.chain_err(|| format!("failed to copy `{}` to `{}`", from.display(), to.display()))
.with_context(|| format!("failed to copy `{}` to `{}`", from.display(), to.display()))
}
/// Changes the filesystem mtime (and atime if possible) for the given file.
@ -551,7 +615,7 @@ pub fn strip_prefix_canonical<P: AsRef<Path>>(
///
/// This function is idempotent and in addition to that it won't exclude ``p`` from cache if it
/// already exists.
pub fn create_dir_all_excluded_from_backups_atomic(p: impl AsRef<Path>) -> CargoResult<()> {
pub fn create_dir_all_excluded_from_backups_atomic(p: impl AsRef<Path>) -> Result<()> {
let path = p.as_ref();
if path.is_dir() {
return Ok(());

View file

@ -1,7 +1,7 @@
use crate::aliased_command;
use cargo::util::errors::CargoResult;
use cargo::util::paths::resolve_executable;
use cargo::Config;
use cargo_util::paths::resolve_executable;
use flate2::read::GzDecoder;
use std::ffi::OsString;
use std::io::Read;

View file

@ -3,9 +3,9 @@ use crate::core::compiler::{
};
use crate::core::{Dependency, Target, TargetKind, Workspace};
use crate::util::config::{Config, StringList, TargetConfig};
use crate::util::{paths, CargoResult, CargoResultExt, Rustc};
use crate::util::{CargoResult, CargoResultExt, Rustc};
use cargo_platform::{Cfg, CfgExpr};
use cargo_util::ProcessBuilder;
use cargo_util::{paths, ProcessBuilder};
use serde::{Deserialize, Serialize};
use std::cell::RefCell;
use std::collections::hash_map::{Entry, HashMap};

View file

@ -4,13 +4,13 @@ use std::ffi::{OsStr, OsString};
use std::path::PathBuf;
use cargo_platform::CfgExpr;
use cargo_util::ProcessBuilder;
use cargo_util::{paths, ProcessBuilder};
use semver::Version;
use super::BuildContext;
use crate::core::compiler::{CompileKind, Metadata, Unit};
use crate::core::Package;
use crate::util::{self, config, join_paths, CargoResult, Config};
use crate::util::{config, CargoResult, Config};
/// Structure with enough information to run `rustdoc --test`.
pub struct Doctest {
@ -279,7 +279,7 @@ impl<'cfg> Compilation<'cfg> {
}
}
let dylib_path = util::dylib_path();
let dylib_path = paths::dylib_path();
let dylib_path_is_empty = dylib_path.is_empty();
search_path.extend(dylib_path.into_iter());
if cfg!(target_os = "macos") && dylib_path_is_empty {
@ -292,9 +292,9 @@ impl<'cfg> Compilation<'cfg> {
search_path.push(PathBuf::from("/usr/local/lib"));
search_path.push(PathBuf::from("/usr/lib"));
}
let search_path = join_paths(&search_path, util::dylib_path_envvar())?;
let search_path = paths::join_paths(&search_path, paths::dylib_path_envvar())?;
cmd.env(util::dylib_path_envvar(), &search_path);
cmd.env(paths::dylib_path_envvar(), &search_path);
if let Some(meta) = script_meta {
if let Some(env) = self.extra_env.get(&meta) {
for (k, v) in env {

View file

@ -6,8 +6,9 @@ use crate::core::{profiles::ProfileRoot, PackageId};
use crate::util::errors::{CargoResult, CargoResultExt};
use crate::util::interning::InternedString;
use crate::util::machine_message::{self, Message};
use crate::util::{self, internal, paths, profile};
use crate::util::{internal, profile};
use cargo_platform::Cfg;
use cargo_util::paths;
use std::collections::hash_map::{Entry, HashMap};
use std::collections::{BTreeSet, HashSet};
use std::path::{Path, PathBuf};
@ -395,7 +396,7 @@ fn build_work(cx: &mut Context<'_, '_>, unit: &Unit) -> CargoResult<Job> {
// modified in the middle of the build.
paths::set_file_time_no_err(output_file, timestamp);
paths::write(&err_file, &output.stderr)?;
paths::write(&root_output_file, util::path2bytes(&script_out_dir)?)?;
paths::write(&root_output_file, paths::path2bytes(&script_out_dir)?)?;
let parsed_output = BuildOutput::parse(
&output.stdout,
pkg_name,
@ -849,7 +850,7 @@ fn prev_build_output(cx: &mut Context<'_, '_>, unit: &Unit) -> (Option<BuildOutp
let output_file = script_run_dir.join("output");
let prev_script_out_dir = paths::read_bytes(&root_output_file)
.and_then(|bytes| util::bytes2path(&bytes))
.and_then(|bytes| paths::bytes2path(&bytes))
.unwrap_or_else(|_| script_out_dir.clone());
let extra_link_arg = cx.bcx.config.cli_unstable().extra_link_arg;

View file

@ -322,7 +322,7 @@ use std::sync::{Arc, Mutex};
use std::time::SystemTime;
use anyhow::{bail, format_err};
use cargo_util::ProcessBuilder;
use cargo_util::{paths, ProcessBuilder};
use filetime::FileTime;
use log::{debug, info};
use serde::de;
@ -334,7 +334,6 @@ use crate::core::Package;
use crate::util;
use crate::util::errors::{CargoResult, CargoResultExt};
use crate::util::interning::InternedString;
use crate::util::paths;
use crate::util::{internal, path_args, profile};
use super::custom_build::BuildDeps;
@ -1916,7 +1915,7 @@ impl EncodedDepInfo {
_ => return None,
};
let bytes = read_bytes(bytes)?;
files.push((ty, util::bytes2path(bytes).ok()?));
files.push((ty, paths::bytes2path(bytes).ok()?));
}
let nenv = read_usize(bytes)?;
@ -1961,7 +1960,7 @@ impl EncodedDepInfo {
DepInfoPathType::PackageRootRelative => dst.push(0),
DepInfoPathType::TargetRootRelative => dst.push(1),
}
write_bytes(dst, util::path2bytes(file)?);
write_bytes(dst, paths::path2bytes(file)?);
}
write_usize(dst, self.env.len());

View file

@ -100,8 +100,8 @@
use crate::core::compiler::CompileTarget;
use crate::core::Workspace;
use crate::util::paths;
use crate::util::{CargoResult, FileLock};
use cargo_util::paths;
use std::path::{Path, PathBuf};
/// Contains the paths of all target output locations.

View file

@ -56,10 +56,9 @@ use crate::core::profiles::{PanicStrategy, Profile, Strip};
use crate::core::{Feature, PackageId, Target};
use crate::util::errors::{CargoResult, CargoResultExt, VerboseError};
use crate::util::interning::InternedString;
use crate::util::machine_message::Message;
use crate::util::{self, machine_message};
use crate::util::{add_path_args, internal, join_paths, paths, profile};
use cargo_util::{ProcessBuilder, ProcessError};
use crate::util::machine_message::{self, Message};
use crate::util::{add_path_args, internal, profile};
use cargo_util::{paths, ProcessBuilder, ProcessError};
const RUSTDOC_CRATE_VERSION_FLAG: &str = "--crate-version";
@ -505,7 +504,7 @@ fn add_plugin_deps(
build_scripts: &BuildScripts,
root_output: &Path,
) -> CargoResult<()> {
let var = util::dylib_path_envvar();
let var = paths::dylib_path_envvar();
let search_path = rustc.get_env(var).unwrap_or_default();
let mut search_path = env::split_paths(&search_path).collect::<Vec<_>>();
for (pkg_id, metadata) in &build_scripts.plugins {
@ -517,7 +516,7 @@ fn add_plugin_deps(
root_output,
));
}
let search_path = join_paths(&search_path, var)?;
let search_path = paths::join_paths(&search_path, var)?;
rustc.env(var, &search_path);
Ok(())
}

View file

@ -26,11 +26,10 @@ use std::collections::{BTreeSet, HashSet};
use std::io::{BufWriter, Write};
use std::path::{Path, PathBuf};
use log::debug;
use super::{fingerprint, Context, FileFlavor, Unit};
use crate::util::paths;
use crate::util::{internal, CargoResult};
use cargo_util::paths;
use log::debug;
fn render_filename<P: AsRef<Path>>(path: P, basedir: Option<&str>) -> CargoResult<String> {
let path = path.as_ref();

View file

@ -8,7 +8,8 @@ use crate::core::compiler::BuildContext;
use crate::core::PackageId;
use crate::util::cpu::State;
use crate::util::machine_message::{self, Message};
use crate::util::{paths, CargoResult, CargoResultExt, Config};
use crate::util::{CargoResult, CargoResultExt, Config};
use cargo_util::paths;
use std::collections::HashMap;
use std::io::{BufWriter, Write};
use std::time::{Duration, Instant, SystemTime};

View file

@ -19,9 +19,9 @@ use crate::ops;
use crate::sources::{PathSource, CRATES_IO_INDEX, CRATES_IO_REGISTRY};
use crate::util::errors::{CargoResult, CargoResultExt, ManifestError};
use crate::util::interning::InternedString;
use crate::util::paths;
use crate::util::toml::{read_manifest, TomlDependency, TomlProfiles};
use crate::util::{config::ConfigRelativePath, Config, Filesystem, IntoUrl};
use cargo_util::paths;
/// The core abstraction in Cargo for working with a workspace of crates.
///

View file

@ -5,8 +5,8 @@ use crate::ops;
use crate::util::errors::{CargoResult, CargoResultExt};
use crate::util::interning::InternedString;
use crate::util::lev_distance;
use crate::util::paths;
use crate::util::Config;
use cargo_util::paths;
use std::fs;
use std::path::Path;

View file

@ -3,17 +3,17 @@ use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::{env, fs};
use anyhow::{bail, format_err};
use semver::VersionReq;
use tempfile::Builder as TempFileBuilder;
use crate::core::compiler::{CompileKind, DefaultExecutor, Executor, Freshness, UnitOutput};
use crate::core::{Dependency, Edition, Package, PackageId, Source, SourceId, Workspace};
use crate::ops::common_for_install_and_uninstall::*;
use crate::sources::{GitSource, PathSource, SourceConfigMap};
use crate::util::errors::{CargoResult, CargoResultExt};
use crate::util::{paths, Config, Filesystem, Rustc, ToSemver};
use crate::util::{Config, Filesystem, Rustc, ToSemver};
use crate::{drop_println, ops};
use anyhow::{bail, format_err};
use cargo_util::paths;
use semver::VersionReq;
use tempfile::Builder as TempFileBuilder;
struct Transaction {
bins: Vec<PathBuf>,

View file

@ -1,7 +1,8 @@
use crate::core::{Edition, Shell, Workspace};
use crate::util::errors::{CargoResult, CargoResultExt};
use crate::util::{existing_vcs_repo, FossilRepo, GitRepo, HgRepo, PijulRepo};
use crate::util::{paths, restricted_names, Config};
use crate::util::{restricted_names, Config};
use cargo_util::paths;
use git2::Config as GitConfig;
use git2::Repository as GitRepository;
use serde::de;

View file

@ -6,20 +6,19 @@ use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::sync::Arc;
use flate2::read::GzDecoder;
use flate2::{Compression, GzBuilder};
use log::debug;
use tar::{Archive, Builder, EntryType, Header, HeaderMode};
use crate::core::compiler::{BuildConfig, CompileMode, DefaultExecutor, Executor};
use crate::core::{Feature, Shell, Verbosity, Workspace};
use crate::core::{Package, PackageId, PackageSet, Resolve, Source, SourceId};
use crate::sources::PathSource;
use crate::util::errors::{CargoResult, CargoResultExt};
use crate::util::paths;
use crate::util::toml::TomlManifest;
use crate::util::{self, restricted_names, Config, FileLock};
use crate::{drop_println, ops};
use cargo_util::paths;
use flate2::read::GzDecoder;
use flate2::{Compression, GzBuilder};
use log::debug;
use tar::{Archive, Builder, EntryType, Header, HeaderMode};
pub struct PackageOpts<'cfg> {
pub config: &'cfg Config,
@ -480,7 +479,7 @@ fn tar(
// Prepare the encoder and its header.
let filename = Path::new(filename);
let encoder = GzBuilder::new()
.filename(util::path2bytes(filename)?)
.filename(paths::path2bytes(filename)?)
.write(dst, Compression::best());
// Put all package files into a compressed archive.

View file

@ -3,13 +3,13 @@ use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use log::{info, trace};
use crate::core::{EitherManifest, Package, PackageId, SourceId};
use crate::util::errors::CargoResult;
use crate::util::important_paths::find_project_manifest_exact;
use crate::util::toml::read_manifest;
use crate::util::{self, Config};
use crate::util::Config;
use cargo_util::paths;
use log::{info, trace};
pub fn read_package(
path: &Path,
@ -192,7 +192,7 @@ fn read_nested_packages(
// TODO: filesystem/symlink implications?
if !source_id.is_registry() {
for p in nested.iter() {
let path = util::normalize_path(&path.join(p));
let path = paths::normalize_path(&path.join(p));
let result =
read_nested_packages(&path, all_packages, source_id, config, visited, errors);
// Ignore broken manifests found on git repositories.

View file

@ -1,15 +1,14 @@
use anyhow::bail;
use std::collections::BTreeSet;
use std::env;
use crate::core::PackageId;
use crate::core::{PackageIdSpec, SourceId};
use crate::ops::common_for_install_and_uninstall::*;
use crate::sources::PathSource;
use crate::util::errors::CargoResult;
use crate::util::paths;
use crate::util::Config;
use crate::util::Filesystem;
use anyhow::bail;
use cargo_util::paths;
use std::collections::BTreeSet;
use std::env;
pub fn uninstall(
root: Option<&str>,

View file

@ -46,7 +46,7 @@ use std::process::{self, Command, ExitStatus};
use std::str;
use anyhow::{bail, Context, Error};
use cargo_util::ProcessBuilder;
use cargo_util::{paths, ProcessBuilder};
use log::{debug, trace, warn};
use rustfix::diagnostics::Diagnostic;
use rustfix::{self, CodeFix};
@ -58,7 +58,7 @@ use crate::core::{Edition, MaybePackage, Workspace};
use crate::ops::{self, CompileOptions};
use crate::util::diagnostic_server::{Message, RustfixDiagnosticServer};
use crate::util::errors::CargoResult;
use crate::util::{self, paths, Config};
use crate::util::Config;
use crate::util::{existing_vcs_repo, LockServer, LockServerClient};
use crate::{drop_eprint, drop_eprintln};
@ -596,7 +596,7 @@ fn rustfix_and_fix(
// Attempt to read the source code for this file. If this fails then
// that'd be pretty surprising, so log a message and otherwise keep
// going.
let code = match util::paths::read(file.as_ref()) {
let code = match paths::read(file.as_ref()) {
Ok(s) => s,
Err(e) => {
warn!("failed to read `{}`: {}", file, e);

View file

@ -8,6 +8,7 @@ use std::time::Duration;
use std::{cmp, env};
use anyhow::{bail, format_err};
use cargo_util::paths;
use crates_io::{self, NewCrate, NewCrateDependency, Registry};
use curl::easy::{Easy, InfoType, SslOpt, SslVersion};
use log::{log, Level};
@ -22,8 +23,8 @@ use crate::sources::{RegistrySource, SourceConfigMap, CRATES_IO_REGISTRY};
use crate::util::config::{self, Config, SslVersionConfig, SslVersionConfigRange};
use crate::util::errors::{CargoResult, CargoResultExt};
use crate::util::important_paths::find_root_manifest_for_wd;
use crate::util::validate_package_name;
use crate::util::IntoUrl;
use crate::util::{paths, validate_package_name};
use crate::{drop_print, drop_println, version};
mod auth;

View file

@ -3,8 +3,9 @@ use crate::core::{GitReference, Workspace};
use crate::ops;
use crate::sources::path::PathSource;
use crate::util::Sha256;
use crate::util::{paths, CargoResult, CargoResultExt, Config};
use crate::util::{CargoResult, CargoResultExt, Config};
use anyhow::bail;
use cargo_util::paths;
use serde::Serialize;
use std::collections::HashSet;
use std::collections::{BTreeMap, BTreeSet, HashMap};

View file

@ -2,14 +2,13 @@ use std::collections::HashMap;
use std::fmt::{self, Debug, Formatter};
use std::path::{Path, PathBuf};
use serde::Deserialize;
use crate::core::source::MaybePackage;
use crate::core::{Dependency, Package, PackageId, Source, SourceId, Summary};
use crate::sources::PathSource;
use crate::util::errors::{CargoResult, CargoResultExt};
use crate::util::paths;
use crate::util::{Config, Sha256};
use cargo_util::paths;
use serde::Deserialize;
pub struct DirectorySource<'cfg> {
source_id: SourceId,

View file

@ -3,10 +3,9 @@
use crate::core::GitReference;
use crate::util::errors::{CargoResult, CargoResultExt};
use crate::util::paths;
use crate::util::{network, Config, IntoUrl, Progress};
use anyhow::{anyhow, Context};
use cargo_util::ProcessBuilder;
use cargo_util::{paths, ProcessBuilder};
use curl::easy::List;
use git2::{self, ErrorClass, ObjectType};
use log::{debug, info};

View file

@ -2,16 +2,16 @@ use std::fmt::{self, Debug, Formatter};
use std::fs;
use std::path::{Path, PathBuf};
use crate::core::source::MaybePackage;
use crate::core::{Dependency, Package, PackageId, Source, SourceId, Summary};
use crate::ops;
use crate::util::{internal, CargoResult, CargoResultExt, Config};
use cargo_util::paths;
use filetime::FileTime;
use ignore::gitignore::GitignoreBuilder;
use ignore::Match;
use log::{trace, warn};
use crate::core::source::MaybePackage;
use crate::core::{Dependency, Package, PackageId, Source, SourceId, Summary};
use crate::ops;
use crate::util::{internal, paths, CargoResult, CargoResultExt, Config};
pub struct PathSource<'cfg> {
source_id: SourceId,
path: PathBuf,

View file

@ -70,9 +70,9 @@ use crate::core::dependency::Dependency;
use crate::core::{PackageId, SourceId, Summary};
use crate::sources::registry::{RegistryData, RegistryPackage, INDEX_V_MAX};
use crate::util::interning::InternedString;
use crate::util::paths;
use crate::util::{internal, CargoResult, Config, Filesystem, ToSemver};
use anyhow::bail;
use cargo_util::paths;
use log::{debug, info};
use semver::{Version, VersionReq};
use std::collections::{HashMap, HashSet};

View file

@ -2,8 +2,8 @@ use crate::core::PackageId;
use crate::sources::registry::{MaybeLock, RegistryConfig, RegistryData};
use crate::util::errors::CargoResult;
use crate::util::interning::InternedString;
use crate::util::paths;
use crate::util::{Config, Filesystem, Sha256};
use cargo_util::paths;
use std::fs::File;
use std::io::prelude::*;
use std::io::SeekFrom;

View file

@ -7,8 +7,8 @@ use crate::sources::registry::{
};
use crate::util::errors::{CargoResult, CargoResultExt};
use crate::util::interning::InternedString;
use crate::util::paths;
use crate::util::{Config, Filesystem, Sha256};
use cargo_util::paths;
use lazycell::LazyCell;
use log::{debug, trace};
use std::cell::{Cell, Ref, RefCell};

View file

@ -5,13 +5,14 @@ use crate::sources::CRATES_IO_REGISTRY;
use crate::util::important_paths::find_root_manifest_for_wd;
use crate::util::interning::InternedString;
use crate::util::restricted_names::is_glob_pattern;
use crate::util::{paths, toml::TomlProfile, validate_package_name};
use crate::util::{
print_available_benches, print_available_binaries, print_available_examples,
print_available_packages, print_available_tests,
};
use crate::util::{toml::TomlProfile, validate_package_name};
use crate::CargoResult;
use anyhow::bail;
use cargo_util::paths;
use clap::{self, SubCommand};
use std::ffi::{OsStr, OsString};
use std::path::PathBuf;

View file

@ -65,12 +65,6 @@ use std::str::FromStr;
use std::sync::Once;
use std::time::Instant;
use anyhow::{anyhow, bail, format_err};
use curl::easy::Easy;
use lazycell::LazyCell;
use serde::Deserialize;
use url::Url;
use self::ConfigValue as CV;
use crate::core::compiler::rustdoc::RustdocExternMap;
use crate::core::shell::Verbosity;
@ -78,8 +72,14 @@ use crate::core::{features, CliUnstable, Shell, SourceId, Workspace};
use crate::ops;
use crate::util::errors::{CargoResult, CargoResultExt};
use crate::util::toml as cargo_toml;
use crate::util::{paths, validate_package_name};
use crate::util::validate_package_name;
use crate::util::{FileLock, Filesystem, IntoUrl, IntoUrlWithBase, Rustc};
use anyhow::{anyhow, bail, format_err};
use cargo_util::paths;
use curl::easy::Easy;
use lazycell::LazyCell;
use serde::Deserialize;
use url::Url;
mod de;
use de::Deserializer;

View file

@ -3,12 +3,11 @@ use std::io;
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::{Display, Path, PathBuf};
use termcolor::Color::Cyan;
use crate::util::errors::{CargoResult, CargoResultExt};
use crate::util::paths;
use crate::util::Config;
use cargo_util::paths;
use sys::*;
use termcolor::Color::Cyan;
#[derive(Debug)]
pub struct FileLock {

View file

@ -1,5 +1,5 @@
use crate::util::errors::CargoResult;
use crate::util::paths;
use cargo_util::paths;
use std::path::{Path, PathBuf};
/// Finds the root `Cargo.toml`.

View file

@ -14,8 +14,6 @@ pub use self::into_url::IntoUrl;
pub use self::into_url_with_base::IntoUrlWithBase;
pub use self::lev_distance::{closest, closest_msg, lev_distance};
pub use self::lockserver::{LockServer, LockServerClient, LockServerStarted};
pub use self::paths::{bytes2path, dylib_path, join_paths, path2bytes};
pub use self::paths::{dylib_path_envvar, normalize_path};
pub use self::progress::{Progress, ProgressStyle};
pub use self::queue::Queue;
pub use self::restricted_names::validate_package_name;
@ -48,7 +46,6 @@ pub mod lev_distance;
mod lockserver;
pub mod machine_message;
pub mod network;
pub mod paths;
pub mod profile;
mod progress;
mod queue;

View file

@ -4,12 +4,11 @@ use std::hash::{Hash, Hasher};
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use cargo_util::{ProcessBuilder, ProcessError};
use cargo_util::{paths, ProcessBuilder, ProcessError};
use log::{debug, info, warn};
use serde::{Deserialize, Serialize};
use crate::util::interning::InternedString;
use crate::util::paths;
use crate::util::{profile, CargoResult, CargoResultExt, StableHasher};
/// Information on the `rustc` executable

View file

@ -1,4 +1,5 @@
use crate::util::{paths, CargoResult, CargoResultExt};
use crate::util::{CargoResult, CargoResultExt};
use cargo_util::paths;
use crypto_hash::{Algorithm, Hasher};
use std::fs::File;
use std::io::{self, Read, Write};

View file

@ -7,6 +7,7 @@ use std::str;
use anyhow::{anyhow, bail};
use cargo_platform::Platform;
use cargo_util::paths;
use log::{debug, trace};
use semver::{self, VersionReq};
use serde::de;
@ -23,9 +24,7 @@ use crate::core::{GitReference, PackageIdSpec, SourceId, WorkspaceConfig, Worksp
use crate::sources::{CRATES_IO_INDEX, CRATES_IO_REGISTRY};
use crate::util::errors::{CargoResult, CargoResultExt, ManifestError};
use crate::util::interning::InternedString;
use crate::util::{
self, config::ConfigRelativePath, paths, validate_package_name, Config, IntoUrl,
};
use crate::util::{self, config::ConfigRelativePath, validate_package_name, Config, IntoUrl};
mod targets;
use self::targets::targets;
@ -1774,7 +1773,7 @@ impl<P: ResolveToPath> DetailedTomlDependency<P> {
// built from.
if cx.source_id.is_path() {
let path = cx.root.join(path);
let path = util::normalize_path(&path);
let path = paths::normalize_path(&path);
SourceId::for_path(&path)?
} else {
cx.source_id

View file

@ -1,5 +1,5 @@
use crate::util::paths;
use crate::util::CargoResult;
use cargo_util::paths;
use cargo_util::ProcessBuilder;
use std::path::Path;

View file

@ -4,7 +4,6 @@ use cargo::{
core::compiler::CompileMode,
core::{Shell, Workspace},
ops::CompileOptions,
util::paths::dylib_path_envvar,
Config,
};
use cargo_test_support::paths::{root, CargoPathExt};
@ -14,6 +13,7 @@ use cargo_test_support::{
lines_match_unordered, main_file, paths, process, project, rustc_host, sleep_ms,
symlink_supported, t, Execs, ProjectBuilder,
};
use cargo_util::paths::dylib_path_envvar;
use std::env;
use std::fs;
use std::io::Read;
@ -5377,7 +5377,7 @@ fn reduced_reproduction_8249() {
.build();
p.cargo("generate-lockfile").run();
cargo::util::paths::append(&p.root().join("Cargo.toml"), b"c = \"*\"").unwrap();
cargo_util::paths::append(&p.root().join("Cargo.toml"), b"c = \"*\"").unwrap();
p.cargo("check").run();
p.cargo("check").run();
}

View file

@ -1,15 +1,14 @@
//! Tests for build.rs scripts.
use std::env;
use std::fs;
use std::io;
use std::thread;
use cargo::util::paths::remove_dir_all;
use cargo_test_support::paths::CargoPathExt;
use cargo_test_support::registry::Package;
use cargo_test_support::{basic_manifest, cross_compile, is_coarse_mtime, project};
use cargo_test_support::{rustc_host, sleep_ms, slow_cpu_multiplier, symlink_supported};
use cargo_util::paths::remove_dir_all;
use std::env;
use std::fs;
use std::io;
use std::thread;
#[cargo_test]
fn custom_build_script_failed() {

View file

@ -1,11 +1,10 @@
//! Tests for corrupt git repos.
use std::fs;
use std::path::{Path, PathBuf};
use cargo::util::paths as cargopaths;
use cargo_test_support::paths;
use cargo_test_support::{basic_manifest, git, project};
use cargo_util::paths as cargopaths;
use std::fs;
use std::path::{Path, PathBuf};
#[cargo_test]
fn deleting_database_files() {

View file

@ -209,7 +209,7 @@ fn publish() {
fn basic_unsupported() {
// Non-action commands don't support login/logout.
registry::RegistryBuilder::new().add_tokens(false).build();
cargo::util::paths::append(
cargo_util::paths::append(
&paths::home().join(".cargo/config"),
br#"
[registry]
@ -271,7 +271,7 @@ fn login() {
.build();
cred_proj.cargo("build").run();
cargo::util::paths::append(
cargo_util::paths::append(
&paths::home().join(".cargo/config"),
format!(
r#"
@ -323,7 +323,7 @@ fn logout() {
.build();
cred_proj.cargo("build").run();
cargo::util::paths::append(
cargo_util::paths::append(
&paths::home().join(".cargo/config"),
format!(
r#"
@ -390,7 +390,7 @@ fn owner() {
fn libexec_path() {
// cargo: prefixed names use the sysroot
registry::RegistryBuilder::new().add_tokens(false).build();
cargo::util::paths::append(
cargo_util::paths::append(
&paths::home().join(".cargo/config"),
br#"
[registry]
@ -428,7 +428,7 @@ fn invalid_token_output() {
.build();
cred_proj.cargo("build").run();
cargo::util::paths::append(
cargo_util::paths::append(
&paths::home().join(".cargo/config"),
format!(
r#"

View file

@ -1,11 +1,12 @@
//! Tests for normal registry dependencies.
use cargo::{core::SourceId, util::paths::remove_dir_all};
use cargo::core::SourceId;
use cargo_test_support::paths::{self, CargoPathExt};
use cargo_test_support::registry::{self, registry_path, Dependency, Package};
use cargo_test_support::{basic_manifest, project};
use cargo_test_support::{cargo_process, registry::registry_url};
use cargo_test_support::{git, install::cargo_home, t};
use cargo_util::paths::remove_dir_all;
use std::fs::{self, File};
use std::path::Path;

View file

@ -1,7 +1,7 @@
//! Tests for the `cargo run` command.
use cargo::util::paths::dylib_path_envvar;
use cargo_test_support::{basic_bin_manifest, basic_lib_manifest, project, Project};
use cargo_util::paths::dylib_path_envvar;
#[cargo_test]
fn simple() {