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//! - [`util`]:
47//! This directory contains generally-useful utility modules.
48//! - [`util::context`]:
49//! This directory contains the global application context.
50//! This includes the config parser which makes heavy use of
51//! [serde](https://serde.rs/) to merge and translate config values.
52//! The [`util::GlobalContext`] is usually accessed from the
53//! [`core::Workspace`]
54//! though references to it are scattered around for more convenient access.
55//! - [`util::toml`]:
56//! This directory contains the code for parsing `Cargo.toml` files.
57//! - [`ops::lockfile`]:
58//! This is where `Cargo.lock` files are loaded and saved.
59//!
60//! Related crates:
61//! - [`cargo-platform`](https://crates.io/crates/cargo-platform)
62//! ([nightly docs](https://doc.rust-lang.org/nightly/nightly-rustc/cargo_platform)):
63//! This library handles parsing `cfg` expressions.
64//! - [`cargo-util`](https://crates.io/crates/cargo-util)
65//! ([nightly docs](https://doc.rust-lang.org/nightly/nightly-rustc/cargo_util)):
66//! This contains general utility code that is shared between cargo and the testsuite
67//! - [`cargo-util-schemas`](https://crates.io/crates/cargo-util-schemas)
68//! ([nightly docs](https://doc.rust-lang.org/nightly/nightly-rustc/cargo_util_schemas)):
69//! This contains the serde schemas for cargo
70//! - [`crates-io`](https://crates.io/crates/crates-io)
71//! ([nightly docs](https://doc.rust-lang.org/nightly/nightly-rustc/crates_io)):
72//! This contains code for accessing the crates.io API.
73//! - [`home`](https://crates.io/crates/home):
74//! This library is shared between cargo and rustup and is used for finding their home directories.
75//! This is not directly depended upon with a `path` dependency; cargo uses the version from crates.io.
76//! It is intended to be versioned and published independently of Rust's release system.
77//! 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.
78//! - [`rustfix`](https://crates.io/crates/rustfix)
79//! ([nightly docs](https://doc.rust-lang.org/nightly/nightly-rustc/rustfix)):
80//! This defines structures that represent fix suggestions from rustc,
81//! as well as generates "fixed" code from suggestions.
82//! Operations in `rustfix` are all in memory and won't write to disks.
83//! - [`cargo-test-support`](https://github.com/rust-lang/cargo/tree/master/crates/cargo-test-support)
84//! ([nightly docs](https://doc.rust-lang.org/nightly/nightly-rustc/cargo_test_support/index.html)):
85//! This contains a variety of code to support writing tests
86//! - [`cargo-test-macro`](https://github.com/rust-lang/cargo/tree/master/crates/cargo-test-macro)
87//! ([nightly docs](https://doc.rust-lang.org/nightly/nightly-rustc/cargo_test_macro/index.html)):
88//! This is the `#[cargo_test]` proc-macro used by the test suite to define tests.
89//! - [`credential`](https://github.com/rust-lang/cargo/tree/master/credential)
90//! This subdirectory contains several packages for implementing the
91//! [credential providers](https://doc.rust-lang.org/nightly/cargo/reference/registry-authentication.html).
92//! - [`mdman`](https://github.com/rust-lang/cargo/tree/master/crates/mdman)
93//! ([nightly docs](https://doc.rust-lang.org/nightly/nightly-rustc/mdman/index.html)):
94//! This is a utility for generating cargo's man pages. See [Building the man
95//! pages](https://github.com/rust-lang/cargo/tree/master/src/doc#building-the-man-pages)
96//! for more information.
97//! - [`resolver-tests`](https://github.com/rust-lang/cargo/tree/master/crates/resolver-tests)
98//! This is a dedicated package that defines tests for the [dependency
99//! resolver][core::resolver].
100//!
101//! ### File Overview
102//!
103//! Files that interact with cargo include
104//!
105//! - Package
106//! - `Cargo.toml`: User-written project manifest, loaded with [`util::toml::read_manifest`] and then
107//! translated to [`core::manifest::Manifest`] which maybe stored in a [`core::Package`].
108//! - This is editable with [`util::toml_mut::manifest::LocalManifest`]
109//! - `Cargo.lock`: Generally loaded with [`ops::resolve_ws`] or a variant of it into a [`core::resolver::Resolve`]
110//! - At the lowest level, [`ops::load_pkg_lockfile`] and [`ops::write_pkg_lockfile`] are used
111//! - See [`core::resolver::encode`] for versioning of `Cargo.lock`
112//! - `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`.
113//! - `target/debug/.fingerprint`: Tracker whether nor not a crate needs to be rebuilt. See [`core::compiler::fingerprint`]
114//! - `$CARGO_HOME/`:
115//! - `registry/`: Package registry cache which is managed in [`sources::registry`]. Be careful
116//! as the lock [`util::GlobalContext::acquire_package_cache_lock`] must be manually acquired.
117//! - `index`/: Fast-to-access crate metadata (no need to download / extract `*.crate` files)
118//! - `cache/*/*.crate`: Local cache of published crates
119//! - `src/*/*`: Extracted from `*.crate` by [`sources::registry::RegistrySource`]
120//! - `git/`: Git source cache. See [`sources::git`].
121//! - `**/.cargo/config.toml`: Environment dependent (env variables, files) configuration. See
122//! [`util::context`]
123//!
124//! ## Contribute to Cargo documentations
125//!
126//! The Cargo team always continues improving all external and internal documentations.
127//! If you spot anything could be better, don't hesitate to discuss with the team on
128//! Zulip [`t-cargo` stream], or [submit an issue] right on GitHub.
129//! There is also an issue label [`A-documenting-cargo-itself`],
130//! which is generally for documenting user-facing [The Cargo Book],
131//! but the Cargo team is welcome any form of enhancement for the [Cargo Contributor Guide]
132//! and this API documentation as well.
133//!
134//! [The Cargo Book: External tools]: https://doc.rust-lang.org/stable/cargo/reference/external-tools.html
135//! [Cargo Architecture Overview]: https://doc.crates.io/contrib/architecture
136//! [`t-cargo` stream]: https://rust-lang.zulipchat.com/#narrow/stream/246057-t-cargo
137//! [submit an issue]: https://github.com/rust-lang/cargo/issues/new/choose
138//! [`A-documenting-cargo-itself`]: https://github.com/rust-lang/cargo/labels/A-documenting-cargo-itself
139//! [The Cargo Book]: https://doc.rust-lang.org/cargo/
140//! [Cargo Contributor Guide]: https://doc.crates.io/contrib/
141
142use crate::core::Shell;
143use crate::core::shell::Verbosity;
144use crate::core::shell::Verbosity::Verbose;
145use anyhow::Error;
146use tracing::debug;
147
148pub use crate::util::errors::{AlreadyPrintedError, InternalError, VerboseError};
149pub use crate::util::{CargoResult, CliError, CliResult, GlobalContext, indented_lines};
150pub use crate::version::version;
151
152pub const CARGO_ENV: &str = "CARGO";
153
154#[macro_use]
155mod macros;
156
157pub mod core;
158pub mod ops;
159pub mod sources;
160pub mod util;
161mod version;
162
163pub fn exit_with_error(err: CliError, shell: &mut Shell) -> ! {
164 debug!("exit_with_error; err={:?}", err);
165
166 if let Some(ref err) = err.error {
167 if let Some(clap_err) = err.downcast_ref::<clap::Error>() {
168 let exit_code = if clap_err.use_stderr() { 1 } else { 0 };
169 let _ = clap_err.print();
170 std::process::exit(exit_code)
171 }
172 }
173
174 let CliError { error, exit_code } = err;
175 if let Some(error) = error {
176 display_error(&error, shell);
177 }
178
179 std::process::exit(exit_code)
180}
181
182/// Displays an error, and all its causes, to stderr.
183pub fn display_error(err: &Error, shell: &mut Shell) {
184 debug!("display_error; err={:?}", err);
185 _display_error(err, shell, true);
186 if err
187 .chain()
188 .any(|e| e.downcast_ref::<InternalError>().is_some())
189 {
190 drop(shell.note("this is an unexpected cargo internal error"));
191 drop(
192 shell.note(
193 "we would appreciate a bug report: https://github.com/rust-lang/cargo/issues/",
194 ),
195 );
196 drop(shell.note(format!("cargo {}", version())));
197 // Once backtraces are stabilized, this should print out a backtrace
198 // if it is available.
199 }
200}
201
202/// Displays a warning, with an error object providing detailed information
203/// and context.
204pub fn display_warning_with_error(warning: &str, err: &Error, shell: &mut Shell) {
205 drop(shell.warn(warning));
206 drop(writeln!(shell.err()));
207 _display_error(err, shell, false);
208}
209
210fn error_chain(err: &Error, verbosity: Verbosity) -> impl Iterator<Item = &dyn std::fmt::Display> {
211 err.chain()
212 .take_while(move |err| {
213 // If we're not in verbose mode then only print cause chain until one
214 // marked as `VerboseError` appears.
215 //
216 // Generally the top error shouldn't be verbose, but check it anyways.
217 verbosity == Verbose || !err.is::<VerboseError>()
218 })
219 .take_while(|err| !err.is::<AlreadyPrintedError>())
220 .map(|err| err as &dyn std::fmt::Display)
221}
222
223fn _display_error(err: &Error, shell: &mut Shell, as_err: bool) {
224 for (i, err) in error_chain(err, shell.verbosity()).enumerate() {
225 if i == 0 {
226 if as_err {
227 drop(shell.error(&err));
228 } else {
229 drop(writeln!(shell.err(), "{}", err));
230 }
231 } else {
232 drop(writeln!(shell.err(), "\nCaused by:"));
233 drop(write!(shell.err(), "{}", indented_lines(&err.to_string())));
234 }
235 }
236}