Skip to main content

cargo/
lib.rs

1#![cfg_attr(test, deny(warnings))]
2#![warn(rust_2018_idioms)]
3// while we're getting used to 2018
4// Clippy isn't enforced by CI, and know that @alexcrichton isn't a fan :)
5#![allow(clippy::boxed_local)] // bug rust-lang-nursery/rust-clippy#1123
6#![allow(clippy::cyclomatic_complexity)] // large project
7#![allow(clippy::derive_hash_xor_eq)] // there's an intentional incoherence
8#![allow(clippy::explicit_into_iter_loop)] // explicit loops are clearer
9#![allow(clippy::explicit_iter_loop)] // explicit loops are clearer
10#![allow(clippy::identity_op)] // used for vertical alignment
11#![allow(clippy::implicit_hasher)] // large project
12#![allow(clippy::large_enum_variant)] // large project
13#![allow(clippy::redundant_closure_call)] // closures over try catch blocks
14#![allow(clippy::too_many_arguments)] // large project
15#![allow(clippy::type_complexity)] // there's an exceptionally complex type
16#![allow(clippy::wrong_self_convention)] // perhaps Rc should be special cased in Clippy?
17
18use std::fmt;
19
20use failure::Error;
21use log::debug;
22use serde::ser;
23
24use crate::core::shell::Verbosity::Verbose;
25use crate::core::Shell;
26
27pub use crate::util::errors::Internal;
28pub use crate::util::{CargoResult, CliError, CliResult, Config};
29
30pub const CARGO_ENV: &str = "CARGO";
31
32#[macro_use]
33mod macros;
34
35pub mod core;
36pub mod ops;
37pub mod sources;
38pub mod util;
39
40pub struct CommitInfo {
41    pub short_commit_hash: String,
42    pub commit_hash: String,
43    pub commit_date: String,
44}
45
46pub struct CfgInfo {
47    // Information about the git repository we may have been built from.
48    pub commit_info: Option<CommitInfo>,
49    // The release channel we were built for.
50    pub release_channel: String,
51}
52
53pub struct VersionInfo {
54    pub major: u8,
55    pub minor: u8,
56    pub patch: u8,
57    pub pre_release: Option<String>,
58    // Information that's only available when we were built with
59    // configure/make, rather than cargo itself.
60    pub cfg_info: Option<CfgInfo>,
61}
62
63impl fmt::Display for VersionInfo {
64    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65        write!(f, "cargo {}.{}.{}", self.major, self.minor, self.patch)?;
66        if let Some(channel) = self.cfg_info.as_ref().map(|ci| &ci.release_channel) {
67            if channel != "stable" {
68                write!(f, "-{}", channel)?;
69                let empty = String::new();
70                write!(f, "{}", self.pre_release.as_ref().unwrap_or(&empty))?;
71            }
72        };
73
74        if let Some(ref cfg) = self.cfg_info {
75            if let Some(ref ci) = cfg.commit_info {
76                write!(f, " ({} {})", ci.short_commit_hash, ci.commit_date)?;
77            }
78        };
79        Ok(())
80    }
81}
82
83pub fn print_json<T: ser::Serialize>(obj: &T) {
84    let encoded = serde_json::to_string(&obj).unwrap();
85    println!("{}", encoded);
86}
87
88pub fn exit_with_error(err: CliError, shell: &mut Shell) -> ! {
89    debug!("exit_with_error; err={:?}", err);
90    if let Some(ref err) = err.error {
91        if let Some(clap_err) = err.downcast_ref::<clap::Error>() {
92            clap_err.exit()
93        }
94    }
95
96    let CliError {
97        error,
98        exit_code,
99        unknown,
100    } = err;
101    // exit_code == 0 is non-fatal error, e.g. docopt version info
102    let fatal = exit_code != 0;
103
104    let hide = unknown && shell.verbosity() != Verbose;
105
106    if let Some(error) = error {
107        if hide {
108            drop(shell.error("An unknown error occurred"))
109        } else if fatal {
110            drop(shell.error(&error))
111        } else {
112            println!("{}", error);
113        }
114
115        if !handle_cause(&error, shell) || hide {
116            drop(writeln!(
117                shell.err(),
118                "\nTo learn more, run the command again \
119                 with --verbose."
120            ));
121        }
122    }
123
124    std::process::exit(exit_code)
125}
126
127pub fn handle_error(err: &failure::Error, shell: &mut Shell) {
128    debug!("handle_error; err={:?}", err);
129
130    let _ignored_result = shell.error(err);
131    handle_cause(err, shell);
132}
133
134fn handle_cause(cargo_err: &Error, shell: &mut Shell) -> bool {
135    fn print(error: &str, shell: &mut Shell) {
136        drop(writeln!(shell.err(), "\nCaused by:"));
137        drop(writeln!(shell.err(), "  {}", error));
138    }
139
140    let verbose = shell.verbosity();
141
142    if verbose == Verbose {
143        // The first error has already been printed to the shell
144        // Print all remaining errors
145        for err in cargo_err.iter_causes() {
146            print(&err.to_string(), shell);
147        }
148    } else {
149        // The first error has already been printed to the shell
150        // Print remaining errors until one marked as Internal appears
151        for err in cargo_err.iter_causes() {
152            if err.downcast_ref::<Internal>().is_some() {
153                return false;
154            }
155
156            print(&err.to_string(), shell);
157        }
158    }
159
160    true
161}
162
163pub fn version() -> VersionInfo {
164    macro_rules! option_env_str {
165        ($name:expr) => {
166            option_env!($name).map(|s| s.to_string())
167        };
168    }
169
170    // So this is pretty horrible...
171    // There are two versions at play here:
172    //   - version of cargo-the-binary, which you see when you type `cargo --version`
173    //   - version of cargo-the-library, which you download from crates.io for use
174    //     in your packages.
175    //
176    // We want to make the `binary` version the same as the corresponding Rust/rustc release.
177    // At the same time, we want to keep the library version at `0.x`, because Cargo as
178    // a library is (and probably will always be) unstable.
179    //
180    // Historically, Cargo used the same version number for both the binary and the library.
181    // Specifically, rustc 1.x.z was paired with cargo 0.x+1.w.
182    // We continue to use this scheme for the library, but transform it to 1.x.w for the purposes
183    // of `cargo --version`.
184    let major = 1;
185    let minor = env!("CARGO_PKG_VERSION_MINOR").parse::<u8>().unwrap() - 1;
186    let patch = env!("CARGO_PKG_VERSION_PATCH").parse::<u8>().unwrap();
187
188    match option_env!("CFG_RELEASE_CHANNEL") {
189        // We have environment variables set up from configure/make.
190        Some(_) => {
191            let commit_info = option_env!("CFG_COMMIT_HASH").map(|s| CommitInfo {
192                commit_hash: s.to_string(),
193                short_commit_hash: option_env_str!("CFG_SHORT_COMMIT_HASH").unwrap(),
194                commit_date: option_env_str!("CFG_COMMIT_DATE").unwrap(),
195            });
196            VersionInfo {
197                major,
198                minor,
199                patch,
200                pre_release: option_env_str!("CARGO_PKG_VERSION_PRE"),
201                cfg_info: Some(CfgInfo {
202                    release_channel: option_env_str!("CFG_RELEASE_CHANNEL").unwrap(),
203                    commit_info,
204                }),
205            }
206        }
207        // We are being compiled by Cargo itself.
208        None => VersionInfo {
209            major,
210            minor,
211            patch,
212            pre_release: option_env_str!("CARGO_PKG_VERSION_PRE"),
213            cfg_info: None,
214        },
215    }
216}