1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
#![deny(missing_docs)]
use std::collections::HashMap;
use std::env;
use std::error;
use std::fmt;
use std::io;
use std::path::Path;
use std::process::Command;
use std::str::{from_utf8, Utf8Error};
use serde_json;
#[derive(Clone, Deserialize, Debug)]
pub struct Metadata {
pub packages: Vec<Package>,
version: usize,
pub workspace_root: String,
}
#[derive(Clone, Deserialize, Debug)]
pub struct Package {
pub name: String,
pub version: String,
id: String,
source: Option<String>,
pub dependencies: Vec<Dependency>,
pub targets: Vec<Target>,
features: HashMap<String, Vec<String>>,
pub manifest_path: String,
}
#[derive(Clone, Deserialize, Debug)]
pub struct Dependency {
pub name: String,
source: Option<String>,
pub req: String,
kind: Option<String>,
optional: bool,
uses_default_features: bool,
features: Vec<String>,
target: Option<String>,
}
#[derive(Clone, Deserialize, Debug)]
pub struct Target {
pub name: String,
pub kind: Vec<String>,
#[serde(default)]
pub crate_types: Vec<String>,
pub src_path: String,
}
#[derive(Debug)]
pub enum Error {
Io(io::Error),
Utf8(Utf8Error),
Json(serde_json::Error),
}
impl From<io::Error> for Error {
fn from(err: io::Error) -> Self {
Error::Io(err)
}
}
impl From<Utf8Error> for Error {
fn from(err: Utf8Error) -> Self {
Error::Utf8(err)
}
}
impl From<serde_json::Error> for Error {
fn from(err: serde_json::Error) -> Self {
Error::Json(err)
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Error::Io(ref err) => err.fmt(f),
Error::Utf8(ref err) => err.fmt(f),
Error::Json(ref err) => err.fmt(f),
}
}
}
impl error::Error for Error {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match self {
Error::Io(ref err) => Some(err),
Error::Utf8(ref err) => Some(err),
Error::Json(ref err) => Some(err),
}
}
}
pub fn metadata(manifest_path: &Path) -> Result<Metadata, Error> {
let cargo = env::var("CARGO").unwrap_or_else(|_| String::from("cargo"));
let mut cmd = Command::new(cargo);
cmd.arg("metadata");
cmd.arg("--all-features");
cmd.arg("--format-version").arg("1");
cmd.arg("--manifest-path");
cmd.arg(manifest_path.to_str().unwrap());
let output = cmd.output()?;
let stdout = from_utf8(&output.stdout)?;
let meta: Metadata = serde_json::from_str(stdout)?;
Ok(meta)
}