Skip to main content

provenant/parsers/
podfile.rs

1//! Parser for CocoaPods Podfile manifest files.
2//!
3//! Extracts dependency declarations from Podfile using regex-based Ruby Domain-Specific
4//! Language (DSL) parsing without full Ruby AST parsing.
5//!
6//! # Supported Formats
7//! - Podfile (CocoaPods manifest with Ruby DSL syntax)
8//!
9//! # Key Features
10//! - Regex-based Ruby DSL parsing for dependency declarations
11//! - Support for git, path, and source dependencies
12//! - Pod groups and target-specific dependencies
13//! - Version constraint parsing (exact, ranges, pessimistic)
14//! - Source URL extraction for custom pod repositories
15//!
16//! # Implementation Notes
17//! - Uses regex for pattern matching (not full Ruby parser)
18//! - Supports syntax: `pod 'Name', 'version'`, `pod 'Name', :git => 'url'`
19//! - Local path dependencies (`:path =>`) are tracked as dependencies
20//! - Graceful error handling with `warn!()` logs
21
22use std::fs;
23use std::path::Path;
24
25use lazy_static::lazy_static;
26use log::warn;
27use packageurl::PackageUrl;
28use regex::Regex;
29
30use crate::models::{DatasourceId, Dependency, PackageData, PackageType};
31use crate::parsers::PackageParser;
32
33/// Parses CocoaPods Podfile dependency files.
34///
35/// Extracts dependency declarations from Podfile using regex-based Ruby DSL parsing.
36///
37/// # Supported Syntax
38/// - `pod 'Name', 'version'` - Standard pod with version
39/// - `pod 'Name'` - Pod without version constraint
40/// - `pod 'Name', :git => 'url'` - Git dependency
41/// - `pod 'Name', :path => '../LocalPod'` - Local path dependency
42/// - `pod 'Firebase/Analytics'` - Subspecs
43/// - Version operators: `~>`, `>=`, `<=`, etc.
44pub struct PodfileParser;
45
46impl PackageParser for PodfileParser {
47    const PACKAGE_TYPE: PackageType = PackageType::Cocoapods;
48
49    fn is_match(path: &Path) -> bool {
50        path.file_name().is_some_and(|name| {
51            name.to_string_lossy().ends_with("Podfile")
52                && !name.to_string_lossy().ends_with("Podfile.lock")
53        })
54    }
55
56    fn extract_packages(path: &Path) -> Vec<PackageData> {
57        let content = match fs::read_to_string(path) {
58            Ok(c) => c,
59            Err(e) => {
60                warn!("Failed to read {:?}: {}", path, e);
61                return vec![default_package_data()];
62            }
63        };
64
65        let dependencies = extract_dependencies(&content);
66
67        vec![PackageData {
68            package_type: Some(Self::PACKAGE_TYPE),
69            namespace: None,
70            name: None,
71            version: None,
72            qualifiers: None,
73            subpath: None,
74            primary_language: Some("Objective-C".to_string()),
75            description: None,
76            release_date: None,
77            parties: Vec::new(),
78            keywords: Vec::new(),
79            homepage_url: None,
80            download_url: None,
81            size: None,
82            sha1: None,
83            md5: None,
84            sha256: None,
85            sha512: None,
86            bug_tracking_url: None,
87            code_view_url: None,
88            vcs_url: None,
89            copyright: None,
90            holder: None,
91            declared_license_expression: None,
92            declared_license_expression_spdx: None,
93            license_detections: Vec::new(),
94            other_license_expression: None,
95            other_license_expression_spdx: None,
96            other_license_detections: Vec::new(),
97            extracted_license_statement: None,
98            notice_text: None,
99            source_packages: Vec::new(),
100            file_references: Vec::new(),
101            extra_data: None,
102            dependencies,
103            repository_homepage_url: None,
104            repository_download_url: None,
105            api_data_url: None,
106            datasource_id: Some(DatasourceId::CocoapodsPodfile),
107            purl: None,
108            is_private: false,
109            is_virtual: false,
110        }]
111    }
112}
113
114fn default_package_data() -> PackageData {
115    PackageData {
116        package_type: Some(PodfileParser::PACKAGE_TYPE),
117        primary_language: Some("Objective-C".to_string()),
118        datasource_id: Some(DatasourceId::CocoapodsPodfile),
119        ..Default::default()
120    }
121}
122
123lazy_static! {
124    static ref POD_PATTERN: Regex = Regex::new(
125        r#"pod\s+['"]([^'"]+)['"](?:\s*,\s*['"]([^'"]+)['"])?(?:\s*,\s*:git\s*=>\s*['"]([^'"]+)['"])?(?:\s*,\s*:path\s*=>\s*['"]([^'"]+)['"])?"#
126    ).unwrap();
127}
128
129/// Extract dependencies from Podfile
130fn extract_dependencies(content: &str) -> Vec<Dependency> {
131    let mut dependencies = Vec::new();
132
133    for line in content.lines() {
134        let cleaned_line = pre_process(line);
135        if let Some(caps) = POD_PATTERN.captures(&cleaned_line) {
136            let name = caps.get(1).map(|m| m.as_str()).unwrap_or("");
137            let version_req = caps.get(2).map(|m| m.as_str().to_string());
138            let git_url = caps.get(3).map(|m| m.as_str().to_string());
139            let local_path = caps.get(4).map(|m| m.as_str().to_string());
140
141            if let Some(dep) = create_dependency(name, version_req, git_url, local_path) {
142                dependencies.push(dep);
143            }
144        }
145    }
146
147    dependencies
148}
149
150/// Create a Dependency from parsed components
151fn create_dependency(
152    name: &str,
153    version_req: Option<String>,
154    _git_url: Option<String>,
155    _local_path: Option<String>,
156) -> Option<Dependency> {
157    if name.is_empty() {
158        return None;
159    }
160
161    let purl = PackageUrl::new("cocoapods", name).ok()?;
162
163    let is_pinned = version_req
164        .as_ref()
165        .map(|v| !v.contains(&['~', '>', '<', '='][..]))
166        .unwrap_or(false);
167
168    Some(Dependency {
169        purl: Some(purl.to_string()),
170        extracted_requirement: version_req,
171        scope: Some("dependencies".to_string()),
172        is_runtime: None,
173        is_optional: None,
174        is_pinned: Some(is_pinned),
175        is_direct: Some(true),
176        resolved_package: None,
177        extra_data: None,
178    })
179}
180
181/// Pre-process a line by removing comments and trimming
182fn pre_process(line: &str) -> String {
183    let line = if let Some(comment_pos) = line.find('#') {
184        &line[..comment_pos]
185    } else {
186        line
187    };
188    line.trim().to_string()
189}
190
191crate::register_parser!(
192    "CocoaPods Podfile",
193    &["**/Podfile", "**/*.podfile"],
194    "cocoapods",
195    "Objective-C",
196    Some("https://guides.cocoapods.org/using/the-podfile.html"),
197);
198
199#[cfg(test)]
200mod tests {
201    use super::*;
202
203    #[test]
204    fn test_is_match() {
205        assert!(PodfileParser::is_match(Path::new("Podfile")));
206        assert!(PodfileParser::is_match(Path::new("project/Podfile")));
207        assert!(!PodfileParser::is_match(Path::new("Podfile.lock")));
208        assert!(!PodfileParser::is_match(Path::new("MyLib.podspec")));
209        assert!(!PodfileParser::is_match(Path::new("MyLib.podspec.json")));
210    }
211
212    #[test]
213    fn test_extract_simple_pod() {
214        let content = r#"
215platform :ios, '9.0'
216
217target 'MyApp' do
218  pod 'AFNetworking', '~> 4.0'
219  pod 'Alamofire'
220end
221"#;
222        let deps = extract_dependencies(content);
223        assert_eq!(deps.len(), 2);
224
225        assert_eq!(deps[0].purl, Some("pkg:cocoapods/AFNetworking".to_string()));
226        assert_eq!(deps[0].extracted_requirement, Some("~> 4.0".to_string()));
227        assert_eq!(deps[0].is_pinned, Some(false));
228        assert_eq!(deps[0].scope, Some("dependencies".to_string()));
229        assert_eq!(deps[0].is_runtime, None);
230        assert_eq!(deps[0].is_optional, None);
231
232        assert_eq!(deps[1].purl, Some("pkg:cocoapods/Alamofire".to_string()));
233        assert_eq!(deps[1].extracted_requirement, None);
234    }
235
236    #[test]
237    fn test_extract_pod_with_git() {
238        let content = r#"
239pod 'AFNetworking', :git => 'https://github.com/AFNetworking/AFNetworking.git'
240"#;
241        let deps = extract_dependencies(content);
242        assert_eq!(deps.len(), 1);
243        assert_eq!(deps[0].purl, Some("pkg:cocoapods/AFNetworking".to_string()));
244    }
245
246    #[test]
247    fn test_extract_pod_with_path() {
248        let content = r#"
249pod 'MyLocalPod', :path => '../MyLocalPod'
250"#;
251        let deps = extract_dependencies(content);
252        assert_eq!(deps.len(), 1);
253        assert_eq!(deps[0].purl, Some("pkg:cocoapods/MyLocalPod".to_string()));
254    }
255
256    #[test]
257    fn test_extract_pod_with_version_and_git() {
258        let content = r#"
259pod 'RestKit', '~> 0.20', :git => 'https://github.com/RestKit/RestKit.git'
260"#;
261        let deps = extract_dependencies(content);
262        assert_eq!(deps.len(), 1);
263        assert_eq!(deps[0].purl, Some("pkg:cocoapods/RestKit".to_string()));
264        assert_eq!(deps[0].extracted_requirement, Some("~> 0.20".to_string()));
265    }
266
267    #[test]
268    fn test_ignores_comments() {
269        let content = r#"
270# pod 'Commented', '1.0'
271pod 'Active', '2.0'  # inline comment
272"#;
273        let deps = extract_dependencies(content);
274        assert_eq!(deps.len(), 1);
275        assert_eq!(deps[0].purl, Some("pkg:cocoapods/Active".to_string()));
276    }
277}