1use crate::models::{DatasourceId, Dependency, FileReference, PackageData, PackageType, Party};
22use crate::parser_warn as warn;
23use crate::parsers::utils::split_name_email;
24use packageurl::PackageUrl;
25use std::fs::File;
26use std::io::Read;
27use std::path::Path;
28use toml::Value;
29
30use super::PackageParser;
31use super::license_normalization::{
32 DeclaredLicenseMatchMetadata, build_declared_license_data, empty_declared_license_data,
33 normalize_spdx_expression,
34};
35
36const FIELD_PACKAGE: &str = "package";
37const FIELD_NAME: &str = "name";
38const FIELD_VERSION: &str = "version";
39const FIELD_LICENSE: &str = "license";
40const FIELD_LICENSE_FILE: &str = "license-file";
41const FIELD_AUTHORS: &str = "authors";
42const FIELD_REPOSITORY: &str = "repository";
43const FIELD_HOMEPAGE: &str = "homepage";
44const FIELD_DEPENDENCIES: &str = "dependencies";
45const FIELD_DEV_DEPENDENCIES: &str = "dev-dependencies";
46const FIELD_DEV_DEPENDENCIES_LEGACY: &str = "dev_dependencies";
47const FIELD_BUILD_DEPENDENCIES: &str = "build-dependencies";
48const FIELD_BUILD_DEPENDENCIES_LEGACY: &str = "build_dependencies";
49const FIELD_DESCRIPTION: &str = "description";
50const FIELD_KEYWORDS: &str = "keywords";
51const FIELD_CATEGORIES: &str = "categories";
52const FIELD_RUST_VERSION: &str = "rust-version";
53const FIELD_EDITION: &str = "edition";
54const FIELD_README: &str = "readme";
55const FIELD_PUBLISH: &str = "publish";
56
57pub struct CargoParser;
62
63impl PackageParser for CargoParser {
64 const PACKAGE_TYPE: PackageType = PackageType::Cargo;
65
66 fn extract_packages(path: &Path) -> Vec<PackageData> {
67 let toml_content = match read_cargo_toml(path) {
68 Ok(content) => content,
69 Err(_) => return Vec::new(),
70 };
71
72 let package = toml_content.get(FIELD_PACKAGE).and_then(|v| v.as_table());
73
74 let name = package
75 .and_then(|p| p.get(FIELD_NAME))
76 .and_then(|v| v.as_str())
77 .map(String::from);
78
79 let version = package
80 .and_then(|p| p.get(FIELD_VERSION))
81 .and_then(|v| v.as_str())
82 .map(String::from);
83
84 let raw_license = package
85 .and_then(|p| p.get(FIELD_LICENSE))
86 .and_then(|v| v.as_str())
87 .map(String::from);
88 let file_references = extract_file_references(&toml_content);
89 let (declared_license_expression, declared_license_expression_spdx, license_detections) =
90 raw_license
91 .as_deref()
92 .and_then(normalize_spdx_expression)
93 .map(|normalized| {
94 build_declared_license_data(
95 normalized,
96 DeclaredLicenseMatchMetadata::single_line(
97 raw_license.as_deref().unwrap_or_default(),
98 ),
99 )
100 })
101 .unwrap_or_else(empty_declared_license_data);
102
103 let extracted_license_statement = raw_license.clone();
104
105 let dependencies = extract_dependencies_for_scopes(&toml_content, &[FIELD_DEPENDENCIES]);
106 let dev_dependencies = extract_dependencies_for_scopes(
107 &toml_content,
108 &[FIELD_DEV_DEPENDENCIES, FIELD_DEV_DEPENDENCIES_LEGACY],
109 );
110 let build_dependencies = extract_dependencies_for_scopes(
111 &toml_content,
112 &[FIELD_BUILD_DEPENDENCIES, FIELD_BUILD_DEPENDENCIES_LEGACY],
113 );
114
115 let purl = create_package_url(&name, &version);
116
117 let homepage_url = package
118 .and_then(|p| p.get(FIELD_HOMEPAGE))
119 .and_then(|v| v.as_str())
120 .map(String::from)
121 .or_else(|| {
122 name.as_ref()
123 .map(|n| format!("https://crates.io/crates/{}", n))
124 });
125
126 let repository_url = package
127 .and_then(|p| p.get(FIELD_REPOSITORY))
128 .and_then(|v| v.as_str())
129 .map(String::from);
130 let download_url = None;
131
132 let api_data_url = generate_cargo_api_url(&name, &version);
133
134 let repository_homepage_url = name
135 .as_ref()
136 .map(|n| format!("https://crates.io/crates/{}", n));
137
138 let repository_download_url = match (&name, &version) {
139 (Some(n), Some(v)) => Some(format!(
140 "https://crates.io/api/v1/crates/{}/{}/download",
141 n, v
142 )),
143 _ => None,
144 };
145
146 let description = package
147 .and_then(|p| p.get(FIELD_DESCRIPTION))
148 .and_then(|v| v.as_str())
149 .map(|s| s.trim().to_string());
150
151 let keywords = extract_keywords_and_categories(&toml_content);
152
153 let extra_data = extract_extra_data(&toml_content);
154 let is_private = package
155 .and_then(|p| p.get(FIELD_PUBLISH))
156 .is_some_and(|value| matches!(value, Value::Boolean(false)));
157 vec![PackageData {
158 package_type: Some(Self::PACKAGE_TYPE),
159 namespace: None,
160 name,
161 version,
162 qualifiers: None,
163 subpath: None,
164 primary_language: Some("Rust".to_string()),
165 description,
166 release_date: None,
167 parties: extract_parties(&toml_content),
168 keywords,
169 homepage_url,
170 download_url,
171 size: None,
172 sha1: None,
173 md5: None,
174 sha256: None,
175 sha512: None,
176 bug_tracking_url: None,
177 code_view_url: None,
178 vcs_url: repository_url,
179 copyright: None,
180 holder: None,
181 declared_license_expression,
182 declared_license_expression_spdx,
183 license_detections,
184 other_license_expression: None,
185 other_license_expression_spdx: None,
186 other_license_detections: Vec::new(),
187 extracted_license_statement,
188 notice_text: None,
189 source_packages: Vec::new(),
190 file_references,
191 is_private,
192 is_virtual: false,
193 extra_data,
194 dependencies: [dependencies, dev_dependencies, build_dependencies].concat(),
195 repository_homepage_url,
196 repository_download_url,
197 api_data_url,
198 datasource_id: Some(DatasourceId::CargoToml),
199 purl,
200 }]
201 }
202
203 fn is_match(path: &Path) -> bool {
204 path.file_name()
205 .and_then(|name| name.to_str())
206 .is_some_and(|name| name.eq_ignore_ascii_case("cargo.toml"))
207 }
208}
209
210fn read_cargo_toml(path: &Path) -> Result<Value, String> {
212 let mut file = File::open(path).map_err(|e| format!("Failed to open file: {}", e))?;
213 let mut content = String::new();
214 file.read_to_string(&mut content)
215 .map_err(|e| format!("Error reading file: {}", e))?;
216
217 toml::from_str(&content).map_err(|e| format!("Failed to parse TOML: {}", e))
218}
219
220fn generate_cargo_api_url(name: &Option<String>, _version: &Option<String>) -> Option<String> {
221 const REGISTRY: &str = "https://crates.io/api/v1/crates";
222 name.as_ref().map(|name| format!("{}/{}", REGISTRY, name))
223}
224
225fn create_package_url(name: &Option<String>, version: &Option<String>) -> Option<String> {
226 name.as_ref().and_then(|name| {
227 let mut package_url = match PackageUrl::new(CargoParser::PACKAGE_TYPE.as_str(), name) {
228 Ok(p) => p,
229 Err(e) => {
230 warn!(
231 "Failed to create PackageUrl for cargo package '{}': {}",
232 name, e
233 );
234 return None;
235 }
236 };
237
238 if let Some(v) = version
239 && let Err(e) = package_url.with_version(v)
240 {
241 warn!(
242 "Failed to set version '{}' for cargo package '{}': {}",
243 v, name, e
244 );
245 return None;
246 }
247
248 Some(package_url.to_string())
249 })
250}
251
252fn extract_parties(toml_content: &Value) -> Vec<Party> {
254 let mut parties = Vec::new();
255
256 if let Some(package) = toml_content.get(FIELD_PACKAGE).and_then(|v| v.as_table())
257 && let Some(authors) = package.get(FIELD_AUTHORS).and_then(|v| v.as_array())
258 {
259 for author in authors {
260 if let Some(author_str) = author.as_str() {
261 let (name, email) = split_name_email(author_str);
262 parties.push(Party {
263 r#type: None,
264 role: Some("author".to_string()),
265 name,
266 email,
267 url: None,
268 organization: None,
269 organization_url: None,
270 timezone: None,
271 });
272 }
273 }
274 }
275
276 parties
277}
278
279fn is_cargo_version_pinned(version_str: &str) -> bool {
286 let trimmed = version_str.trim();
287
288 if trimmed.is_empty() {
290 return false;
291 }
292
293 if trimmed.contains('^')
295 || trimmed.contains('~')
296 || trimmed.contains('>')
297 || trimmed.contains('<')
298 || trimmed.contains('*')
299 || trimmed.contains('=')
300 {
301 return false;
302 }
303
304 trimmed.matches('.').count() >= 2
308}
309
310fn extract_dependencies(toml_content: &Value, scope: &str) -> Vec<Dependency> {
311 use serde_json::json;
312
313 let mut dependencies = Vec::new();
314
315 let is_runtime = !scope.ends_with("dev-dependencies") && !scope.ends_with("build-dependencies");
317
318 if let Some(deps_table) = toml_content.get(scope).and_then(|v| v.as_table()) {
319 for (name, value) in deps_table {
320 let (extracted_requirement, is_optional, extra_data_map, is_pinned) = match value {
321 Value::String(version_str) => {
322 let pinned = is_cargo_version_pinned(version_str);
324 (
325 Some(version_str.to_string()),
326 false,
327 std::collections::HashMap::new(),
328 pinned,
329 )
330 }
331 Value::Table(table) => {
332 let version = table
334 .get("version")
335 .and_then(|v| v.as_str())
336 .map(String::from);
337
338 let pinned = version.as_ref().is_some_and(|v| is_cargo_version_pinned(v));
339
340 let is_optional = table
341 .get("optional")
342 .and_then(|v| v.as_bool())
343 .unwrap_or(false);
344
345 let mut extra_data = std::collections::HashMap::new();
346
347 for (key, val) in table {
349 match key.as_str() {
350 "version" => {
351 if let Some(v) = val.as_str() {
353 extra_data.insert("version".to_string(), json!(v));
354 }
355 }
356 "features" => {
357 if let Some(features_array) = val.as_array() {
359 let features: Vec<String> = features_array
360 .iter()
361 .filter_map(|f| f.as_str().map(String::from))
362 .collect();
363 extra_data.insert("features".to_string(), json!(features));
364 }
365 }
366 "optional" => {
367 }
369 _ => {
370 if let Some(s) = val.as_str() {
372 extra_data.insert(key.clone(), json!(s));
373 } else if let Some(b) = val.as_bool() {
374 extra_data.insert(key.clone(), json!(b));
375 } else if let Some(i) = val.as_integer() {
376 extra_data.insert(key.clone(), json!(i));
377 }
378 }
379 }
380 }
381
382 (version, is_optional, extra_data, pinned)
383 }
384 _ => {
385 continue;
387 }
388 };
389
390 if extracted_requirement.is_some() || !extra_data_map.is_empty() {
392 let purl = match PackageUrl::new(CargoParser::PACKAGE_TYPE.as_str(), name) {
393 Ok(p) => p.to_string(),
394 Err(e) => {
395 warn!(
396 "Failed to create PackageUrl for cargo dependency '{}': {}",
397 name, e
398 );
399 continue; }
401 };
402
403 dependencies.push(Dependency {
404 purl: Some(purl),
405 extracted_requirement,
406 scope: Some(scope.to_string()),
407 is_runtime: Some(is_runtime),
408 is_optional: Some(is_optional),
409 is_pinned: Some(is_pinned),
410 is_direct: Some(true),
411 resolved_package: None,
412 extra_data: if extra_data_map.is_empty() {
413 None
414 } else {
415 Some(extra_data_map)
416 },
417 });
418 }
419 }
420 }
421
422 dependencies
423}
424
425fn extract_dependencies_for_scopes(toml_content: &Value, scopes: &[&str]) -> Vec<Dependency> {
426 scopes
427 .iter()
428 .flat_map(|scope| extract_dependencies(toml_content, scope))
429 .collect()
430}
431
432fn extract_keywords_and_categories(toml_content: &Value) -> Vec<String> {
434 let mut keywords = Vec::new();
435
436 if let Some(package) = toml_content.get(FIELD_PACKAGE).and_then(|v| v.as_table()) {
437 if let Some(kw_array) = package.get(FIELD_KEYWORDS).and_then(|v| v.as_array()) {
439 for kw in kw_array {
440 if let Some(kw_str) = kw.as_str() {
441 keywords.push(kw_str.to_string());
442 }
443 }
444 }
445
446 if let Some(cat_array) = package.get(FIELD_CATEGORIES).and_then(|v| v.as_array()) {
448 for cat in cat_array {
449 if let Some(cat_str) = cat.as_str() {
450 keywords.push(cat_str.to_string());
451 }
452 }
453 }
454 }
455
456 keywords
457}
458
459fn extract_file_references(toml_content: &Value) -> Vec<FileReference> {
460 let mut file_references = Vec::new();
461
462 if let Some(package) = toml_content
463 .get(FIELD_PACKAGE)
464 .and_then(|value| value.as_table())
465 {
466 for path in [
467 package
468 .get(FIELD_LICENSE_FILE)
469 .and_then(|value| value.as_str()),
470 package.get(FIELD_README).and_then(|value| value.as_str()),
471 ]
472 .into_iter()
473 .flatten()
474 {
475 if file_references
476 .iter()
477 .any(|reference: &FileReference| reference.path == path)
478 {
479 continue;
480 }
481
482 file_references.push(FileReference {
483 path: path.to_string(),
484 size: None,
485 sha1: None,
486 md5: None,
487 sha256: None,
488 sha512: None,
489 extra_data: None,
490 });
491 }
492 }
493
494 file_references
495}
496
497fn toml_to_json(value: &toml::Value) -> serde_json::Value {
499 match value {
500 toml::Value::String(s) => serde_json::json!(s),
501 toml::Value::Integer(i) => serde_json::json!(i),
502 toml::Value::Float(f) => serde_json::json!(f),
503 toml::Value::Boolean(b) => serde_json::json!(b),
504 toml::Value::Array(a) => serde_json::Value::Array(a.iter().map(toml_to_json).collect()),
505 toml::Value::Table(t) => {
506 let map: serde_json::Map<String, serde_json::Value> = t
507 .iter()
508 .map(|(k, v)| (k.clone(), toml_to_json(v)))
509 .collect();
510 serde_json::Value::Object(map)
511 }
512 toml::Value::Datetime(d) => serde_json::json!(d.to_string()),
513 }
514}
515
516fn extract_extra_data(
518 toml_content: &Value,
519) -> Option<std::collections::HashMap<String, serde_json::Value>> {
520 use serde_json::json;
521 let mut extra_data = std::collections::HashMap::new();
522
523 if let Some(package) = toml_content.get(FIELD_PACKAGE).and_then(|v| v.as_table()) {
524 if let Some(rust_version_value) = package.get(FIELD_RUST_VERSION) {
526 if let Some(rust_version_str) = rust_version_value.as_str() {
527 extra_data.insert("rust_version".to_string(), json!(rust_version_str));
528 } else if rust_version_value
529 .as_table()
530 .is_some_and(|t| t.get("workspace") == Some(&toml::Value::Boolean(true)))
531 {
532 extra_data.insert("rust-version".to_string(), json!("workspace"));
533 }
534 }
535
536 if let Some(edition_value) = package.get(FIELD_EDITION) {
538 if let Some(edition_str) = edition_value.as_str() {
539 extra_data.insert("rust_edition".to_string(), json!(edition_str));
540 } else if edition_value
541 .as_table()
542 .is_some_and(|t| t.get("workspace") == Some(&toml::Value::Boolean(true)))
543 {
544 extra_data.insert("edition".to_string(), json!("workspace"));
545 }
546 }
547
548 if let Some(documentation) = package.get("documentation").and_then(|v| v.as_str()) {
550 extra_data.insert("documentation_url".to_string(), json!(documentation));
551 }
552
553 if let Some(license_file) = package.get(FIELD_LICENSE_FILE).and_then(|v| v.as_str()) {
555 extra_data.insert("license_file".to_string(), json!(license_file));
556 }
557
558 if let Some(readme_value) = package.get(FIELD_README) {
559 if let Some(readme_file) = readme_value.as_str() {
560 extra_data.insert("readme_file".to_string(), json!(readme_file));
561 } else if let Some(readme_enabled) = readme_value.as_bool() {
562 extra_data.insert("readme".to_string(), json!(readme_enabled));
563 } else if readme_value
564 .as_table()
565 .is_some_and(|t| t.get("workspace") == Some(&toml::Value::Boolean(true)))
566 {
567 extra_data.insert("readme".to_string(), json!("workspace"));
568 }
569 }
570
571 if let Some(publish_value) = package.get(FIELD_PUBLISH) {
572 extra_data.insert("publish".to_string(), toml_to_json(publish_value));
573 }
574
575 if let Some(version_value) = package.get(FIELD_VERSION)
578 && version_value
579 .as_table()
580 .is_some_and(|t| t.get("workspace") == Some(&toml::Value::Boolean(true)))
581 {
582 extra_data.insert("version".to_string(), json!("workspace"));
583 }
584
585 if let Some(license_value) = package.get(FIELD_LICENSE)
587 && license_value
588 .as_table()
589 .is_some_and(|t| t.get("workspace") == Some(&toml::Value::Boolean(true)))
590 {
591 extra_data.insert("license".to_string(), json!("workspace"));
592 }
593
594 if let Some(homepage_value) = package.get(FIELD_HOMEPAGE)
596 && homepage_value
597 .as_table()
598 .is_some_and(|t| t.get("workspace") == Some(&toml::Value::Boolean(true)))
599 {
600 extra_data.insert("homepage".to_string(), json!("workspace"));
601 }
602
603 if let Some(repository_value) = package.get(FIELD_REPOSITORY)
605 && repository_value
606 .as_table()
607 .is_some_and(|t| t.get("workspace") == Some(&toml::Value::Boolean(true)))
608 {
609 extra_data.insert("repository".to_string(), json!("workspace"));
610 }
611
612 if let Some(categories_value) = package.get(FIELD_CATEGORIES)
614 && categories_value
615 .as_table()
616 .is_some_and(|t| t.get("workspace") == Some(&toml::Value::Boolean(true)))
617 {
618 extra_data.insert("categories".to_string(), json!("workspace"));
619 }
620
621 if let Some(authors_value) = package.get(FIELD_AUTHORS)
623 && authors_value
624 .as_table()
625 .is_some_and(|t| t.get("workspace") == Some(&toml::Value::Boolean(true)))
626 {
627 extra_data.insert("authors".to_string(), json!("workspace"));
628 }
629 }
630
631 if let Some(workspace_value) = toml_content.get("workspace") {
633 extra_data.insert("workspace".to_string(), toml_to_json(workspace_value));
634 }
635
636 if extra_data.is_empty() {
637 None
638 } else {
639 Some(extra_data)
640 }
641}
642
643crate::register_parser!(
644 "Rust Cargo.toml manifest",
645 &["**/Cargo.toml", "**/cargo.toml"],
646 "cargo",
647 "Rust",
648 Some("https://doc.rust-lang.org/cargo/reference/manifest.html"),
649);