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