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