1#![cfg_attr(test, deny(warnings))]
2#![warn(rust_2018_idioms)]
3#![allow(clippy::boxed_local)] #![allow(clippy::cyclomatic_complexity)] #![allow(clippy::derive_hash_xor_eq)] #![allow(clippy::explicit_into_iter_loop)] #![allow(clippy::explicit_iter_loop)] #![allow(clippy::identity_op)] #![allow(clippy::implicit_hasher)] #![allow(clippy::large_enum_variant)] #![allow(clippy::redundant_closure_call)] #![allow(clippy::too_many_arguments)] #![allow(clippy::type_complexity)] #![allow(clippy::wrong_self_convention)] use 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 pub commit_info: Option<CommitInfo>,
49 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 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 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 for err in cargo_err.iter_causes() {
146 print(&err.to_string(), shell);
147 }
148 } else {
149 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 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 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 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}