1use std::collections::HashMap;
29use std::path::Path;
30
31use crate::parser_warn as warn;
32use crate::parsers::podfile_lock::build_cocoapods_purl;
33use crate::parsers::utils::{CappedIterExt, read_file_to_string, truncate_field};
34use serde_json::Value;
35
36use crate::models::{DatasourceId, Dependency, PackageData, PackageType, Party, PartyType};
37
38use super::PackageParser;
39use super::license_normalization::normalize_spdx_declared_license;
40use super::metadata::ParserMetadata;
41
42const FIELD_NAME: &str = "name";
43const FIELD_VERSION: &str = "version";
44const FIELD_SUMMARY: &str = "summary";
45const FIELD_DESCRIPTION: &str = "description";
46const FIELD_HOMEPAGE: &str = "homepage";
47const FIELD_LICENSE: &str = "license";
48const FIELD_SOURCE: &str = "source";
49const FIELD_AUTHORS: &str = "authors";
50const FIELD_DEPENDENCIES: &str = "dependencies";
51
52const PRIMARY_LANGUAGE: &str = "Objective-C";
53
54pub struct PodspecJsonParser;
58
59impl PackageParser for PodspecJsonParser {
60 const PACKAGE_TYPE: PackageType = PackageType::Cocoapods;
61
62 fn metadata() -> Vec<ParserMetadata> {
63 vec![ParserMetadata {
64 description: "CocoaPods .podspec.json manifest",
65 file_patterns: &["**/*.podspec.json"],
66 package_type: "cocoapods",
67 primary_language: "Objective-C",
68 documentation_url: Some("https://guides.cocoapods.org/syntax/podspec.html"),
69 }]
70 }
71
72 fn extract_packages(path: &Path) -> Vec<PackageData> {
73 let json_content = match read_json_file(path) {
74 Ok(content) => content,
75 Err(e) => {
76 warn!("Failed to read .podspec.json at {:?}: {}", path, e);
77 return vec![default_package_data()];
78 }
79 };
80
81 let name = json_content
82 .get(FIELD_NAME)
83 .and_then(|v| v.as_str())
84 .map(|s| truncate_field(s.trim().to_string()))
85 .filter(|s| !s.is_empty());
86
87 let version = json_content
88 .get(FIELD_VERSION)
89 .and_then(|v| v.as_str())
90 .map(|s| truncate_field(s.trim().to_string()))
91 .filter(|s| !s.is_empty());
92
93 let summary = json_content
94 .get(FIELD_SUMMARY)
95 .and_then(|v| v.as_str())
96 .map(|s| truncate_field(s.trim().to_string()))
97 .filter(|s| !s.is_empty());
98
99 let mut description = json_content
100 .get(FIELD_DESCRIPTION)
101 .and_then(|v| v.as_str())
102 .map(|s| truncate_field(s.trim().to_string()))
103 .filter(|s| !s.is_empty());
104
105 if let (Some(summary_text), Some(desc_text)) = (&summary, &description) {
107 if !desc_text.starts_with(summary_text) {
108 description = Some(format!("{}. {}", summary_text, desc_text));
109 }
110 } else if summary.is_some() && description.is_none() {
111 description = summary.clone();
112 }
113
114 let homepage_url = json_content
115 .get(FIELD_HOMEPAGE)
116 .and_then(|v| v.as_str())
117 .map(|s| truncate_field(s.trim().to_string()))
118 .filter(|s| !s.is_empty());
119
120 let extracted_license_statement = extract_license_statement(&json_content);
121 let (declared_license_expression, declared_license_expression_spdx, license_detections) =
122 normalize_podspec_json_declared_license(
123 &json_content,
124 extracted_license_statement.as_deref(),
125 );
126
127 let (vcs_url, download_url) = extract_source_urls(&json_content);
128
129 let parties = extract_parties(&json_content);
130
131 let dependencies = extract_dependencies(&json_content);
132
133 let mut extra_data = HashMap::new();
134
135 if let Some(source) = json_content.get(FIELD_SOURCE) {
137 extra_data.insert("source".to_string(), source.clone());
138 }
139
140 if let Some(deps) = json_content.get(FIELD_DEPENDENCIES)
142 && let Some(obj) = deps.as_object()
143 && !obj.is_empty()
144 {
145 extra_data.insert(FIELD_DEPENDENCIES.to_string(), deps.clone());
146 }
147
148 if let Some(license_file) = json_content
149 .get(FIELD_LICENSE)
150 .and_then(|license| license.as_object())
151 .and_then(|license| license.get("file"))
152 .and_then(|value| value.as_str())
153 .filter(|value| !value.trim().is_empty())
154 {
155 extra_data.insert(
156 "license_file".to_string(),
157 Value::String(license_file.trim().to_string()),
158 );
159 }
160
161 let raw_json = serde_json::to_string(&json_content).unwrap_or_default();
162 if raw_json.len() <= 10 * 1024 * 1024 {
163 extra_data.insert("podspec.json".to_string(), json_content.clone());
164 } else {
165 warn!(
166 "Skipping podspec.json extra_data entry: serialized size {} bytes exceeds 10MB limit",
167 raw_json.len()
168 );
169 }
170
171 let extra_data = if extra_data.is_empty() {
172 None
173 } else {
174 Some(extra_data)
175 };
176
177 let repository_homepage_url = name
179 .as_ref()
180 .map(|n| format!("https://cocoapods.org/pods/{}", n));
181 let repository_download_url =
182 if let (Some(_name_str), Some(version_str)) = (&name, &version) {
183 if let Some(homepage) = &homepage_url {
184 Some(format!("{}/archive/{}.zip", homepage, version_str))
185 } else if let Some(vcs) = &vcs_url {
186 let repo_base = get_repo_base_url(vcs);
187 repo_base.map(|base| format!("{}/archive/refs/tags/{}.zip", base, version_str))
188 } else {
189 None
190 }
191 } else {
192 None
193 };
194
195 let code_view_url = if let (Some(vcs), Some(version_str)) = (&vcs_url, &version) {
196 let repo_base = get_repo_base_url(vcs);
197 repo_base.map(|base| format!("{}/tree/{}", base, version_str))
198 } else {
199 None
200 };
201
202 let bug_tracking_url = vcs_url.as_ref().and_then(|vcs| {
203 let repo_base = get_repo_base_url(vcs);
204 repo_base.map(|base| format!("{}/issues/", base))
205 });
206
207 let api_data_url = if let (Some(name_str), Some(version_str)) = (&name, &version) {
208 get_hashed_path(name_str).map(|hashed| {
209 format!(
210 "https://raw.githubusercontent.com/CocoaPods/Specs/blob/master/Specs/{}/{}/{}/{}.podspec.json",
211 hashed, name_str, version_str, name_str
212 )
213 })
214 } else {
215 None
216 };
217
218 let purl = name
219 .as_deref()
220 .and_then(|name_str| build_cocoapods_purl(name_str, version.as_deref()));
221
222 vec![PackageData {
223 package_type: Some(Self::PACKAGE_TYPE),
224 namespace: None,
225 name: name.clone(),
226 version: version.clone(),
227 qualifiers: None,
228 subpath: None,
229 primary_language: Some(PRIMARY_LANGUAGE.to_string()),
230 description,
231 release_date: None,
232 parties,
233 keywords: Vec::new(),
234 homepage_url,
235 download_url,
236 size: None,
237 sha1: None,
238 md5: None,
239 sha256: None,
240 sha512: None,
241 bug_tracking_url,
242 code_view_url,
243 vcs_url,
244 copyright: None,
245 holder: None,
246 declared_license_expression,
247 declared_license_expression_spdx,
248 license_detections,
249 other_license_expression: None,
250 other_license_expression_spdx: None,
251 other_license_detections: Vec::new(),
252 extracted_license_statement,
253 notice_text: None,
254 source_packages: Vec::new(),
255 file_references: Vec::new(),
256 is_private: false,
257 is_virtual: false,
258 extra_data,
259 dependencies,
260 repository_homepage_url,
261 repository_download_url,
262 api_data_url,
263 datasource_id: Some(DatasourceId::CocoapodsPodspecJson),
264 purl,
265 }]
266 }
267
268 fn is_match(path: &Path) -> bool {
269 path.file_name()
270 .and_then(|name| name.to_str())
271 .is_some_and(|name| name.ends_with(".podspec.json"))
272 }
273}
274
275fn read_json_file(path: &Path) -> Result<Value, String> {
276 let contents = read_file_to_string(path, None).map_err(|e| e.to_string())?;
277 serde_json::from_str(&contents).map_err(|e| format!("Failed to parse JSON: {}", e))
278}
279
280fn default_package_data() -> PackageData {
282 PackageData {
283 package_type: Some(PodspecJsonParser::PACKAGE_TYPE),
284 primary_language: Some(PRIMARY_LANGUAGE.to_string()),
285 datasource_id: Some(DatasourceId::CocoapodsPodspecJson),
286 ..Default::default()
287 }
288}
289
290fn extract_license_statement(json: &Value) -> Option<String> {
293 json.get(FIELD_LICENSE).and_then(|lic| {
294 if let Some(lic_str) = lic.as_str() {
295 Some(truncate_field(lic_str.trim().to_string()))
296 } else if let Some(lic_obj) = lic.as_object() {
297 let values: Vec<String> = lic_obj
299 .values()
300 .filter_map(|v| v.as_str())
301 .map(|s| s.trim().to_string())
302 .filter(|s| !s.is_empty())
303 .collect();
304 if values.is_empty() {
305 None
306 } else {
307 Some(values.join(" "))
308 }
309 } else {
310 None
311 }
312 })
313}
314
315fn normalize_podspec_json_declared_license(
316 json: &Value,
317 extracted_license_statement: Option<&str>,
318) -> (
319 Option<String>,
320 Option<String>,
321 Vec<crate::models::LicenseDetection>,
322) {
323 let normalized_candidate = json
324 .get(FIELD_LICENSE)
325 .and_then(|license| {
326 license
327 .as_str()
328 .map(str::trim)
329 .filter(|value| !value.is_empty())
330 .map(canonicalize_cocoapods_license_type)
331 .or_else(|| {
332 license
333 .as_object()
334 .and_then(|obj| obj.get("type"))
335 .and_then(|value| value.as_str())
336 .map(str::trim)
337 .filter(|value| !value.is_empty())
338 .map(canonicalize_cocoapods_license_type)
339 })
340 })
341 .or_else(|| extracted_license_statement.map(canonicalize_cocoapods_license_type));
342
343 normalize_spdx_declared_license(normalized_candidate.as_deref())
344}
345
346fn canonicalize_cocoapods_license_type(value: &str) -> String {
347 match value.trim() {
348 "Apache License, Version 2.0" => "Apache-2.0".to_string(),
349 other => other.to_string(),
350 }
351}
352
353fn extract_source_urls(json: &Value) -> (Option<String>, Option<String>) {
355 let mut vcs_url = None;
356 let mut download_url = None;
357
358 if let Some(source) = json.get(FIELD_SOURCE) {
359 if let Some(source_obj) = source.as_object() {
360 if let Some(git_url) = source_obj.get("git").and_then(|v| v.as_str()) {
362 let git_str = truncate_field(git_url.trim().to_string());
363 if !git_str.is_empty() {
364 vcs_url = Some(git_str);
365 }
366 }
367
368 if let Some(http_url) = source_obj.get("http").and_then(|v| v.as_str()) {
370 let http_str = truncate_field(http_url.trim().to_string());
371 if !http_str.is_empty() {
372 download_url = Some(http_str);
373 }
374 }
375 } else if let Some(source_str) = source.as_str() {
376 let source_trimmed = truncate_field(source_str.trim().to_string());
378 if !source_trimmed.is_empty() {
379 vcs_url = Some(source_trimmed);
380 }
381 }
382 }
383
384 (vcs_url, download_url)
385}
386
387fn extract_parties(json: &Value) -> Vec<Party> {
389 let mut parties = Vec::new();
390
391 if let Some(authors) = json.get(FIELD_AUTHORS) {
392 if let Some(authors_obj) = authors.as_object() {
393 for (name, value) in authors_obj.iter().capped("podspec.json authors") {
395 let name_str = truncate_field(name.trim().to_string());
396 if !name_str.is_empty() {
397 let url = value.as_str().and_then(|s| {
398 let trimmed = s.trim();
399 if trimmed.is_empty() {
400 None
401 } else if trimmed.contains("://") || trimmed.contains('.') {
402 Some(truncate_field(trimmed.to_string()))
403 } else {
404 Some(truncate_field(format!("{}.com", trimmed)))
405 }
406 });
407
408 parties.push(Party {
409 r#type: Some(PartyType::Organization),
410 role: Some("owner".to_string()),
411 name: Some(name_str),
412 email: None,
413 url,
414 organization: None,
415 organization_url: None,
416 timezone: None,
417 });
418 }
419 }
420 } else if let Some(authors_str) = authors.as_str() {
421 let authors_trimmed = truncate_field(authors_str.trim().to_string());
423 if !authors_trimmed.is_empty() {
424 parties.push(Party {
425 r#type: Some(PartyType::Organization),
426 role: Some("owner".to_string()),
427 name: Some(authors_trimmed),
428 email: None,
429 url: None,
430 organization: None,
431 organization_url: None,
432 timezone: None,
433 });
434 }
435 }
436 }
437
438 parties
439}
440
441fn extract_dependencies(json: &Value) -> Vec<Dependency> {
443 let mut dependencies = Vec::new();
444
445 if let Some(deps) = json.get(FIELD_DEPENDENCIES)
446 && let Some(deps_obj) = deps.as_object()
447 {
448 for (name, requirement) in deps_obj.iter().capped("podspec.json dependencies") {
449 let name_str = name.trim();
450 if name_str.is_empty() {
451 continue;
452 }
453
454 let requirement_str = requirement
455 .as_str()
456 .map(|s| truncate_field(s.trim().to_string()))
457 .filter(|s| !s.is_empty());
458
459 let purl = build_cocoapods_purl(name_str, None).map(truncate_field);
460
461 dependencies.push(Dependency {
462 purl,
463 extracted_requirement: requirement_str,
464 scope: Some("runtime".to_string()),
465 is_runtime: Some(true),
466 is_optional: Some(false),
467 is_pinned: None,
468 is_direct: None,
469 resolved_package: None,
470 extra_data: None,
471 });
472 }
473 }
474
475 dependencies
476}
477
478fn get_repo_base_url(vcs_url: &str) -> Option<String> {
480 if vcs_url.is_empty() {
481 return None;
482 }
483
484 if vcs_url.ends_with(".git") {
485 Some(vcs_url.trim_end_matches(".git").to_string())
486 } else {
487 Some(vcs_url.to_string())
488 }
489}
490
491fn get_hashed_path(name: &str) -> Option<String> {
495 use md5::{Digest, Md5};
496
497 if name.is_empty() {
498 return None;
499 }
500
501 let mut hasher = Md5::new();
503 hasher.update(name.as_bytes());
504 let result = hasher.finalize();
505 let hash_str = hex::encode(result);
506
507 if hash_str.len() >= 3 {
508 Some(format!(
509 "{}/{}/{}",
510 &hash_str[0..1],
511 &hash_str[1..2],
512 &hash_str[2..3]
513 ))
514 } else {
515 Some(hash_str)
516 }
517}