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
//! Consult [`README.md`](https://crates.io/crates/ci-cargo).
extern crate alloc;
/// Functionality related to parsing CLI arguments.
mod args;
/// Functionality related to running `cargo`.
mod cargo;
/// Functionality related to `Cargo.toml` parsing.
mod manifest;
/// Contains a `const bool` that is `true` iff `rustup` is supported by the platform.
mod rustup;
use args::{ArgsErr, HELP_MSG, MetaCmd};
use cargo::{CargoErr, Options, Toolchain, ToolchainErr};
use manifest::{Manifest, ManifestErr};
use std::{
collections::HashSet,
env,
fs::{self, File, TryLockError},
io::{self, BufWriter, Error, Read as _, Write as _},
path::{Path, PathBuf},
process::ExitCode,
};
/// Application error.
enum E {
/// Error related to the passed arguments.
Args(ArgsErr),
/// Error getting the current directory.
CurDir(Error),
/// Error looking for `Cargo.toml`.
CargoTomlIo(Error, PathBuf),
/// Error when `Cargo.toml` could not be found.
///
/// Note this is not returned when `--dir` is passed.
CargoTomlDoesNotExist(PathBuf),
/// Error canonicalizing `--dir`.
CanonicalizePath(Error, PathBuf),
/// Error setting the working directory.
SetDir(Error, PathBuf),
/// Error reading `Cargo.toml`.
CargoTomlRead(Error, PathBuf),
/// Error acquiring shared lock on `Cargo.toml`.
CargoTomlLock(TryLockError, PathBuf),
/// Error when `Cargo.toml` length does not match the length we read.
CargoTomlLenMismatch(PathBuf),
/// Error related to extracting the necessary data from `Cargo.toml`.
Manifest(Box<ManifestErr>),
/// Error looking for `rust-toolchain.toml`.
RustToolchainTomlIo(Error, PathBuf),
/// Error when `--ignore-msrv` was passed when using the `stable` toolchain.
IgnoreMsrvStable,
/// Error from `Msrv::compare_to_other`.
Toolchain(Box<ToolchainErr>),
/// Variant returned where there are too many features to generate the power set on.
TooManyFeatures(PathBuf),
/// Unable to write non-terminating messages to stderr.
StdErr,
/// Unable to write the help message to stdout.
Help(Error),
/// Unable to write the version message to stdout.
Version(Error),
/// `cargo` erred.
Cargo(Box<CargoErr>),
/// Unable to write the summary message to stdout.
Summary(Error),
}
impl E {
/// Writes `self` to `stderr` before returning [`ExitCode::FAILURE`].
fn into_exit_code(self) -> ExitCode {
let mut stderr = io::stderr().lock();
match self {
Self::Args(e) => e.write(stderr),
Self::CurDir(err) => {
writeln!(
stderr,
"There was an error getting the working directory: {err}."
)
}
Self::CargoTomlIo(err, p) => {
writeln!(stderr, "There was an error looking for Cargo.toml in {} and its ancestor directories: {err}.", p.display())
}
Self::CargoTomlDoesNotExist(p) => {
writeln!(stderr, "Cargo.toml does not exist in {} nor its ancestor directories.", p.display())
}
Self::CanonicalizePath(err, p) => {
writeln!(
stderr,
"There was an error canonicalizing the path {}: {err}.",
p.display()
)
}
Self::SetDir(err, p) => {
writeln!(
stderr,
"There was an error changing the working directory to {}: {err}.", p.display()
)
}
Self::CargoTomlRead(err, p) => {
writeln!(stderr, "There was an error reading {}: {err}.", p.display())
}
Self::CargoTomlLock(err, p) => {
writeln!(stderr, "There was an error acquiring a shared lock on {}: {err}.", p.display())
}
Self::CargoTomlLenMismatch(p) => writeln!(stderr, "The number of bytes read from {} does not match the length reported from the file system.", p.display()),
Self::Manifest(e) => e.write(stderr),
Self::RustToolchainTomlIo(err, p) => {
writeln!(
stderr,
"There was an error looking for rust-toolchain.toml in {} and its ancestor directories: {err}.", p.display()
)
}
Self::IgnoreMsrvStable => writeln!(stderr, "--ignore-msrv was passed when using the stable toolchain."),
Self::Toolchain(e) => e.write(stderr),
Self::TooManyFeatures(p) => writeln!(stderr, "There are too many features defined in {}. The max number of features allowed is the number of bits that make up a pointer.", p.display()),
Self::StdErr => Ok(()),
Self::Help(err) => writeln!(
stderr,
"There was an error writing ci-cargo help to stdout: {err}."
),
Self::Version(err) => writeln!(
stderr,
"There was an error writing ci-cargo version to stdout: {err}."
),
Self::Cargo(e) => e.write(stderr),
Self::Summary(err) => writeln!(
stderr,
"There was an error writing the summary to stdout: {err}."
),
}
.map_or(ExitCode::FAILURE, |()| ExitCode::FAILURE)
}
}
/// `"Cargo.toml"`.
fn cargo_toml() -> &'static Path {
Path::new("Cargo.toml")
}
/// `"rust-toolchain.toml"`.
fn rust_toolchain_toml() -> &'static Path {
Path::new("rust-toolchain.toml")
}
/// Finds `file` in `cur_dir` or its ancestor directories returning `true` iff `file` exists. Searching is
/// done from child directories up.
///
/// We make this recursive in the rare (impossible?) case that traversal becomes circular; in which case,
/// we want a stack overflow to occur.
fn get_path_of_file(cur_dir: &mut PathBuf, file: &Path) -> Result<bool, Error> {
cur_dir.push(file);
fs::exists(&cur_dir).and_then(|exists| {
// Remove `file`.
_ = cur_dir.pop();
if exists {
Ok(true)
} else if cur_dir.pop() {
get_path_of_file(cur_dir, file)
} else {
Ok(false)
}
})
}
/// Current version of this crate.
const VERSION: &str = concat!("ci-cargo ", env!("CARGO_PKG_VERSION"));
#[expect(
clippy::arithmetic_side_effects,
reason = "comment justifies correctness"
)]
#[expect(
clippy::verbose_file_reads,
reason = "false positive since we want to lock the file"
)]
fn main() -> ExitCode {
MetaCmd::from_args(env::args_os()).map_err(E::Args).and_then(|meta_cmd| {
match meta_cmd {
MetaCmd::Help => io::stdout().lock().write_all(HELP_MSG.as_bytes()).map_err(E::Help),
MetaCmd::Version => writeln!(io::stdout().lock(), "{VERSION}").map_err(E::Version),
MetaCmd::Cargo(cmd, mut opts) => opts.exec_dir.map_or_else(
|| env::current_dir().map_err(E::CurDir).and_then(|mut path| {
let search_start = path.clone();
get_path_of_file(&mut path, cargo_toml()).map_err(|e| E::CargoTomlIo(e, search_start.clone())).and_then(|exists| if exists { Ok(path) } else { Err(E::CargoTomlDoesNotExist(search_start)) })
}),
|path| fs::canonicalize(&path).map_err(|e| E::CanonicalizePath(e, path)),
).and_then(|mut cur_dir| env::set_current_dir(&cur_dir).map_err(|e| E::SetDir(e, cur_dir.clone())).and_then(|()| {
cur_dir.push(cargo_toml());
let mut skip_no_feats = false;
// `ignore_features` is unique, so we simply need to check for the first
// occurrence of an empty string and remove it. We do this _before_ calling
// `Manifest::from_toml` since the empty string is treated special in that it
// represents the empty set of features. It is not the name of a feature. Note
// `cargo` disallows an empty string to be a feature name, so there is no fear
// of misinterpeting it.
if let Err(ig_idx) = opts.ignore_features.iter().try_fold(0, |idx, feat| {
if feat.is_empty() {
Err(idx)
} else {
// Clearly can't overflow since this is the index. Caps at `isize::MAX`.
Ok(idx + 1)
}
}) {
skip_no_feats = true;
drop(opts.ignore_features.swap_remove(ig_idx));
}
File::options().read(true).open(&cur_dir).map_err(|e| E::CargoTomlRead(e, cur_dir.clone())).and_then(|mut toml_file| {
toml_file.try_lock_shared().map_err(|e| E::CargoTomlLock(e, cur_dir.clone())).and_then(|()| {
toml_file.metadata().map_err(|e| E::CargoTomlRead(e, cur_dir.clone())).and_then(|meta| {
let meta_len = usize::try_from(meta.len()).unwrap_or(usize::MAX);
let mut toml_utf8 = Vec::with_capacity(meta_len);
toml_file.read_to_end(&mut toml_utf8).map_err(|e| E::CargoTomlRead(e, cur_dir.clone())).and_then(|len| {
drop(toml_file);
if meta_len == len {
String::from_utf8(toml_utf8).map_err(|e| E::CargoTomlRead(Error::other(e), cur_dir.clone())).and_then(|toml| {
Manifest::from_toml(toml, opts.allow_implied_features, &cur_dir, &opts.ignore_features).map_err(E::Manifest).and_then(|man| {
if opts.default_toolchain || (!rustup::SUPPORTED && opts.rustup_home.is_none()) {
Ok(Toolchain::Default(opts.ignore_msrv))
} else {
let mut cargo_toml_path = cur_dir.clone();
_ = cargo_toml_path.pop();
get_path_of_file(&mut cargo_toml_path, rust_toolchain_toml()).map_err(|e| E::RustToolchainTomlIo(e, cargo_toml_path)).and_then(|rust_toolchain_exists| if rust_toolchain_exists { Ok(Toolchain::Default(opts.ignore_msrv)) } else if opts.ignore_msrv { Err(E::IgnoreMsrvStable) } else { Ok(Toolchain::Stable) })
}.and_then(|toolchain| man.package().msrv().map_or(Ok(None), |msrv| if !opts.skip_msrv && (rustup::SUPPORTED || opts.rustup_home.is_some()) {
msrv.compare_to_other(matches!(toolchain, Toolchain::Default(_)), opts.rustup_home.as_deref(), &opts.cargo_path, opts.cargo_home.as_deref()).map_err(E::Toolchain)
} else {
Ok(None)
}).and_then(|msrv_string| {
let default_feature_does_not_exist = !man.features().contains_default();
man.features().power_set(skip_no_feats).map_err(|_e| E::TooManyFeatures(cur_dir)).and_then(|power_set_opt| power_set_opt.map_or_else(|| Ok(()), |mut power_set| {
let mut non_term_errs = HashSet::new();
cmd.run(Options { toolchain, rustup_home: opts.rustup_home, cargo_path: opts.cargo_path, cargo_home: opts.cargo_home, package_name: man.package().name(), color: opts.color, ignore_compile_errors: opts.ignore_compile_errors, default_feature_does_not_exist, non_terminating_errors: &mut non_term_errs, }, msrv_string.as_deref(), &mut power_set, opts.progress).map_err(E::Cargo).and_then(|()| {
if non_term_errs.is_empty() {
Ok(())
} else {
// `StderrLock` is not buffered.
let mut stderr = BufWriter::new(io::stderr().lock());
non_term_errs.into_iter().try_fold((), |(), msg| stderr.write_all(msg.as_bytes())).and_then(|()| stderr.flush()).map_err(|_e| E::StdErr)
}
}).and_then(|()| {
if opts.summary {
let mut stdout = io::stdout().lock();
if matches!(toolchain, Toolchain::Stable) {
if let Some(ref msrv_val) = msrv_string {
writeln!(stdout, "Toolchains used: cargo +stable and cargo {msrv_val}")
} else {
writeln!(stdout, "Toolchain used: cargo +stable")
}
} else if let Some(ref msrv_val) = msrv_string {
writeln!(stdout, "Toolchains used: cargo and cargo {msrv_val}")
} else {
writeln!(stdout, "Toolchain used: cargo")
}.and_then(|()| {
writeln!(stdout, "Features used:").and_then(|()| {
power_set.reset();
while let Some(features) = power_set.next_set() {
writeln!(stdout, "{}", if features.is_empty() { "<none>" } else { features })?;
}
Ok(())
})
}).map_err(E::Summary)
} else {
Ok(())
}
})
}))
}))
})
})
} else {
Err(E::CargoTomlLenMismatch(cur_dir))
}
})
})
})
})
}))
}
}).map_or_else(E::into_exit_code, |()| ExitCode::SUCCESS)
}