1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
use std::{
io,
path::PathBuf,
process::{ExitCode, ExitStatus, Termination},
};
use binstalk_downloader::{
download::DownloadError, gh_api_client::GhApiError, remote::Error as RemoteError,
};
use cargo_toml::Error as CargoTomlError;
use compact_str::CompactString;
use miette::{Diagnostic, Report};
use thiserror::Error;
use tokio::task;
use tracing::{error, warn};
#[derive(Debug, Error)]
#[error("crates.io API error for {crate_name}: {err}")]
pub struct CratesIoApiError {
pub crate_name: CompactString,
#[source]
pub err: RemoteError,
}
#[derive(Debug, Error)]
#[error("version string '{v}' is not semver: {err}")]
pub struct VersionParseError {
pub v: CompactString,
#[source]
pub err: semver::Error,
}
#[derive(Debug, Diagnostic, Error)]
#[error("For crate {crate_name}: {err}")]
pub struct CrateContextError {
crate_name: CompactString,
#[source]
#[diagnostic(transparent)]
err: BinstallError,
}
#[derive(Debug, Error)]
#[error("Invalid pkg-url {pkg_url} for {crate_name}@{version} on {target}: {reason}")]
pub struct InvalidPkgFmtError {
pub crate_name: CompactString,
pub version: CompactString,
pub target: String,
pub pkg_url: String,
pub reason: &'static str,
}
/// Error kinds emitted by cargo-binstall.
#[derive(Error, Diagnostic, Debug)]
#[non_exhaustive]
pub enum BinstallError {
/// Internal: a task could not be joined.
///
/// - Code: `binstall::internal::task_join`
/// - Exit: 17
#[error(transparent)]
#[diagnostic(severity(error), code(binstall::internal::task_join))]
TaskJoinError(#[from] task::JoinError),
/// The installation was cancelled by a user at a confirmation prompt,
/// or user send a ctrl_c on all platforms or
/// `SIGINT`, `SIGHUP`, `SIGTERM` or `SIGQUIT` on unix to the program.
///
/// - Code: `binstall::user_abort`
/// - Exit: 32
#[error("installation cancelled by user")]
#[diagnostic(severity(info), code(binstall::user_abort))]
UserAbort,
/// A URL is invalid.
///
/// This may be the result of a template in a Cargo manifest.
///
/// - Code: `binstall::url_parse`
/// - Exit: 65
#[error("Failed to parse url: {0}")]
#[diagnostic(severity(error), code(binstall::url_parse))]
UrlParse(#[from] url::ParseError),
/// Failed to parse template.
///
/// - Code: `binstall::template`
/// - Exit: 67
#[error(transparent)]
#[diagnostic(severity(error), code(binstall::template))]
#[source_code(transparent)]
#[label(transparent)]
TemplateParseError(
#[from]
#[diagnostic_source]
leon::ParseError,
),
/// Failed to render template.
///
/// - Code: `binstall::template`
/// - Exit: 69
#[error("Failed to render template: {0}")]
#[diagnostic(severity(error), code(binstall::template))]
#[source_code(transparent)]
#[label(transparent)]
TemplateRenderError(
#[from]
#[diagnostic_source]
leon::RenderError,
),
/// Failed to download or failed to decode the body.
///
/// - Code: `binstall::download`
/// - Exit: 68
#[error(transparent)]
#[diagnostic(severity(error), code(binstall::download))]
Download(#[from] DownloadError),
/// A subprocess failed.
///
/// This is often about cargo-install calls.
///
/// - Code: `binstall::subprocess`
/// - Exit: 70
#[error("subprocess {command} errored with {status}")]
#[diagnostic(severity(error), code(binstall::subprocess))]
SubProcess {
command: Box<str>,
status: ExitStatus,
},
/// A generic I/O error.
///
/// - Code: `binstall::io`
/// - Exit: 74
#[error("I/O Error: {0}")]
#[diagnostic(severity(error), code(binstall::io))]
Io(io::Error),
/// An error interacting with the crates.io API.
///
/// This could either be a "not found" or a server/transport error.
///
/// - Code: `binstall::crates_io_api`
/// - Exit: 76
#[error(transparent)]
#[diagnostic(
severity(error),
code(binstall::crates_io_api),
help("Check that the crate name you provided is correct.\nYou can also search for a matching crate at: https://lib.rs/search?q={}", .0.crate_name)
)]
CratesIoApi(#[from] Box<CratesIoApiError>),
/// The override path to the cargo manifest is invalid or cannot be resolved.
///
/// - Code: `binstall::cargo_manifest_path`
/// - Exit: 77
#[error("the --manifest-path is invalid or cannot be resolved")]
#[diagnostic(severity(error), code(binstall::cargo_manifest_path))]
CargoManifestPath,
/// A parsing or validation error in a cargo manifest.
///
/// This should be rare, as manifests are generally fetched from crates.io, which does its own
/// validation upstream. The most common failure will therefore be for direct repository access
/// and with the `--manifest-path` option.
///
/// - Code: `binstall::cargo_manifest`
/// - Exit: 78
#[error("Failed to parse cargo manifest: {0}")]
#[diagnostic(
severity(error),
code(binstall::cargo_manifest),
help("If you used --manifest-path, check the Cargo.toml syntax.")
)]
CargoManifest(Box<CargoTomlError>),
/// A version is not valid semver.
///
/// Note that we use the [`semver`] crate, which parses Cargo version syntax; this may be
/// somewhat stricter or very slightly different from other semver implementations.
///
/// - Code: `binstall::version::parse`
/// - Exit: 80
#[error(transparent)]
#[diagnostic(severity(error), code(binstall::version::parse))]
VersionParse(#[from] Box<VersionParseError>),
/// No available version matches the requirements.
///
/// This may be the case when using the `--version` option.
///
/// Note that using `--version 1.2.3` is interpreted as the requirement `=1.2.3`.
///
/// - Code: `binstall::version::mismatch`
/// - Exit: 82
#[error("no version matching requirement '{req}'")]
#[diagnostic(severity(error), code(binstall::version::mismatch))]
VersionMismatch { req: semver::VersionReq },
/// The crate@version syntax was used at the same time as the --version option.
///
/// You can't do that as it's ambiguous which should apply.
///
/// - Code: `binstall::conflict::version`
/// - Exit: 84
#[error("superfluous version specification")]
#[diagnostic(
severity(error),
code(binstall::conflict::version),
help("You cannot use both crate@version and the --version option. Remove one.")
)]
SuperfluousVersionOption,
/// No binaries were found for the crate.
///
/// When installing, either the binaries are specified in the crate's Cargo.toml, or they're
/// inferred from the crate layout (e.g. src/main.rs or src/bins/name.rs). If no binaries are
/// found through these methods, we can't know what to install!
///
/// - Code: `binstall::resolve::binaries`
/// - Exit: 86
#[error("no binaries specified nor inferred")]
#[diagnostic(
severity(error),
code(binstall::resolve::binaries),
help("This crate doesn't specify any binaries, so there's nothing to install.")
)]
UnspecifiedBinaries,
/// No viable targets were found.
///
/// When installing, we attempt to find which targets the host (your computer) supports, and
/// discover builds for these targets from the remote binary source. This error occurs when we
/// fail to discover the host's target.
///
/// You should in this case specify --target manually.
///
/// - Code: `binstall::targets::none_host`
/// - Exit: 87
#[error("failed to discovered a viable target from the host")]
#[diagnostic(
severity(error),
code(binstall::targets::none_host),
help("Try to specify --target")
)]
NoViableTargets,
/// Bin file is not found.
///
/// - Code: `binstall::binfile`
/// - Exit: 88
#[error("bin file {0} not found")]
#[diagnostic(severity(error), code(binstall::binfile))]
BinFileNotFound(PathBuf),
/// `Cargo.toml` of the crate does not have section "Package".
///
/// - Code: `binstall::cargo_manifest`
/// - Exit: 89
#[error("Cargo.toml of crate {0} does not have section \"Package\"")]
#[diagnostic(severity(error), code(binstall::cargo_manifest))]
CargoTomlMissingPackage(CompactString),
/// bin-dir configuration provided generates duplicate source path.
///
/// - Code: `binstall::cargo_manifest`
/// - Exit: 90
#[error("bin-dir configuration provided generates duplicate source path: {path}")]
#[diagnostic(severity(error), code(binstall::SourceFilePath))]
DuplicateSourceFilePath { path: PathBuf },
/// bin-dir configuration provided generates source path outside
/// of the temporary dir.
///
/// - Code: `binstall::cargo_manifest`
/// - Exit: 91
#[error(
"bin-dir configuration provided generates source path outside of the temporary dir: {path}"
)]
#[diagnostic(severity(error), code(binstall::SourceFilePath))]
InvalidSourceFilePath { path: PathBuf },
/// bin-dir configuration provided generates empty source path.
///
/// - Code: `binstall::cargo_manifest`
/// - Exit: 92
#[error("bin-dir configuration provided generates empty source path")]
#[diagnostic(severity(error), code(binstall::SourceFilePath))]
EmptySourceFilePath,
/// Fallback to `cargo-install` is disabled.
///
/// - Code: `binstall::no_fallback_to_cargo_install`
/// - Exit: 94
#[error("Fallback to cargo-install is disabled")]
#[diagnostic(severity(error), code(binstall::no_fallback_to_cargo_install))]
NoFallbackToCargoInstall,
/// Fallback to `cargo-install` is disabled.
///
/// - Code: `binstall::invalid_pkg_fmt`
/// - Exit: 95
#[error(transparent)]
#[diagnostic(severity(error), code(binstall::invalid_pkg_fmt))]
InvalidPkgFmt(Box<InvalidPkgFmtError>),
/// Request to GitHub Restful API failed
///
/// - Code: `binstall::gh_restful_api_failure`
/// - Exit: 96
#[error("Request to GitHub Restful API failed: {0}")]
#[diagnostic(severity(error), code(binstall::gh_restful_api_failure))]
GhApiErr(#[source] Box<GhApiError>),
/// A wrapped error providing the context of which crate the error is about.
#[error(transparent)]
#[diagnostic(transparent)]
CrateContext(Box<CrateContextError>),
}
impl BinstallError {
fn exit_number(&self) -> u8 {
use BinstallError::*;
let code: u8 = match self {
TaskJoinError(_) => 17,
UserAbort => 32,
UrlParse(_) => 65,
TemplateParseError(..) => 67,
TemplateRenderError(..) => 69,
Download(_) => 68,
SubProcess { .. } => 70,
Io(_) => 74,
CratesIoApi { .. } => 76,
CargoManifestPath => 77,
CargoManifest { .. } => 78,
VersionParse { .. } => 80,
VersionMismatch { .. } => 82,
SuperfluousVersionOption => 84,
UnspecifiedBinaries => 86,
NoViableTargets => 87,
BinFileNotFound(_) => 88,
CargoTomlMissingPackage(_) => 89,
DuplicateSourceFilePath { .. } => 90,
InvalidSourceFilePath { .. } => 91,
EmptySourceFilePath => 92,
NoFallbackToCargoInstall => 94,
InvalidPkgFmt(..) => 95,
GhApiErr(..) => 96,
CrateContext(context) => context.err.exit_number(),
};
// reserved codes
debug_assert!(code != 64 && code != 16 && code != 1 && code != 2 && code != 0);
code
}
/// The recommended exit code for this error.
///
/// This will never output:
/// - 0 (success)
/// - 1 and 2 (catchall and shell)
/// - 16 (binstall errors not handled here)
/// - 64 (generic error)
pub fn exit_code(&self) -> ExitCode {
self.exit_number().into()
}
/// Add crate context to the error
pub fn crate_context(self, crate_name: impl Into<CompactString>) -> Self {
Self::CrateContext(Box::new(CrateContextError {
err: self,
crate_name: crate_name.into(),
}))
}
}
impl Termination for BinstallError {
fn report(self) -> ExitCode {
let code = self.exit_code();
if let BinstallError::UserAbort = self {
warn!("Installation cancelled");
} else {
error!("Fatal error:\n{:?}", Report::new(self));
}
code
}
}
impl From<io::Error> for BinstallError {
fn from(err: io::Error) -> Self {
if err.get_ref().is_some() {
let kind = err.kind();
let inner = err
.into_inner()
.expect("err.get_ref() returns Some, so err.into_inner() should also return Some");
inner
.downcast()
.map(|b| *b)
.unwrap_or_else(|err| BinstallError::Io(io::Error::new(kind, err)))
} else {
BinstallError::Io(err)
}
}
}
impl From<BinstallError> for io::Error {
fn from(e: BinstallError) -> io::Error {
match e {
BinstallError::Io(io_error) => io_error,
e => io::Error::new(io::ErrorKind::Other, e),
}
}
}
impl From<RemoteError> for BinstallError {
fn from(e: RemoteError) -> Self {
DownloadError::from(e).into()
}
}
impl From<CargoTomlError> for BinstallError {
fn from(e: CargoTomlError) -> Self {
BinstallError::CargoManifest(Box::new(e))
}
}
impl From<InvalidPkgFmtError> for BinstallError {
fn from(e: InvalidPkgFmtError) -> Self {
BinstallError::InvalidPkgFmt(Box::new(e))
}
}
impl From<GhApiError> for BinstallError {
fn from(e: GhApiError) -> Self {
BinstallError::GhApiErr(Box::new(e))
}
}