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//! It uses [`cargo_util_config`](crate::config) to merge and deserialize config values.
59//! The [`util::GlobalContext`] is usually accessed from the
60//! [`workspace::Workspace`]
61//! though references to it are scattered around for more convenient access.
62//! - [`workspace::parser`]:
63//! This directory contains the code for parsing `Cargo.toml` files.
64//! - [`ops::lockfile`]:
65//! This is where `Cargo.lock` files are loaded and saved.
66//!
67//! Related crates:
68//! - [`cargo-platform`](https://crates.io/crates/cargo-platform)
69//! ([nightly docs](https://doc.rust-lang.org/nightly/nightly-rustc/cargo_platform)):
70//! This library handles parsing `cfg` expressions.
71//! - [`cargo-util`](https://crates.io/crates/cargo-util)
72//! ([nightly docs](https://doc.rust-lang.org/nightly/nightly-rustc/cargo_util)):
73//! This contains general utility code that is shared between cargo and the testsuite
74//! - [`cargo-util-schemas`](https://crates.io/crates/cargo-util-schemas)
75//! ([nightly docs](https://doc.rust-lang.org/nightly/nightly-rustc/cargo_util_schemas)):
76//! This contains the serde schemas for cargo
77//! - [`crates-io`](https://crates.io/crates/crates-io)
78//! ([nightly docs](https://doc.rust-lang.org/nightly/nightly-rustc/crates_io)):
79//! This contains code for accessing the crates.io API.
80//! - [`home`](https://crates.io/crates/home):
81//! This library is shared between cargo and rustup and is used for finding their home directories.
82//! This is not directly depended upon with a `path` dependency; cargo uses the version from crates.io.
83//! It is intended to be versioned and published independently of Rust's release system.
84//! 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.
85//! - [`rustfix`](https://crates.io/crates/rustfix)
86//! ([nightly docs](https://doc.rust-lang.org/nightly/nightly-rustc/rustfix)):
87//! This defines structures that represent fix suggestions from rustc,
88//! as well as generates "fixed" code from suggestions.
89//! Operations in `rustfix` are all in memory and won't write to disks.
90//! - [`cargo-test-support`](https://github.com/rust-lang/cargo/tree/master/crates/cargo-test-support)
91//! ([nightly docs](https://doc.rust-lang.org/nightly/nightly-rustc/cargo_test_support/index.html)):
92//! This contains a variety of code to support writing tests
93//! - [`cargo-test-macro`](https://github.com/rust-lang/cargo/tree/master/crates/cargo-test-macro)
94//! ([nightly docs](https://doc.rust-lang.org/nightly/nightly-rustc/cargo_test_macro/index.html)):
95//! This is the `#[cargo_test]` proc-macro used by the test suite to define tests.
96//! - [`credential`](https://github.com/rust-lang/cargo/tree/master/credential)
97//! This subdirectory contains several packages for implementing the
98//! [credential providers](https://doc.rust-lang.org/nightly/cargo/reference/registry-authentication.html).
99//! - [`mdman`](https://github.com/rust-lang/cargo/tree/master/crates/mdman)
100//! ([nightly docs](https://doc.rust-lang.org/nightly/nightly-rustc/mdman/index.html)):
101//! This is a utility for generating cargo's man pages. See [Building the man
102//! pages](https://github.com/rust-lang/cargo/tree/master/doc#building-the-man-pages)
103//! for more information.
104//! - [`resolver-tests`](https://github.com/rust-lang/cargo/tree/master/crates/resolver-tests)
105//! This is a dedicated package that defines tests for the [dependency
106//! resolver][resolver].
107//!
108//! ### File Overview
109//!
110//! Files that interact with cargo include
111//!
112//! - Package
113//! - `Cargo.toml`: User-written project manifest, loaded with [`workspace::parser::read_manifest`] and then
114//! translated to [`workspace::manifest::Manifest`] which maybe stored in a [`workspace::Package`].
115//! - This is editable with [`workspace::editor::manifest::LocalManifest`]
116//! - `Cargo.lock`: Generally loaded with [`ops::resolve_ws`] or a variant of it into a [`resolver::Resolve`]
117//! - At the lowest level, [`ops::load_pkg_lockfile`] and [`ops::write_pkg_lockfile`] are used
118//! - See [`resolver::encode`] for versioning of `Cargo.lock`
119//! - `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`.
120//! - `target/debug/.fingerprint`: Tracker whether nor not a crate needs to be rebuilt. See [`compiler::fingerprint`]
121//! - `$CARGO_HOME/`:
122//! - `registry/`: Package registry cache which is managed in [`sources::registry`]. Be careful
123//! as the lock [`util::GlobalContext::acquire_package_cache_lock`] must be manually acquired.
124//! - `index`/: Fast-to-access crate metadata (no need to download / extract `*.crate` files)
125//! - `cache/*/*.crate`: Local cache of published crates
126//! - `src/*/*`: Extracted from `*.crate` by [`sources::registry::RegistrySource`]
127//! - `git/`: Git source cache. See [`sources::git`].
128//! - `**/.cargo/config.toml`: Environment dependent (env variables, files) configuration. See
129//! [`context`]
130//!
131//! ## Contribute to Cargo documentations
132//!
133//! The Cargo team always continues improving all external and internal documentations.
134//! If you spot anything could be better, don't hesitate to discuss with the team on
135//! Zulip [`t-cargo` stream], or [submit an issue] right on GitHub.
136//! There is also an issue label [`A-documenting-cargo-itself`],
137//! which is generally for documenting user-facing [The Cargo Book],
138//! but the Cargo team is welcome any form of enhancement for the [Cargo Contributor Guide]
139//! and this API documentation as well.
140//!
141//! [The Cargo Book: External tools]: https://doc.rust-lang.org/stable/cargo/reference/external-tools.html
142//! [Cargo Architecture Overview]: https://doc.crates.io/contrib/architecture
143//! [`t-cargo` stream]: https://rust-lang.zulipchat.com/#narrow/stream/246057-t-cargo
144//! [submit an issue]: https://github.com/rust-lang/cargo/issues/new/choose
145//! [`A-documenting-cargo-itself`]: https://github.com/rust-lang/cargo/labels/A-documenting-cargo-itself
146//! [The Cargo Book]: https://doc.rust-lang.org/cargo/
147//! [Cargo Contributor Guide]: https://doc.crates.io/contrib/
148
149use anyhow::Error;
150use cargo_util_terminal::Shell;
151use cargo_util_terminal::Verbosity;
152use cargo_util_terminal::Verbosity::Verbose;
153use tracing::debug;
154
155pub use crate::util::errors::{AlreadyPrintedError, InternalError, VerboseError};
156pub use crate::util::{CargoResult, CliError, CliResult, GlobalContext, indented_lines};
157pub use crate::version::version;
158
159pub const CARGO_ENV: &str = "CARGO";
160
161#[macro_use]
162mod macros;
163
164pub mod compiler;
165pub use cargo_util_config as config;
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}