cargo/lib.rs
1//! # Cargo as a library
2//!
3//! There are two places you can find API documentation of cargo-the-library,
4//!
5//! - <https://docs.rs/cargo>: targeted at external tool developers using cargo-the-library
6//! - Released with every rustc release
7//! - <https://doc.rust-lang.org/nightly/nightly-rustc/cargo>: targeted at cargo contributors
8//! - Updated on each update of the `cargo` submodule in `rust-lang/rust`
9//!
10//! > This library is maintained by the Cargo team, primarily for use by Cargo
11//! > and not intended for external use (except as a transitive dependency). This
12//! > crate may make major changes to its APIs. See [The Cargo Book:
13//! > External tools] for more on this topic.
14//!
15//! ## Overview
16//!
17//! Major components of cargo include:
18//!
19//! - [`ops`]:
20//! Every major operation is implemented here. Each command is a thin wrapper around ops.
21//! - [`ops::cargo_compile`]:
22//! This is the entry point for all the compilation commands. This is a
23//! good place to start if you want to follow how compilation starts and
24//! flows to completion.
25//! - [`ops::resolve`]:
26//! Top-level API for dependency and feature resolver (e.g. [`ops::resolve_ws`])
27//! - [`core::resolver`]: The core algorithm
28//! - [`core::compiler`]:
29//! This is the code responsible for running `rustc` and `rustdoc`.
30//! - [`core::compiler::build_context`]:
31//! The [`BuildContext`][core::compiler::BuildContext] is the result of the "front end" of the
32//! build process. This contains the graph of work to perform and any settings necessary for
33//! `rustc`. After this is built, the next stage of building is handled in
34//! [`BuildRunner`][core::compiler::BuildRunner].
35//! - [`core::compiler::build_runner`]:
36//! The `Context` is the mutable state used during the build process. This
37//! is the core of the build process, and everything is coordinated through
38//! this.
39//! - [`core::compiler::fingerprint`]:
40//! The `fingerprint` module contains all the code that handles detecting
41//! if a crate needs to be recompiled.
42//! - [`sources::source`]:
43//! The [`sources::source::Source`] trait is an abstraction over different sources of packages.
44//! Sources are uniquely identified by a [`core::SourceId`]. Sources are implemented in the [`sources`]
45//! directory.
46//! - [`diagnostics`]: Home of diagnostic [passes][diagnostics::passes] and their
47//! [rules][diagnostics::rules].
48//! - [`util`]:
49//! This directory contains generally-useful utility modules.
50//! - [`util::context`]:
51//! This directory contains the global application context.
52//! This includes the config parser which makes heavy use of
53//! [serde](https://serde.rs/) to merge and translate config values.
54//! The [`util::GlobalContext`] is usually accessed from the
55//! [`core::Workspace`]
56//! though references to it are scattered around for more convenient access.
57//! - [`util::toml`]:
58//! This directory contains the code for parsing `Cargo.toml` files.
59//! - [`ops::lockfile`]:
60//! This is where `Cargo.lock` files are loaded and saved.
61//!
62//! Related crates:
63//! - [`cargo-platform`](https://crates.io/crates/cargo-platform)
64//! ([nightly docs](https://doc.rust-lang.org/nightly/nightly-rustc/cargo_platform)):
65//! This library handles parsing `cfg` expressions.
66//! - [`cargo-util`](https://crates.io/crates/cargo-util)
67//! ([nightly docs](https://doc.rust-lang.org/nightly/nightly-rustc/cargo_util)):
68//! This contains general utility code that is shared between cargo and the testsuite
69//! - [`cargo-util-schemas`](https://crates.io/crates/cargo-util-schemas)
70//! ([nightly docs](https://doc.rust-lang.org/nightly/nightly-rustc/cargo_util_schemas)):
71//! This contains the serde schemas for cargo
72//! - [`crates-io`](https://crates.io/crates/crates-io)
73//! ([nightly docs](https://doc.rust-lang.org/nightly/nightly-rustc/crates_io)):
74//! This contains code for accessing the crates.io API.
75//! - [`home`](https://crates.io/crates/home):
76//! This library is shared between cargo and rustup and is used for finding their home directories.
77//! This is not directly depended upon with a `path` dependency; cargo uses the version from crates.io.
78//! It is intended to be versioned and published independently of Rust's release system.
79//! Whenever a change needs to be made, bump the version in Cargo.toml and `cargo publish` it manually, and then update cargo's `Cargo.toml` to depend on the new version.
80//! - [`rustfix`](https://crates.io/crates/rustfix)
81//! ([nightly docs](https://doc.rust-lang.org/nightly/nightly-rustc/rustfix)):
82//! This defines structures that represent fix suggestions from rustc,
83//! as well as generates "fixed" code from suggestions.
84//! Operations in `rustfix` are all in memory and won't write to disks.
85//! - [`cargo-test-support`](https://github.com/rust-lang/cargo/tree/master/crates/cargo-test-support)
86//! ([nightly docs](https://doc.rust-lang.org/nightly/nightly-rustc/cargo_test_support/index.html)):
87//! This contains a variety of code to support writing tests
88//! - [`cargo-test-macro`](https://github.com/rust-lang/cargo/tree/master/crates/cargo-test-macro)
89//! ([nightly docs](https://doc.rust-lang.org/nightly/nightly-rustc/cargo_test_macro/index.html)):
90//! This is the `#[cargo_test]` proc-macro used by the test suite to define tests.
91//! - [`credential`](https://github.com/rust-lang/cargo/tree/master/credential)
92//! This subdirectory contains several packages for implementing the
93//! [credential providers](https://doc.rust-lang.org/nightly/cargo/reference/registry-authentication.html).
94//! - [`mdman`](https://github.com/rust-lang/cargo/tree/master/crates/mdman)
95//! ([nightly docs](https://doc.rust-lang.org/nightly/nightly-rustc/mdman/index.html)):
96//! This is a utility for generating cargo's man pages. See [Building the man
97//! pages](https://github.com/rust-lang/cargo/tree/master/src/doc#building-the-man-pages)
98//! for more information.
99//! - [`resolver-tests`](https://github.com/rust-lang/cargo/tree/master/crates/resolver-tests)
100//! This is a dedicated package that defines tests for the [dependency
101//! resolver][core::resolver].
102//!
103//! ### File Overview
104//!
105//! Files that interact with cargo include
106//!
107//! - Package
108//! - `Cargo.toml`: User-written project manifest, loaded with [`util::toml::read_manifest`] and then
109//! translated to [`core::manifest::Manifest`] which maybe stored in a [`core::Package`].
110//! - This is editable with [`util::toml_mut::manifest::LocalManifest`]
111//! - `Cargo.lock`: Generally loaded with [`ops::resolve_ws`] or a variant of it into a [`core::resolver::Resolve`]
112//! - At the lowest level, [`ops::load_pkg_lockfile`] and [`ops::write_pkg_lockfile`] are used
113//! - See [`core::resolver::encode`] for versioning of `Cargo.lock`
114//! - `target/`: Used for build artifacts and abstracted with [`core::compiler::layout`]. `Layout` handles locking the target directory and providing paths to parts inside. There is a separate `Layout` for each build `target`.
115//! - `target/debug/.fingerprint`: Tracker whether nor not a crate needs to be rebuilt. See [`core::compiler::fingerprint`]
116//! - `$CARGO_HOME/`:
117//! - `registry/`: Package registry cache which is managed in [`sources::registry`]. Be careful
118//! as the lock [`util::GlobalContext::acquire_package_cache_lock`] must be manually acquired.
119//! - `index`/: Fast-to-access crate metadata (no need to download / extract `*.crate` files)
120//! - `cache/*/*.crate`: Local cache of published crates
121//! - `src/*/*`: Extracted from `*.crate` by [`sources::registry::RegistrySource`]
122//! - `git/`: Git source cache. See [`sources::git`].
123//! - `**/.cargo/config.toml`: Environment dependent (env variables, files) configuration. See
124//! [`util::context`]
125//!
126//! ## Contribute to Cargo documentations
127//!
128//! The Cargo team always continues improving all external and internal documentations.
129//! If you spot anything could be better, don't hesitate to discuss with the team on
130//! Zulip [`t-cargo` stream], or [submit an issue] right on GitHub.
131//! There is also an issue label [`A-documenting-cargo-itself`],
132//! which is generally for documenting user-facing [The Cargo Book],
133//! but the Cargo team is welcome any form of enhancement for the [Cargo Contributor Guide]
134//! and this API documentation as well.
135//!
136//! [The Cargo Book: External tools]: https://doc.rust-lang.org/stable/cargo/reference/external-tools.html
137//! [Cargo Architecture Overview]: https://doc.crates.io/contrib/architecture
138//! [`t-cargo` stream]: https://rust-lang.zulipchat.com/#narrow/stream/246057-t-cargo
139//! [submit an issue]: https://github.com/rust-lang/cargo/issues/new/choose
140//! [`A-documenting-cargo-itself`]: https://github.com/rust-lang/cargo/labels/A-documenting-cargo-itself
141//! [The Cargo Book]: https://doc.rust-lang.org/cargo/
142//! [Cargo Contributor Guide]: https://doc.crates.io/contrib/
143
144use anyhow::Error;
145use cargo_util_terminal::Shell;
146use cargo_util_terminal::Verbosity;
147use cargo_util_terminal::Verbosity::Verbose;
148use tracing::debug;
149
150pub use crate::util::errors::{AlreadyPrintedError, InternalError, VerboseError};
151pub use crate::util::{CargoResult, CliError, CliResult, GlobalContext, indented_lines};
152pub use crate::version::version;
153
154pub const CARGO_ENV: &str = "CARGO";
155
156#[macro_use]
157mod macros;
158
159pub mod core;
160pub mod diagnostics;
161pub mod ops;
162pub mod sources;
163pub mod util;
164mod version;
165
166pub fn exit_with_error(err: CliError, shell: &mut Shell) -> ! {
167 debug!("exit_with_error; err={:?}", err);
168
169 if let Some(ref err) = err.error {
170 if let Some(clap_err) = err.downcast_ref::<clap::Error>() {
171 let exit_code = if clap_err.use_stderr() { 1 } else { 0 };
172 let _ = clap_err.print();
173 std::process::exit(exit_code)
174 }
175 }
176
177 let CliError { error, exit_code } = err;
178 if let Some(error) = error {
179 display_error(&error, shell);
180 }
181
182 std::process::exit(exit_code)
183}
184
185/// Displays an error, and all its causes, to stderr.
186pub fn display_error(err: &Error, shell: &mut Shell) {
187 debug!("display_error; err={:?}", err);
188 _display_error(err, shell, true);
189 if err
190 .chain()
191 .any(|e| e.downcast_ref::<InternalError>().is_some())
192 {
193 drop(shell.note("this is an unexpected cargo internal error"));
194 drop(
195 shell.note(
196 "we would appreciate a bug report: https://github.com/rust-lang/cargo/issues/",
197 ),
198 );
199 drop(shell.note(format!("cargo {}", version())));
200 // Once backtraces are stabilized, this should print out a backtrace
201 // if it is available.
202 }
203}
204
205/// Displays a warning, with an error object providing detailed information
206/// and context.
207pub fn display_warning_with_error(warning: &str, err: &Error, shell: &mut Shell) {
208 drop(shell.warn(warning));
209 drop(writeln!(shell.err()));
210 _display_error(err, shell, false);
211}
212
213fn error_chain(err: &Error, verbosity: Verbosity) -> impl Iterator<Item = &dyn std::fmt::Display> {
214 err.chain()
215 .take_while(move |err| {
216 // If we're not in verbose mode then only print cause chain until one
217 // marked as `VerboseError` appears.
218 //
219 // Generally the top error shouldn't be verbose, but check it anyways.
220 verbosity == Verbose || !err.is::<VerboseError>()
221 })
222 .take_while(|err| !err.is::<AlreadyPrintedError>())
223 .map(|err| err as &dyn std::fmt::Display)
224}
225
226fn _display_error(err: &Error, shell: &mut Shell, as_err: bool) {
227 for (i, err) in error_chain(err, shell.verbosity()).enumerate() {
228 if i == 0 {
229 if as_err {
230 drop(shell.error(&err));
231 } else {
232 drop(writeln!(shell.err(), "{}", err));
233 }
234 } else {
235 drop(writeln!(shell.err(), "\nCaused by:"));
236 drop(write!(shell.err(), "{}", indented_lines(&err.to_string())));
237 }
238 }
239}