Skip to main content

provenant/parsers/
vcpkg.rs

1use std::collections::HashMap;
2use std::fs;
3use std::path::Path;
4
5use log::warn;
6use packageurl::PackageUrl;
7use serde_json::Value;
8
9use crate::models::{DatasourceId, Dependency, PackageData, PackageType, Party};
10use crate::parsers::utils::split_name_email;
11
12use super::PackageParser;
13
14pub struct VcpkgManifestParser;
15
16impl PackageParser for VcpkgManifestParser {
17    const PACKAGE_TYPE: PackageType = PackageType::Vcpkg;
18
19    fn is_match(path: &Path) -> bool {
20        path.file_name().and_then(|name| name.to_str()) == Some("vcpkg.json")
21    }
22
23    fn extract_packages(path: &Path) -> Vec<PackageData> {
24        let content = match fs::read_to_string(path) {
25            Ok(content) => content,
26            Err(e) => {
27                warn!("Failed to read vcpkg.json at {:?}: {}", path, e);
28                return vec![default_package_data()];
29            }
30        };
31
32        let json: Value = match serde_json::from_str(&content) {
33            Ok(json) => json,
34            Err(e) => {
35                warn!("Failed to parse vcpkg.json at {:?}: {}", path, e);
36                return vec![default_package_data()];
37            }
38        };
39
40        vec![parse_vcpkg_manifest(path, &json)]
41    }
42}
43
44fn default_package_data() -> PackageData {
45    PackageData {
46        package_type: Some(PackageType::Vcpkg),
47        datasource_id: Some(DatasourceId::VcpkgJson),
48        ..Default::default()
49    }
50}
51
52fn parse_vcpkg_manifest(path: &Path, json: &Value) -> PackageData {
53    let name = get_non_empty_string(json, "name");
54    let version = manifest_version(json);
55    let description = get_string_or_array(json, "description");
56    let homepage_url = get_non_empty_string(json, "homepage");
57    let extracted_license_statement = get_string_or_array(json, "license");
58    let parties = extract_maintainers(json);
59    let dependencies = extract_dependencies(json);
60    let extra_data = build_extra_data(path, json);
61
62    PackageData {
63        package_type: Some(PackageType::Vcpkg),
64        namespace: None,
65        name: name.clone(),
66        version: version.clone(),
67        primary_language: Some("C++".to_string()),
68        description,
69        parties,
70        homepage_url,
71        extracted_license_statement,
72        is_private: name.is_none(),
73        dependencies,
74        extra_data,
75        datasource_id: Some(DatasourceId::VcpkgJson),
76        purl: name
77            .as_deref()
78            .and_then(|name| build_vcpkg_purl(name, version.as_deref())),
79        ..default_package_data()
80    }
81}
82
83fn manifest_version(json: &Value) -> Option<String> {
84    let version = [
85        "version",
86        "version-semver",
87        "version-date",
88        "version-string",
89    ]
90    .into_iter()
91    .find_map(|field| get_non_empty_string(json, field));
92
93    match (version, json.get("port-version").and_then(Value::as_i64)) {
94        (Some(version), Some(port_version)) if port_version > 0 => {
95            Some(format!("{}#{}", version, port_version))
96        }
97        (version, _) => version,
98    }
99}
100
101fn extract_maintainers(json: &Value) -> Vec<Party> {
102    let Some(value) = json.get("maintainers") else {
103        return Vec::new();
104    };
105
106    let maintainers: Vec<String> = match value {
107        Value::String(s) => vec![s.clone()],
108        Value::Array(values) => values
109            .iter()
110            .filter_map(Value::as_str)
111            .map(ToOwned::to_owned)
112            .collect(),
113        _ => Vec::new(),
114    };
115
116    maintainers
117        .into_iter()
118        .map(|entry| {
119            let (name, email) = split_name_email(&entry);
120            Party {
121                r#type: Some("person".to_string()),
122                role: Some("maintainer".to_string()),
123                name,
124                email,
125                url: None,
126                organization: None,
127                organization_url: None,
128                timezone: None,
129            }
130        })
131        .collect()
132}
133
134fn extract_dependencies(json: &Value) -> Vec<Dependency> {
135    let Some(deps) = json.get("dependencies").and_then(Value::as_array) else {
136        return Vec::new();
137    };
138
139    deps.iter().filter_map(parse_dependency_entry).collect()
140}
141
142fn parse_dependency_entry(value: &Value) -> Option<Dependency> {
143    match value {
144        Value::String(name) => Some(Dependency {
145            purl: build_vcpkg_purl(name, None),
146            extracted_requirement: Some(name.clone()),
147            scope: Some("dependencies".to_string()),
148            is_runtime: Some(true),
149            is_optional: Some(false),
150            is_pinned: Some(false),
151            is_direct: Some(true),
152            resolved_package: None,
153            extra_data: None,
154        }),
155        Value::Object(obj) => {
156            let name = obj.get("name").and_then(Value::as_str)?.trim();
157            if name.is_empty() {
158                return None;
159            }
160
161            let extracted_requirement = obj
162                .get("version>=")
163                .and_then(Value::as_str)
164                .map(ToOwned::to_owned)
165                .or_else(|| Some(name.to_string()));
166
167            let host = obj.get("host").and_then(Value::as_bool).unwrap_or(false);
168            let mut extra = HashMap::new();
169            for field in [
170                "version>=",
171                "features",
172                "default-features",
173                "host",
174                "platform",
175            ] {
176                if let Some(field_value) = obj.get(field) {
177                    extra.insert(field.to_string(), field_value.clone());
178                }
179            }
180
181            Some(Dependency {
182                purl: build_vcpkg_purl(name, None),
183                extracted_requirement,
184                scope: Some("dependencies".to_string()),
185                is_runtime: Some(!host),
186                is_optional: Some(false),
187                is_pinned: Some(false),
188                is_direct: Some(true),
189                resolved_package: None,
190                extra_data: (!extra.is_empty()).then_some(extra),
191            })
192        }
193        _ => None,
194    }
195}
196
197fn build_extra_data(path: &Path, json: &Value) -> Option<HashMap<String, Value>> {
198    let mut extra = HashMap::new();
199    for field in [
200        "builtin-baseline",
201        "overrides",
202        "supports",
203        "default-features",
204        "features",
205        "configuration",
206        "vcpkg-configuration",
207        "documentation",
208    ] {
209        if let Some(value) = json.get(field) {
210            extra.insert(field.to_string(), value.clone());
211        }
212    }
213
214    if !extra.contains_key("configuration")
215        && !extra.contains_key("vcpkg-configuration")
216        && let Some(config) = read_sibling_configuration(path)
217    {
218        extra.insert("configuration".to_string(), config);
219    }
220
221    (!extra.is_empty()).then_some(extra)
222}
223
224fn read_sibling_configuration(path: &Path) -> Option<Value> {
225    let sibling_path = path.with_file_name("vcpkg-configuration.json");
226    let content = fs::read_to_string(&sibling_path).ok()?;
227    match serde_json::from_str(&content) {
228        Ok(value) => Some(value),
229        Err(e) => {
230            warn!(
231                "Failed to parse sibling vcpkg-configuration.json at {:?}: {}",
232                sibling_path, e
233            );
234            None
235        }
236    }
237}
238
239fn get_non_empty_string(json: &Value, field: &str) -> Option<String> {
240    json.get(field)
241        .and_then(Value::as_str)
242        .map(str::trim)
243        .filter(|value| !value.is_empty())
244        .map(|value| value.to_string())
245}
246
247fn get_string_or_array(json: &Value, field: &str) -> Option<String> {
248    match json.get(field) {
249        Some(Value::String(s)) if !s.trim().is_empty() => Some(s.trim().to_string()),
250        Some(Value::Array(values)) => {
251            let collected: Vec<_> = values
252                .iter()
253                .filter_map(Value::as_str)
254                .map(str::trim)
255                .filter(|s| !s.is_empty())
256                .collect();
257            (!collected.is_empty()).then(|| collected.join("\n"))
258        }
259        _ => None,
260    }
261}
262
263fn build_vcpkg_purl(name: &str, version: Option<&str>) -> Option<String> {
264    let mut purl = PackageUrl::new("generic", name).ok()?;
265    purl.with_namespace("vcpkg").ok()?;
266    if let Some(version) = version {
267        purl.with_version(version).ok()?;
268    }
269    Some(purl.to_string())
270}
271
272crate::register_parser!(
273    "vcpkg manifest file",
274    &["**/vcpkg.json"],
275    "vcpkg",
276    "",
277    Some("https://learn.microsoft.com/en-us/vcpkg/reference/vcpkg-json"),
278);