cargo/src/cargo/util/errors.rs

330 lines
8.6 KiB
Rust
Raw Normal View History

#![allow(unknown_lints)]
2020-01-08 03:58:45 +00:00
use crate::core::{TargetKind, Workspace};
use crate::ops::CompileOptions;
use anyhow::Error;
2021-03-20 18:28:38 +00:00
use cargo_util::ProcessError;
2015-01-13 16:41:04 +00:00
use std::fmt;
2018-12-08 11:19:47 +00:00
use std::path::PathBuf;
pub type CargoResult<T> = anyhow::Result<T>;
2014-06-19 15:13:58 +00:00
// TODO: should delete this trait and just use `with_context` instead
pub trait CargoResultExt<T, E> {
fn chain_err<F, D>(self, f: F) -> CargoResult<T>
2018-03-14 15:17:44 +00:00
where
F: FnOnce() -> D,
D: fmt::Display + Send + Sync + 'static;
}
2014-06-19 15:13:58 +00:00
impl<T, E> CargoResultExt<T, E> for Result<T, E>
2018-03-14 15:17:44 +00:00
where
E: Into<Error>,
{
fn chain_err<F, D>(self, f: F) -> CargoResult<T>
2018-03-14 15:17:44 +00:00
where
F: FnOnce() -> D,
D: fmt::Display + Send + Sync + 'static,
{
self.map_err(|e| e.into().context(f()))
}
}
#[derive(Debug)]
pub struct HttpNot200 {
pub code: u32,
pub url: String,
}
impl fmt::Display for HttpNot200 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"failed to get 200 response from `{}`, got {}",
self.url, self.code
)
}
}
impl std::error::Error for HttpNot200 {}
2020-02-18 02:46:48 +00:00
// =============================================================================
// Verbose error
/// An error wrapper for errors that should only be displayed with `--verbose`.
///
/// This should only be used in rare cases. When emitting this error, you
/// should have a normal error higher up the error-cause chain (like "could
/// not compile `foo`"), so at least *something* gets printed without
/// `--verbose`.
pub struct VerboseError {
inner: Error,
}
2020-02-18 02:46:48 +00:00
impl VerboseError {
pub fn new(inner: Error) -> VerboseError {
VerboseError { inner }
}
}
2020-02-18 02:46:48 +00:00
impl std::error::Error for VerboseError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.inner.source()
}
}
2015-01-24 08:16:54 +00:00
2020-02-18 02:46:48 +00:00
impl fmt::Debug for VerboseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.inner.fmt(f)
2015-01-24 08:16:54 +00:00
}
Implement a registry source # cargo upload The cargo-upload command will take the local package and upload it to the specified registry. The local package is uploaded as a tarball compressed with gzip under maximum compression. Most of this is done by just delegating to `cargo package` The host to upload to is specified, in order of priority, by a command line `--host` flag, the `registry.host` config key, and then the default registry. The default registry is still `example.com` The registry itself is still a work in progress, but the general plumbing for a command such as this would look like: 1. Ensure the local package has been compressed into an archive. 2. Fetch the relevant registry and login token from config files. 3. Ensure all dependencies for a package are listed as coming from the same registry. 4. Upload the archive to the registry with the login token. 5. The registry will verify the package is under 2MB (configurable). 6. The registry will upload the archive to S3, calculating a checksum in the process. 7. The registry will add an entry to the registry's index (a git repository). The entry will include the name of the package, the version uploaded, the checksum of the upload, and then the list of dependencies (name/version req) 8. The local `cargo upload` command will succeed. # cargo login Uploading requires a token from the api server, and this token follows the same config chain for the host except that there is no fallback. To implement login, the `cargo login` command is used. With 0 arguments, the command will request that a site be visited for a login token, and with an argument it will set the argument as the new login token. The `util::config` module was modified to allow writing configuration as well as reading it. The support is a little lacking in that comments are blown away, but the support is there at least. # RegistrySource An implementation of `RegistrySource` has been created (deleting the old `DummyRegistrySource`). This implementation only needs a URL to be constructed, and it is assumed that the URL is running an instance of the cargo registry. ## RegistrySource::update Currently this will unconditionally update the registry's index (a git repository). Tuning is necessary to prevent updating the index each time (more coming soon). ## RegistrySource::query This is called in the resolve phase of cargo. This function is given a dependency to query for, and the source will simply look into the index to see if any package with the name is present. If found, the package's index file will be loaded and parsed into a list of summaries. The main optimization of this function is to not require the entire registry to ever be resident in memory. Instead, only necessary packages are loaded into memory and parsed. ## RegistrySource::download This is also called during the resolve phase of cargo, but only when a package has been selected to be built (actually resolved). This phase of the source will actually download and unpack the tarball for the package. Currently a configuration file is located in the root of a registry's index describing the root url to download packages from. This function is optimized for two different metrics: 1. If a tarball is downloaded, it is not downloaded again. It is assumed that once a tarball is successfully downloaded it will never change. 2. If the unpacking destination has a `.cargo-ok` file, it is assumed that the unpacking has already occurred and does not need to happen again. With these in place, a rebuild should take almost no time at all. ## RegistrySource::get This function is simply implemented in terms of a PathSource's `get` function by creating a `PathSource` for all unpacked tarballs as part of the `download` stage. ## Filesystem layout There are a few new directories as part of the `.cargo` home folder: * `.cargo/registry/index/$hostname-$hash` - This is the directory containing the actual index of the registry. `$hostname` comes from its url, and `$hash` is the hash of the entire url. * `.cargo/registry/cache/$hostname-$hash/$pkg-$vers.tar.gz` - This is a directory used to cache the downloads of packages from the registry. * `.cargo/registry/src/$hostname-$hash/$pkg-$vers` - This is the location of the unpacked packages. They will be compiled from this location. # New Dependencies Cargo has picked up a new dependency on the `curl-rust` package in order to send HTTP requests to the registry as well as send HTTP requests to download tarballs.
2014-07-18 15:40:45 +00:00
}
2020-02-18 02:46:48 +00:00
impl fmt::Display for VerboseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.inner.fmt(f)
}
}
Implement a registry source # cargo upload The cargo-upload command will take the local package and upload it to the specified registry. The local package is uploaded as a tarball compressed with gzip under maximum compression. Most of this is done by just delegating to `cargo package` The host to upload to is specified, in order of priority, by a command line `--host` flag, the `registry.host` config key, and then the default registry. The default registry is still `example.com` The registry itself is still a work in progress, but the general plumbing for a command such as this would look like: 1. Ensure the local package has been compressed into an archive. 2. Fetch the relevant registry and login token from config files. 3. Ensure all dependencies for a package are listed as coming from the same registry. 4. Upload the archive to the registry with the login token. 5. The registry will verify the package is under 2MB (configurable). 6. The registry will upload the archive to S3, calculating a checksum in the process. 7. The registry will add an entry to the registry's index (a git repository). The entry will include the name of the package, the version uploaded, the checksum of the upload, and then the list of dependencies (name/version req) 8. The local `cargo upload` command will succeed. # cargo login Uploading requires a token from the api server, and this token follows the same config chain for the host except that there is no fallback. To implement login, the `cargo login` command is used. With 0 arguments, the command will request that a site be visited for a login token, and with an argument it will set the argument as the new login token. The `util::config` module was modified to allow writing configuration as well as reading it. The support is a little lacking in that comments are blown away, but the support is there at least. # RegistrySource An implementation of `RegistrySource` has been created (deleting the old `DummyRegistrySource`). This implementation only needs a URL to be constructed, and it is assumed that the URL is running an instance of the cargo registry. ## RegistrySource::update Currently this will unconditionally update the registry's index (a git repository). Tuning is necessary to prevent updating the index each time (more coming soon). ## RegistrySource::query This is called in the resolve phase of cargo. This function is given a dependency to query for, and the source will simply look into the index to see if any package with the name is present. If found, the package's index file will be loaded and parsed into a list of summaries. The main optimization of this function is to not require the entire registry to ever be resident in memory. Instead, only necessary packages are loaded into memory and parsed. ## RegistrySource::download This is also called during the resolve phase of cargo, but only when a package has been selected to be built (actually resolved). This phase of the source will actually download and unpack the tarball for the package. Currently a configuration file is located in the root of a registry's index describing the root url to download packages from. This function is optimized for two different metrics: 1. If a tarball is downloaded, it is not downloaded again. It is assumed that once a tarball is successfully downloaded it will never change. 2. If the unpacking destination has a `.cargo-ok` file, it is assumed that the unpacking has already occurred and does not need to happen again. With these in place, a rebuild should take almost no time at all. ## RegistrySource::get This function is simply implemented in terms of a PathSource's `get` function by creating a `PathSource` for all unpacked tarballs as part of the `download` stage. ## Filesystem layout There are a few new directories as part of the `.cargo` home folder: * `.cargo/registry/index/$hostname-$hash` - This is the directory containing the actual index of the registry. `$hostname` comes from its url, and `$hash` is the hash of the entire url. * `.cargo/registry/cache/$hostname-$hash/$pkg-$vers.tar.gz` - This is a directory used to cache the downloads of packages from the registry. * `.cargo/registry/src/$hostname-$hash/$pkg-$vers` - This is the location of the unpacked packages. They will be compiled from this location. # New Dependencies Cargo has picked up a new dependency on the `curl-rust` package in order to send HTTP requests to the registry as well as send HTTP requests to download tarballs.
2014-07-18 15:40:45 +00:00
2020-02-18 02:46:48 +00:00
// =============================================================================
// Internal error
/// An unexpected, internal error.
///
/// This should only be used for unexpected errors. It prints a message asking
/// the user to file a bug report.
pub struct InternalError {
inner: Error,
}
impl InternalError {
pub fn new(inner: Error) -> InternalError {
InternalError { inner }
}
}
impl std::error::Error for InternalError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.inner.source()
}
}
impl fmt::Debug for InternalError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.inner.fmt(f)
}
}
impl fmt::Display for InternalError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.inner.fmt(f)
}
}
// =============================================================================
// Manifest error
/// Error wrapper related to a particular manifest and providing it's path.
///
/// This error adds no displayable info of it's own.
2018-10-09 13:05:10 +00:00
pub struct ManifestError {
cause: Error,
manifest: PathBuf,
}
impl ManifestError {
pub fn new<E: Into<Error>>(cause: E, manifest: PathBuf) -> Self {
Self {
cause: cause.into(),
manifest,
}
2018-10-09 13:05:10 +00:00
}
pub fn manifest_path(&self) -> &PathBuf {
&self.manifest
}
/// Returns an iterator over the `ManifestError` chain of causes.
///
/// So if this error was not caused by another `ManifestError` this will be empty.
pub fn manifest_causes(&self) -> ManifestCauses<'_> {
ManifestCauses { current: self }
}
2018-10-09 13:05:10 +00:00
}
impl std::error::Error for ManifestError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.cause.source()
2018-10-09 13:05:10 +00:00
}
}
impl fmt::Debug for ManifestError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2018-10-09 13:05:10 +00:00
self.cause.fmt(f)
}
}
impl fmt::Display for ManifestError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2018-10-09 13:05:10 +00:00
self.cause.fmt(f)
}
}
/// An iterator over the `ManifestError` chain of causes.
pub struct ManifestCauses<'a> {
current: &'a ManifestError,
}
impl<'a> Iterator for ManifestCauses<'a> {
type Item = &'a ManifestError;
fn next(&mut self) -> Option<Self::Item> {
self.current = self.current.cause.downcast_ref()?;
Some(self.current)
}
}
impl<'a> ::std::iter::FusedIterator for ManifestCauses<'a> {}
// =============================================================================
// Cargo test errors.
/// Error when testcases fail
#[derive(Debug)]
pub struct CargoTestError {
pub test: Test,
pub desc: String,
pub code: Option<i32>,
pub causes: Vec<ProcessError>,
}
impl fmt::Display for CargoTestError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.desc.fmt(f)
}
}
impl std::error::Error for CargoTestError {}
#[derive(Debug)]
pub enum Test {
Multiple,
Doc,
2018-03-14 15:17:44 +00:00
UnitTest {
kind: TargetKind,
name: String,
pkg_name: String,
},
}
impl CargoTestError {
pub fn new(test: Test, errors: Vec<ProcessError>) -> Self {
if errors.is_empty() {
panic!("Cannot create CargoTestError from empty Vec")
}
2018-03-14 15:17:44 +00:00
let desc = errors
.iter()
.map(|error| error.desc.clone())
.collect::<Vec<String>>()
.join("\n");
CargoTestError {
test,
desc,
code: errors[0].code,
causes: errors,
}
}
2020-03-19 22:34:12 +00:00
pub fn hint(&self, ws: &Workspace<'_>, opts: &CompileOptions) -> String {
2017-09-22 13:56:47 +00:00
match self.test {
2018-03-14 15:17:44 +00:00
Test::UnitTest {
ref kind,
ref name,
ref pkg_name,
} => {
let pkg_info = if opts.spec.needs_spec_flag(ws) {
format!("-p {} ", pkg_name)
} else {
String::new()
};
match *kind {
2018-03-14 15:17:44 +00:00
TargetKind::Bench => {
format!("test failed, to rerun pass '{}--bench {}'", pkg_info, name)
}
TargetKind::Bin => {
format!("test failed, to rerun pass '{}--bin {}'", pkg_info, name)
}
TargetKind::Lib(_) => format!("test failed, to rerun pass '{}--lib'", pkg_info),
TargetKind::Test => {
format!("test failed, to rerun pass '{}--test {}'", pkg_info, name)
}
TargetKind::ExampleBin | TargetKind::ExampleLib(_) => {
format!("test failed, to rerun pass '{}--example {}", pkg_info, name)
}
_ => "test failed.".into(),
}
2018-03-14 15:17:44 +00:00
}
2017-09-22 13:56:47 +00:00
Test::Doc => "test failed, to rerun pass '--doc'".into(),
2018-03-14 15:17:44 +00:00
_ => "test failed.".into(),
}
}
}
// =============================================================================
// CLI errors
pub type CliResult = Result<(), CliError>;
2015-01-23 18:42:29 +00:00
#[derive(Debug)]
2020-02-18 02:46:48 +00:00
/// The CLI error is the error type used at Cargo's CLI-layer.
///
/// All errors from the lib side of Cargo will get wrapped with this error.
/// Other errors (such as command-line argument validation) will create this
/// directly.
pub struct CliError {
2020-02-18 02:46:48 +00:00
/// The error to display. This can be `None` in rare cases to exit with a
/// code without displaying a message. For example `cargo run -q` where
/// the resulting process exits with a nonzero code (on Windows), or an
/// external subcommand that exits nonzero (we assume it printed its own
/// message).
pub error: Option<anyhow::Error>,
2020-02-18 02:46:48 +00:00
/// The process exit code.
2018-03-14 15:17:44 +00:00
pub exit_code: i32,
}
impl CliError {
pub fn new(error: anyhow::Error, code: i32) -> CliError {
2018-03-14 15:17:44 +00:00
CliError {
error: Some(error),
exit_code: code,
}
}
pub fn code(code: i32) -> CliError {
2018-03-14 15:17:44 +00:00
CliError {
error: None,
exit_code: code,
}
}
}
impl From<anyhow::Error> for CliError {
fn from(err: anyhow::Error) -> CliError {
CliError::new(err, 101)
2015-02-06 07:27:53 +00:00
}
}
2018-03-09 07:43:00 +00:00
impl From<clap::Error> for CliError {
fn from(err: clap::Error) -> CliError {
let code = if err.use_stderr() { 1 } else { 0 };
CliError::new(err.into(), code)
}
}
// =============================================================================
// Construction helpers
pub fn internal<S: fmt::Display>(error: S) -> anyhow::Error {
2020-02-18 02:46:48 +00:00
InternalError::new(anyhow::format_err!("{}", error)).into()
}