Skip to content

Commit

Permalink
Auto merge of #14141 - hi-rustin:rustin-patch-info, r=epage
Browse files Browse the repository at this point in the history
feat: Add `info` cargo subcommand

<!-- homu-ignore:start -->

close #14081
close #948

fcp #14141 (comment)

This PR added a new `info` cargo subcommand.

# Background

This adds a new subcommand to Cargo, `cargo info`. This subcommand would allow users to get information about a crate from the command line, without having to go to the web.

The main motivation for this is to make it easier to get information about a crate from the command line. Currently, the way to get information about a crate is to go to the web and look it up on [crates.io] or find the crate's source code and look at the `Cargo.toml` file. This is not very convenient, especially not all information is displayed on the [crates.io] page.
This command also has been requested by the community for a long time. You can find more discussion about this in [cargo#948].

Another motivation is to make the workflow of finding and evaluating crates more efficient. In the current workflow, users can search for crates using `cargo search`, but then they have to go to the web to get more information about the crate. This is not very efficient, especially if the user is just trying to get a quick overview of the crate. This would allow users to quickly get information about a crate without having to leave the terminal.

[crates.io]: https://crates.io
[cargo#948]: #948

Example usage:

```console
./target/debug/cargo info clap --verbose
  Credential cargo:token get crates-io
clap #argument #cli #arg #parser #parse
A simple to use, efficient, and full-featured Command Line Argument Parser
version: 4.5.8 (latest 4.5.9)
license: MIT OR Apache-2.0
rust-version: 1.74
documentation: https://docs.rs/clap/4.5.8
repository: https://github.com/clap-rs/clap
crates.io: https://crates.io/crates/clap/4.5.8
features:
 +default         = [std, color, help, usage, error-context, suggestions]
  color           = [clap_builder/color]
  error-context   = [clap_builder/error-context]
  help            = [clap_builder/help]
  std             = [clap_builder/std]
  suggestions     = [clap_builder/suggestions]
  usage           = [clap_builder/usage]
  cargo           = [clap_builder/cargo]
  debug           = [clap_builder/debug, clap_derive?/debug]
  deprecated      = [clap_builder/deprecated, clap_derive?/deprecated]
  derive          = [dep:clap_derive]
  env             = [clap_builder/env]
  string          = [clap_builder/string]
  unicode         = [clap_builder/unicode]
  unstable-doc    = [clap_builder/unstable-doc, derive]
  unstable-styles = [clap_builder/unstable-styles]
  unstable-v5     = [clap_builder/unstable-v5, clap_derive?/unstable-v5, deprecated]
  wrap_help       = [clap_builder/wrap_help]
dependencies:
 +clap_builder@=4.5.8
  clap_derive@=4.5.8
owners:
  kbknapp (Kevin K.)
  github:rust-cli:maintainers (Maintainers)
  github:clap-rs:admins (Admins)
note: to see how you depend on clap, run `cargo tree --invert --package [email protected]`
```

<img width="1425" alt="image" src="https://github.com/user-attachments/assets/e0813c45-624f-417c-a61d-eda03f9ab5ed">

*note:* this is showing the `--verbose` output to show every thing the user can possibly see.  Normal operation does not include
- dependencies

## Detailed design

| Content                                                                    | Explanation                         | Why                                                                               |
|----------------------------------------------------------------------------|-------------------------------------|-----------------------------------------------------------------------------------|
| clap                                                                       | Name                                | The basic information.                                                            |
| #argument #cli #arg #parser #parse                                         | Keywords (clickable)                           | It's more like a category, which you can use to search for relevant alternatives. |
| A simple to use, efficient, and full-featured Command Line Argument Parser | Description                         | The basic information.                                                            |
| version: 4.5.8 (latest 4.5.9)                                                           | Version                             | The basic information.                                                            |
| license: MIT OR Apache-2.0                                                 | License                             | When choosing a crate, it is crucial to consider the license.                     |
| rust-version: 1.74                                                       | MSRV                                | When choosing a crate, it is crucial to make sure it can work with your MSRV.     |
| documentation: <https://docs.rs/clap/4.5.8>                               | Documentation Link                  | Use these links can find more docs and information.                               |
| repository: <https://github.com/clap-rs/clap>                              | Repo Link                           | Use these links can find more docs and information.                               |
| crates.io: https://crates.io/crates/clap/4.5.8                             | crates.io Link                           | Use these links can find more docs and information.                               |
| features:                                                                  | Default Features And Other Features | It helps for enabling features.                                                   |
| dependencies:                                                              | All dependencies                    | It indicates what it depends on.                                                  |
| owners:                                                                    | Owners                              | It indicates who maintains the crate.                                             |
| note: to see how you depend on clap, run `cargo tree --invert --package [email protected]`                                                                   | A note for cargo tree command                              | It will prompt the user that the package is depended on under the workspace, and the dependencies can be viewed using the cargo tree command.           |

## Rendering features

- For features enabled by users, a + prefix and colored output are now used for better visibility.
- For features enabled automatically, colored output is used to distinguish them.
- For disabled features, non-colored output is used to clearly indicate their status.

## Rendering deps

Only show dependencies in verbose mode.

- For dependencies required by the package, a + prefix and colored output are now used for better visibility.
- For dependencies that are optional and activated, colored output is used to distinguish them.
- For dependencies that are optional and not activated, non-colored output is used to clearly indicate their status.

# Some important notes

## Downloading the crate from any Cargo compatible registry

The `cargo info` command will download the crate from any Cargo compatible registry. It will then extract the information from the `Cargo.toml` file and display it in the terminal.

If the crate is already in the local cache, it will not download the crate again. It will get the information from the local cache.

## Pick the correct version from the workspace

When executed in a workspace directory, the cargo info command chooses the version that the workspace is currently using.

If there's a lock file available, the version from this file will be used. In the absence of a lock file, the command attempts to select a version that is compatible with the Minimum Supported Rust Version (MSRV). And the lock file will be generated automatically.

The following hierarchy is used to determine the MSRV:

- First, the MSRV of the parent directory package is checked, if it exists.
- If the parent directory package does not specify an MSRV, the minimal MSRV of the workspace is checked.
- If neither the workspace nor the parent directory package specify an MSRV, the version of the current Rust compiler (rustc --version) is used.

# Prior art

## NPM

[npm] has a similar command called `npm info`.
For example:

```console
$ npm info lodash

[email protected] | MIT | deps: none | versions: 114
Lodash modular utilities.
https://lodash.com/

keywords: modules, stdlib, util

dist
.tarball: https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz
.shasum: 679591c564c3bffaae8454cf0b3df370c3d6911c
.integrity: sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==
.unpackedSize: 1.4 MB

maintainers:
- mathias <[email protected]>
- jdalton <[email protected]>
- bnjmnt4n <[email protected]>

dist-tags:
latest: 4.17.21

published over a year ago by bnjmnt4n <[email protected]>
```

[npm]: https://www.npmjs.com/

## Poetry

[Poetry] has a similar command called `poetry show`.

For example:

```console
$ poetry show pendulum

name        : pendulum
version     : 1.4.2
description : Python datetimes made easy

dependencies
 - python-dateutil >=2.6.1
 - tzlocal >=1.4
 - pytzdata >=2017.2.2

required by
 - calendar >=1.4.0
```

[Poetry]: https://python-poetry.org/

# insta-stable

As `@weihanglo` mentioned in #14141 (comment), commands that shadow third-party commands tend to be insta-stabilized to avoid an intermediate period where users can't access the third-party command (built-ins get priority) nor the built-in command (requires nightly)

For the cargo-info command, there are two commands that this would shadow
- [cargo-information](https://github.com/hi-rustin/cargo-information): hasn't been around too long and only has 4k downloads
- [cargo-info](https://gitlab.com/imp/cargo-info) : been around longer and has 63k downloads

We might be able to get away with having this unstable but starting from the assumption of insta-stabilization.
  • Loading branch information
bors committed Aug 12, 2024
2 parents ec05ed9 + ba07215 commit f3fee6d
Show file tree
Hide file tree
Showing 206 changed files with 5,563 additions and 1 deletion.
35 changes: 35 additions & 0 deletions src/bin/cargo/commands/info.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
use anyhow::Context;
use cargo::ops::info;
use cargo::util::command_prelude::*;
use cargo_util_schemas::core::PackageIdSpec;

pub fn cli() -> Command {
Command::new("info")
.about("Display information about a package in the registry")
.arg(
Arg::new("package")
.required(true)
.value_name("SPEC")
.help_heading(heading::PACKAGE_SELECTION)
.help("Package to inspect"),
)
.arg_index("Registry index URL to search packages in")
.arg_registry("Registry to search packages in")
.arg_silent_suggestion()
.after_help(color_print::cstr!(
"Run `<cyan,bold>cargo help info</>` for more detailed information.\n"
))
}

pub fn exec(gctx: &mut GlobalContext, args: &ArgMatches) -> CliResult {
let package = args
.get_one::<String>("package")
.map(String::as_str)
.unwrap();
let spec = PackageIdSpec::parse(package)
.with_context(|| format!("invalid package ID specification: `{package}`"))?;

let reg_or_index = args.registry_or_index(gctx)?;
info(&spec, gctx, reg_or_index)?;
Ok(())
}
3 changes: 3 additions & 0 deletions src/bin/cargo/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ pub fn builtin() -> Vec<Command> {
generate_lockfile::cli(),
git_checkout::cli(),
help::cli(),
info::cli(),
init::cli(),
install::cli(),
locate_project::cli(),
Expand Down Expand Up @@ -59,6 +60,7 @@ pub fn builtin_exec(cmd: &str) -> Option<Exec> {
"generate-lockfile" => generate_lockfile::exec,
"git-checkout" => git_checkout::exec,
"help" => help::exec,
"info" => info::exec,
"init" => init::exec,
"install" => install::exec,
"locate-project" => locate_project::exec,
Expand Down Expand Up @@ -102,6 +104,7 @@ pub mod fix;
pub mod generate_lockfile;
pub mod git_checkout;
pub mod help;
pub mod info;
pub mod init;
pub mod install;
pub mod locate_project;
Expand Down
1 change: 1 addition & 0 deletions src/cargo/ops/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ pub use self::cargo_update::write_manifest_upgrades;
pub use self::cargo_update::UpdateOptions;
pub use self::fix::{fix, fix_exec_rustc, fix_get_proxy_lock_addr, FixOptions};
pub use self::lockfile::{load_pkg_lockfile, resolve_to_string, write_pkg_lockfile};
pub use self::registry::info;
pub use self::registry::modify_owners;
pub use self::registry::publish;
pub use self::registry::registry_login;
Expand Down
287 changes: 287 additions & 0 deletions src/cargo/ops/registry/info/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,287 @@
//! Implementation of `cargo info`.

use anyhow::bail;
use cargo_credential::Operation;
use cargo_util_schemas::core::{PackageIdSpec, PartialVersion};
use crates_io::User;

use crate::core::registry::PackageRegistry;
use crate::core::{Dependency, Package, PackageId, PackageIdSpecQuery, Registry, Workspace};
use crate::ops::registry::info::view::pretty_view;
use crate::ops::registry::{get_source_id_with_package_id, RegistryOrIndex, RegistrySourceIds};
use crate::ops::resolve_ws;
use crate::sources::source::QueryKind;
use crate::sources::{IndexSummary, SourceConfigMap};
use crate::util::auth::AuthorizationErrorReason;
use crate::util::cache_lock::CacheLockMode;
use crate::util::command_prelude::root_manifest;
use crate::{CargoResult, GlobalContext};

mod view;

pub fn info(
spec: &PackageIdSpec,
gctx: &GlobalContext,
reg_or_index: Option<RegistryOrIndex>,
) -> CargoResult<()> {
let source_config = SourceConfigMap::new(gctx)?;
let mut registry = PackageRegistry::new_with_source_config(gctx, source_config)?;
// Make sure we get the lock before we download anything.
let _lock = gctx.acquire_package_cache_lock(CacheLockMode::DownloadExclusive)?;
registry.lock_patches();

// If we can find it in workspace, use it as a specific version.
let nearest_manifest_path = root_manifest(None, gctx).ok();
let ws = nearest_manifest_path
.as_ref()
.and_then(|root| Workspace::new(root, gctx).ok());
validate_locked_and_frozen_options(ws.is_some(), gctx)?;
let nearest_package = ws.as_ref().and_then(|ws| {
nearest_manifest_path
.as_ref()
.and_then(|path| ws.members().find(|p| p.manifest_path() == path))
});
let (mut package_id, is_member) = find_pkgid_in_ws(nearest_package, ws.as_ref(), spec);
let (use_package_source_id, source_ids) =
get_source_id_with_package_id(gctx, package_id, reg_or_index.as_ref())?;
// If we don't use the package's source, we need to query the package ID from the specified registry.
if !use_package_source_id {
package_id = None;
}

let msrv_from_nearest_manifest_path_or_ws =
try_get_msrv_from_nearest_manifest_or_ws(nearest_package, ws.as_ref());
// If the workspace does not have a specific Rust version,
// or if the command is not called within the workspace, then fallback to the global Rust version.
let rustc_version = match msrv_from_nearest_manifest_path_or_ws {
Some(msrv) => msrv,
None => {
let current_rustc = gctx.load_global_rustc(ws.as_ref())?.version;
// Remove any pre-release identifiers for easier comparison.
// Otherwise, the MSRV check will fail if the current Rust version is a nightly or beta version.
semver::Version::new(
current_rustc.major,
current_rustc.minor,
current_rustc.patch,
)
.into()
}
};
// Only suggest cargo tree command when the package is not a workspace member.
// For workspace members, `cargo tree --package <SPEC> --invert` is useless. It only prints itself.
let suggest_cargo_tree_command = package_id.is_some() && !is_member;

let summaries = query_summaries(spec, &mut registry, &source_ids)?;
let package_id = match package_id {
Some(id) => id,
None => find_pkgid_in_summaries(&summaries, spec, &rustc_version, &source_ids)?,
};

let package = registry.get(&[package_id])?;
let package = package.get_one(package_id)?;
let owners = try_list_owners(
gctx,
&source_ids,
reg_or_index.as_ref(),
package_id.name().as_str(),
)?;
pretty_view(
package,
&summaries,
&owners,
suggest_cargo_tree_command,
gctx,
)?;

Ok(())
}

fn find_pkgid_in_ws(
nearest_package: Option<&Package>,
ws: Option<&Workspace<'_>>,
spec: &PackageIdSpec,
) -> (Option<PackageId>, bool) {
let Some(ws) = ws else {
return (None, false);
};

if let Some(member) = ws.members().find(|p| spec.matches(p.package_id())) {
return (Some(member.package_id()), true);
}

let Ok((_, resolve)) = resolve_ws(ws, false) else {
return (None, false);
};

if let Some(package_id) = nearest_package
.map(|p| p.package_id())
.into_iter()
.flat_map(|p| resolve.deps(p))
.map(|(p, _)| p)
.filter(|&p| spec.matches(p))
.max_by_key(|&p| p.version())
{
return (Some(package_id), false);
}

if let Some(package_id) = ws
.members()
.map(|p| p.package_id())
.flat_map(|p| resolve.deps(p))
.map(|(p, _)| p)
.filter(|&p| spec.matches(p))
.max_by_key(|&p| p.version())
{
return (Some(package_id), false);
}

if let Some(package_id) = resolve
.iter()
.filter(|&p| spec.matches(p))
.max_by_key(|&p| p.version())
{
return (Some(package_id), false);
}

(None, false)
}

fn find_pkgid_in_summaries(
summaries: &[IndexSummary],
spec: &PackageIdSpec,
rustc_version: &PartialVersion,
source_ids: &RegistrySourceIds,
) -> CargoResult<PackageId> {
let summary = summaries
.iter()
.filter(|s| spec.matches(s.package_id()))
.max_by(|s1, s2| {
// Check the MSRV compatibility.
let s1_matches = s1
.as_summary()
.rust_version()
.map(|v| v.is_compatible_with(rustc_version))
.unwrap_or_else(|| false);
let s2_matches = s2
.as_summary()
.rust_version()
.map(|v| v.is_compatible_with(rustc_version))
.unwrap_or_else(|| false);
// MSRV compatible version is preferred.
match (s1_matches, s2_matches) {
(true, false) => std::cmp::Ordering::Greater,
(false, true) => std::cmp::Ordering::Less,
// If both summaries match the current Rust version or neither do, try to
// pick the latest version.
_ => s1.package_id().version().cmp(s2.package_id().version()),
}
});

match summary {
Some(summary) => Ok(summary.package_id()),
None => {
anyhow::bail!(
"could not find `{}` in registry `{}`",
spec,
source_ids.original.url()
)
}
}
}

fn query_summaries(
spec: &PackageIdSpec,
registry: &mut PackageRegistry<'_>,
source_ids: &RegistrySourceIds,
) -> CargoResult<Vec<IndexSummary>> {
// Query without version requirement to get all index summaries.
let dep = Dependency::parse(spec.name(), None, source_ids.original)?;
loop {
// Exact to avoid returning all for path/git
match registry.query_vec(&dep, QueryKind::Exact) {
std::task::Poll::Ready(res) => {
break res;
}
std::task::Poll::Pending => registry.block_until_ready()?,
}
}
}

// Try to list the login and name of all owners of a crate.
fn try_list_owners(
gctx: &GlobalContext,
source_ids: &RegistrySourceIds,
reg_or_index: Option<&RegistryOrIndex>,
package_name: &str,
) -> CargoResult<Option<Vec<String>>> {
// Only remote registries support listing owners.
if !source_ids.original.is_remote_registry() {
return Ok(None);
}
match super::registry(
gctx,
source_ids,
None,
reg_or_index,
false,
Some(Operation::Read),
) {
Ok(mut registry) => {
let owners = registry.list_owners(package_name)?;
let names = owners.iter().map(get_username).collect();
return Ok(Some(names));
}
Err(err) => {
// If the token is missing, it means the user is not logged in.
// We don't want to show an error in this case.
if err.to_string().contains(
(AuthorizationErrorReason::TokenMissing)
.to_string()
.as_str(),
) {
return Ok(None);
}
return Err(err);
}
}
}

fn get_username(u: &User) -> String {
format!(
"{}{}",
u.login,
u.name
.as_ref()
.map(|name| format!(" ({})", name))
.unwrap_or_default(),
)
}

fn validate_locked_and_frozen_options(
in_workspace: bool,
gctx: &GlobalContext,
) -> Result<(), anyhow::Error> {
// Only in workspace, we can use --frozen or --locked.
if !in_workspace {
if gctx.locked() {
bail!("the option `--locked` can only be used within a workspace");
}

if gctx.frozen() {
bail!("the option `--frozen` can only be used within a workspace");
}
}
Ok(())
}

fn try_get_msrv_from_nearest_manifest_or_ws(
nearest_package: Option<&Package>,
ws: Option<&Workspace<'_>>,
) -> Option<PartialVersion> {
// Try to get the MSRV from the nearest manifest.
let rust_version = nearest_package.and_then(|p| p.rust_version().map(|v| v.as_partial()));
// If the nearest manifest does not have a specific Rust version, try to get it from the workspace.
rust_version
.or_else(|| ws.and_then(|ws| ws.rust_version().map(|v| v.as_partial())))
.cloned()
}
Loading

0 comments on commit f3fee6d

Please sign in to comment.