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::Verbosity::Verbose;
143use crate::core::Shell;
144use anyhow::Error;
145use tracing::debug;
146
147pub use crate::util::errors::{AlreadyPrintedError, InternalError, VerboseError};
148pub use crate::util::{indented_lines, CargoResult, CliError, CliResult, GlobalContext};
149pub use crate::version::version;
150
151pub const CARGO_ENV: &str = "CARGO";
152
153#[macro_use]
154mod macros;
155
156pub mod core;
157pub mod ops;
158pub mod sources;
159pub mod util;
160mod version;
161
162pub fn exit_with_error(err: CliError, shell: &mut Shell) -> ! {
163 debug!("exit_with_error; err={:?}", err);
164
165 if let Some(ref err) = err.error {
166 if let Some(clap_err) = err.downcast_ref::<clap::Error>() {
167 let exit_code = if clap_err.use_stderr() { 1 } else { 0 };
168 let _ = clap_err.print();
169 std::process::exit(exit_code)
170 }
171 }
172
173 let CliError { error, exit_code } = err;
174 if let Some(error) = error {
175 display_error(&error, shell);
176 }
177
178 std::process::exit(exit_code)
179}
180
181/// Displays an error, and all its causes, to stderr.
182pub fn display_error(err: &Error, shell: &mut Shell) {
183 debug!("display_error; err={:?}", err);
184 _display_error(err, shell, true);
185 if err
186 .chain()
187 .any(|e| e.downcast_ref::<InternalError>().is_some())
188 {
189 drop(shell.note("this is an unexpected cargo internal error"));
190 drop(
191 shell.note(
192 "we would appreciate a bug report: https://github.com/rust-lang/cargo/issues/",
193 ),
194 );
195 drop(shell.note(format!("cargo {}", version())));
196 // Once backtraces are stabilized, this should print out a backtrace
197 // if it is available.
198 }
199}
200
201/// Displays a warning, with an error object providing detailed information
202/// and context.
203pub fn display_warning_with_error(warning: &str, err: &Error, shell: &mut Shell) {
204 drop(shell.warn(warning));
205 drop(writeln!(shell.err()));
206 _display_error(err, shell, false);
207}
208
209fn _display_error(err: &Error, shell: &mut Shell, as_err: bool) -> bool {
210 for (i, err) in err.chain().enumerate() {
211 // If we're not in verbose mode then only print cause chain until one
212 // marked as `VerboseError` appears.
213 //
214 // Generally the top error shouldn't be verbose, but check it anyways.
215 if shell.verbosity() != Verbose && err.is::<VerboseError>() {
216 return true;
217 }
218 if err.is::<AlreadyPrintedError>() {
219 break;
220 }
221 if i == 0 {
222 if as_err {
223 drop(shell.error(&err));
224 } else {
225 drop(writeln!(shell.err(), "{}", err));
226 }
227 } else {
228 drop(writeln!(shell.err(), "\nCaused by:"));
229 drop(write!(shell.err(), "{}", indented_lines(&err.to_string())));
230 }
231 }
232 false
233}