Skip to main content

features_cli/
feature_metadata_detector.rs

1//! Module for detecting feature metadata in source code comments
2//!
3//! This module scans source files for special comments that start with "--feature-"
4//! and contain feature metadata. It supports multiple programming languages
5//! and their respective comment styles.
6
7use anyhow::Result;
8use indexmap::IndexMap;
9use std::collections::HashMap;
10use std::fs;
11use std::path::Path;
12use walkdir::WalkDir;
13
14use crate::skip_dirs::is_non_source_dir;
15
16/// Represents a single metadata entry's properties (key-value pairs)
17/// Uses IndexMap to preserve insertion order from comments
18type MetadataProperties = IndexMap<String, String>;
19
20/// Represents a list of metadata entries for a specific metadata key
21type MetadataEntries = Vec<MetadataProperties>;
22
23/// Maps metadata keys (e.g., "flag") to their entries
24type MetadataByKey = HashMap<String, MetadataEntries>;
25
26/// Maps feature paths to their metadata, organized by metadata key
27pub type FeatureMetadataMap = HashMap<String, MetadataByKey>;
28
29#[derive(Debug, Clone)]
30pub struct FeatureMetadataComment {
31    #[allow(dead_code)]
32    pub file_path: String,
33    #[allow(dead_code)]
34    pub line_number: usize,
35    pub metadata_key: String,
36    pub properties: MetadataProperties,
37}
38
39/// Detects comment start patterns for various languages based on file extension
40fn get_comment_patterns(extension: &str) -> Vec<CommentPattern> {
41    match extension {
42        // C-style comments (C, C++, Java, JavaScript, TypeScript, Rust, etc.)
43        "rs" | "c" | "cpp" | "cc" | "cxx" | "h" | "hpp" | "java" | "js" | "jsx" | "ts" | "tsx"
44        | "go" | "cs" | "swift" | "kt" | "scala" => vec![
45            CommentPattern::LineComment("//"),
46            CommentPattern::BlockComment("/*", "*/"),
47        ],
48        // Python, Bash, Shell, Ruby, Perl, YAML, etc.
49        "py" | "sh" | "bash" | "rb" | "pl" | "yml" | "yaml" | "toml" => {
50            vec![CommentPattern::LineComment("#")]
51        }
52        // HTML, XML
53        "html" | "xml" | "svg" => vec![CommentPattern::BlockComment("<!--", "-->")],
54        // CSS, SCSS, Less
55        "css" | "scss" | "less" => vec![
56            CommentPattern::LineComment("//"),
57            CommentPattern::BlockComment("/*", "*/"),
58        ],
59        // Lua
60        "lua" => vec![
61            CommentPattern::LineComment("--"),
62            CommentPattern::BlockComment("--[[", "]]"),
63        ],
64        // SQL
65        "sql" => vec![
66            CommentPattern::LineComment("--"),
67            CommentPattern::BlockComment("/*", "*/"),
68        ],
69        // Default: try common patterns
70        _ => vec![
71            CommentPattern::LineComment("//"),
72            CommentPattern::LineComment("#"),
73            CommentPattern::BlockComment("/*", "*/"),
74        ],
75    }
76}
77
78#[derive(Debug, Clone)]
79enum CommentPattern {
80    LineComment(&'static str),
81    BlockComment(&'static str, &'static str),
82}
83
84/// Extracts the content from a comment, handling different comment styles
85fn extract_comment_content(line: &str, patterns: &[CommentPattern]) -> Option<String> {
86    let trimmed = line.trim();
87
88    for pattern in patterns {
89        match pattern {
90            CommentPattern::LineComment(prefix) => {
91                if let Some(content) = trimmed.strip_prefix(prefix) {
92                    return Some(content.trim().to_string());
93                }
94            }
95            CommentPattern::BlockComment(start, end) => {
96                if let Some(mut content) = trimmed.strip_prefix(start) {
97                    // Remove ending marker if present on same line
98                    if let Some(stripped) = content.strip_suffix(end) {
99                        content = stripped;
100                    }
101                    return Some(content.trim().to_string());
102                }
103            }
104        }
105    }
106
107    None
108}
109
110/// Parses properties from a feature flag comment
111/// Format: "key: value, key2: value2, ..."
112/// Preserves the order of properties as they appear in the comment
113fn parse_properties(content: &str) -> MetadataProperties {
114    let mut properties = IndexMap::new();
115
116    // Split by comma and parse key:value pairs
117    for part in content.split(',') {
118        let part = part.trim();
119        if let Some(colon_pos) = part.find(':') {
120            let key = part[..colon_pos].trim();
121            let value = part[colon_pos + 1..].trim();
122
123            if !key.is_empty() {
124                properties.insert(key.to_string(), value.to_string());
125            }
126        }
127    }
128
129    properties
130}
131
132/// Checks if a line contains a feature metadata comment
133/// Returns the metadata key (e.g., "flag" from "--feature-flag") and the properties
134fn check_line_for_feature_metadata(
135    line: &str,
136    patterns: &[CommentPattern],
137) -> Option<(String, MetadataProperties)> {
138    if let Some(comment_content) = extract_comment_content(line, patterns) {
139        // Check if the comment contains "--feature-" pattern
140        if let Some(feature_start) = comment_content.find("--feature-") {
141            // Extract the metadata key (e.g., "--feature-flag" -> "flag")
142            let after_dashes = &comment_content[feature_start + 2..]; // Skip "--"
143
144            // Find where the metadata key ends (at space, comma, or end of string)
145            let metadata_key_end = after_dashes
146                .find(|c: char| c.is_whitespace() || c == ',')
147                .unwrap_or(after_dashes.len());
148
149            let full_key = after_dashes[..metadata_key_end].to_string();
150
151            // Strip "feature-" prefix to get just the key (e.g., "feature-flag" -> "flag")
152            let metadata_key = full_key
153                .strip_prefix("feature-")
154                .unwrap_or(&full_key)
155                .to_string();
156
157            // Extract everything after the metadata key for property parsing
158            let properties_start = feature_start + 2 + metadata_key_end; // +2 for "--"
159            let properties_content = if properties_start < comment_content.len() {
160                comment_content[properties_start..].trim_start()
161            } else {
162                ""
163            };
164
165            // Parse properties from the content after the metadata key
166            let properties = parse_properties(properties_content);
167
168            // Only return if we actually found some properties or patterns
169            if !properties.is_empty() {
170                return Some((metadata_key, properties));
171            }
172        }
173    }
174
175    None
176}
177
178/// Scans a single file for feature metadata comments
179fn scan_file(file_path: &Path) -> Result<Vec<FeatureMetadataComment>> {
180    let mut results = Vec::new();
181
182    // Get file extension
183    let extension = file_path.extension().and_then(|e| e.to_str()).unwrap_or("");
184
185    let patterns = get_comment_patterns(extension);
186
187    // Read file content
188    let content = fs::read_to_string(file_path)?;
189
190    // Check each line
191    for (line_number, line) in content.lines().enumerate() {
192        if let Some((metadata_key, properties)) = check_line_for_feature_metadata(line, &patterns) {
193            results.push(FeatureMetadataComment {
194                file_path: file_path.to_string_lossy().to_string(),
195                line_number: line_number + 1, // Line numbers are 1-based
196                metadata_key,
197                properties,
198            });
199        }
200    }
201
202    Ok(results)
203}
204
205/// Attempts to infer the feature path from a file path by looking for a 'features' directory
206/// in the path hierarchy and extracting the path from base to the feature directory
207///
208/// For example (with base_path as project root):
209/// - `src/features/user-auth/component.tsx` -> Some("src/features/user-auth")
210/// - `libs/features/api-v2/utils.ts` -> Some("libs/features/api-v2")
211/// - `src/components/Button.tsx` -> None
212fn infer_feature_path_from_file(file_path: &Path, base_path: &Path) -> Option<String> {
213    // Get the relative path from base_path
214    let relative_path = file_path.strip_prefix(base_path).ok()?;
215
216    // Look for 'features' directory in the path components
217    let components: Vec<_> = relative_path.components().collect();
218
219    for (i, component) in components.iter().enumerate() {
220        if let Some(os_str) = component.as_os_str().to_str()
221            && os_str == "features"
222            && let Some(_next_component) = components.get(i + 1)
223        {
224            // Build the path up to and including the feature directory (i+1)
225            let mut feature_path = std::path::PathBuf::new();
226            for j in 0..=i + 1 {
227                if let Some(comp) = components.get(j) {
228                    feature_path.push(comp);
229                }
230            }
231            return Some(feature_path.to_string_lossy().to_string());
232        }
233    }
234
235    None
236}
237
238/// Scans a directory recursively for feature metadata comments
239///
240/// Returns a nested map:
241/// - Outer key: feature name (from "feature:feature-1")
242/// - Inner key: metadata key (e.g., "flag" from "--feature-flag", "experiment" from "--feature-experiment")
243/// - Value: vector of property maps
244pub fn scan_directory_for_feature_metadata(dir_path: &Path) -> Result<FeatureMetadataMap> {
245    let mut feature_metadata = FeatureMetadataMap::new();
246
247    // Collect all entries first
248    let mut entries: Vec<_> = WalkDir::new(dir_path)
249        .into_iter()
250        .filter_entry(|e| {
251            if e.file_type().is_dir() {
252                let dir_name = e.file_name().to_string_lossy();
253                !is_non_source_dir(&dir_name)
254            } else {
255                true
256            }
257        })
258        .filter_map(|e| e.ok())
259        .collect();
260
261    // Sort entries by path for consistent cross-platform behavior
262    entries.sort_by(|a, b| a.path().cmp(b.path()));
263
264    for entry in entries {
265        if entry.file_type().is_file()
266            && let Ok(comments) = scan_file(entry.path())
267        {
268            for comment in comments {
269                // Get the feature path from the properties, or infer from file path
270                let feature_path = comment
271                    .properties
272                    .get("feature")
273                    .cloned()
274                    .or_else(|| infer_feature_path_from_file(entry.path(), dir_path));
275
276                if let Some(feature_path) = feature_path {
277                    feature_metadata
278                        .entry(feature_path)
279                        .or_default()
280                        .entry(comment.metadata_key)
281                        .or_default()
282                        .push(comment.properties);
283                }
284            }
285        }
286    }
287
288    Ok(feature_metadata)
289}
290
291#[cfg(test)]
292mod tests {
293    use super::*;
294
295    #[test]
296    fn test_extract_comment_content_single_line() {
297        let patterns = vec![CommentPattern::LineComment("//")];
298        let line = "// This is a comment";
299        assert_eq!(
300            extract_comment_content(line, &patterns),
301            Some("This is a comment".to_string())
302        );
303    }
304
305    #[test]
306    fn test_extract_comment_content_block() {
307        let patterns = vec![CommentPattern::BlockComment("/*", "*/")];
308        let line = "/* This is a block comment */";
309        assert_eq!(
310            extract_comment_content(line, &patterns),
311            Some("This is a block comment".to_string())
312        );
313    }
314
315    #[test]
316    fn test_extract_comment_content_hash() {
317        let patterns = vec![CommentPattern::LineComment("#")];
318        let line = "# This is a Python comment";
319        assert_eq!(
320            extract_comment_content(line, &patterns),
321            Some("This is a Python comment".to_string())
322        );
323    }
324
325    #[test]
326    fn test_parse_properties() {
327        let content =
328            "feature:feature-1, type: experiment, owner: #owner, introduced_on: 2025-12-31";
329        let props = parse_properties(content);
330
331        assert_eq!(props.get("feature"), Some(&"feature-1".to_string()));
332        assert_eq!(props.get("type"), Some(&"experiment".to_string()));
333        assert_eq!(props.get("owner"), Some(&"#owner".to_string()));
334        assert_eq!(props.get("introduced_on"), Some(&"2025-12-31".to_string()));
335    }
336
337    #[test]
338    fn test_check_line_for_feature_metadata_js_style() {
339        let patterns = vec![CommentPattern::BlockComment("/*", "*/")];
340        let line = "/** --feature-flag feature:feature-1, type: experiment, owner: #owner */";
341
342        let result = check_line_for_feature_metadata(line, &patterns);
343        assert!(result.is_some());
344
345        let (metadata_key, props) = result.unwrap();
346        assert_eq!(metadata_key, "flag");
347        assert_eq!(props.get("feature"), Some(&"feature-1".to_string()));
348        assert_eq!(props.get("type"), Some(&"experiment".to_string()));
349    }
350    #[test]
351    fn test_check_line_for_feature_metadata_rust_style() {
352        let patterns = vec![CommentPattern::LineComment("//")];
353        let line = "// --feature-flag feature:my-feature, enabled: true";
354
355        let result = check_line_for_feature_metadata(line, &patterns);
356        assert!(result.is_some());
357
358        let (metadata_key, props) = result.unwrap();
359        assert_eq!(metadata_key, "flag");
360        assert_eq!(props.get("feature"), Some(&"my-feature".to_string()));
361        assert_eq!(props.get("enabled"), Some(&"true".to_string()));
362    }
363
364    #[test]
365    fn test_check_line_for_feature_metadata_python_style() {
366        let patterns = vec![CommentPattern::LineComment("#")];
367        let line = "# --feature-flag feature:analytics, team: data-team";
368
369        let result = check_line_for_feature_metadata(line, &patterns);
370        assert!(result.is_some());
371
372        let (metadata_key, props) = result.unwrap();
373        assert_eq!(metadata_key, "flag");
374        assert_eq!(props.get("feature"), Some(&"analytics".to_string()));
375        assert_eq!(props.get("team"), Some(&"data-team".to_string()));
376    }
377
378    #[test]
379    fn test_no_feature_metadata_in_regular_comment() {
380        let patterns = vec![CommentPattern::LineComment("//")];
381        let line = "// This is just a regular comment";
382
383        assert!(check_line_for_feature_metadata(line, &patterns).is_none());
384    }
385
386    #[test]
387    fn test_different_metadata_keys() {
388        let patterns = vec![CommentPattern::LineComment("//")];
389
390        let line1 = "// --feature-experiment feature:test-feature, status: active";
391        let result1 = check_line_for_feature_metadata(line1, &patterns);
392        assert!(result1.is_some());
393        let (metadata_key1, _) = result1.unwrap();
394        assert_eq!(metadata_key1, "experiment");
395
396        let line2 = "// --feature-toggle feature:another-feature, enabled: true";
397        let result2 = check_line_for_feature_metadata(line2, &patterns);
398        assert!(result2.is_some());
399        let (metadata_key2, _) = result2.unwrap();
400        assert_eq!(metadata_key2, "toggle");
401    }
402}