56 releases

0.18.1 Oct 13, 2023
0.17.0 Jul 24, 2023
0.15.3 Jan 31, 2023
0.15.2 Nov 21, 2022
0.2.0 Mar 17, 2017

#1 in Cargo plugins

Download history 555454/week @ 2024-07-04 603162/week @ 2024-07-11 609549/week @ 2024-07-18 600983/week @ 2024-07-25 619687/week @ 2024-08-01 649765/week @ 2024-08-08 613917/week @ 2024-08-15 624184/week @ 2024-08-22 603601/week @ 2024-08-29 686033/week @ 2024-09-05 649760/week @ 2024-09-12 641701/week @ 2024-09-19 706877/week @ 2024-09-26 732730/week @ 2024-10-03 735277/week @ 2024-10-10 753296/week @ 2024-10-17

3,055,631 downloads per month
Used in 2,379 crates (575 directly)

MIT license

65KB
983 lines

cargo_metadata

Structured access to the output of cargo metadata. Usually used from within a cargo-* executable.

Also supports serialization to aid in implementing --message-format=json-like output generation in cargo-* subcommands, since some of the types in what cargo --message-format=json emits are exactly the same as the ones from cargo metadata.

Build Status crates.io

Documentation


lib.rs:

Structured access to the output of cargo metadata and cargo --message-format=json. Usually used from within a cargo-* executable

See the cargo book for details on cargo itself.

Examples

let mut args = std::env::args().skip_while(|val| !val.starts_with("--manifest-path"));

let mut cmd = cargo_metadata::MetadataCommand::new();
let manifest_path = match args.next() {
    Some(ref p) if p == "--manifest-path" => {
        cmd.manifest_path(args.next().unwrap());
    }
    Some(p) => {
        cmd.manifest_path(p.trim_start_matches("--manifest-path="));
    }
    None => {}
};

let _metadata = cmd.exec().unwrap();

Pass features flags

use cargo_metadata::{MetadataCommand, CargoOpt};

let _metadata = MetadataCommand::new()
    .manifest_path("./Cargo.toml")
    .features(CargoOpt::AllFeatures)
    .exec()
    .unwrap();

Parse message-format output:

use std::process::{Stdio, Command};
use cargo_metadata::Message;

let mut command = Command::new("cargo")
    .args(&["build", "--message-format=json-render-diagnostics"])
    .stdout(Stdio::piped())
    .spawn()
    .unwrap();

let reader = std::io::BufReader::new(command.stdout.take().unwrap());
for message in cargo_metadata::Message::parse_stream(reader) {
    match message.unwrap() {
        Message::CompilerMessage(msg) => {
            println!("{:?}", msg);
        },
        Message::CompilerArtifact(artifact) => {
            println!("{:?}", artifact);
        },
        Message::BuildScriptExecuted(script) => {
            println!("{:?}", script);
        },
        Message::BuildFinished(finished) => {
            println!("{:?}", finished);
        },
        _ => () // Unknown message
    }
}

let output = command.wait().expect("Couldn't get cargo's exit status");

Dependencies

~1–2MB
~40K SLoC