features-cli 0.14.0

A CLI tool for discovering the features in a folder
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
use anyhow::Result;
use clap::Parser;
use indicatif::{ProgressBar, ProgressStyle};
use std::collections::HashSet;

mod build;
mod checker;
mod codeowners;
mod coverage_parser;
mod dependency_resolver;
mod feature_metadata_detector;
mod features_toml_parser;
mod file_scanner;
mod git_helper;
mod http_server;
mod import_detector;
mod models;
mod printer;
mod readme_parser;
mod scan;
mod skip_dirs;

use build::{BuildConfig, create_build};
use checker::run_checks;
use codeowners::generate_codeowners;
use http_server::serve_features_with_watching;
use models::Feature;
use printer::print_features;
use scan::{ScanConfig, scan_features};

/// A CLI tool for discovering features in a folder by reading README.md or README.mdx files,
/// and serving them via HTTP or static builds.
#[derive(Parser)]
#[command(name = "features")]
#[command(author = env!("CARGO_PKG_AUTHORS"))]
#[command(about = env!("CARGO_PKG_DESCRIPTION"))]
#[command(arg_required_else_help = true)]
struct Cli {
    /// The path to the directory to list
    #[arg(required = false)]
    path: Option<std::path::PathBuf>,

    /// Print version information
    #[arg(short = 'V', long)]
    version: bool,

    /// Output features as JSON
    #[arg(long)]
    json: bool,

    /// Output features as a flat array instead of nested structure
    #[arg(long)]
    flat: bool,

    /// Include descriptions in the output
    #[arg(long)]
    description: bool,

    /// Display only unique list of owners
    #[arg(long)]
    list_owners: bool,

    /// Run checks on features (e.g., duplicate names)
    #[arg(long)]
    check: bool,

    /// Start an HTTP server to serve the features
    #[arg(long)]
    serve: bool,

    /// Port for the HTTP server (default: 3000)
    #[arg(long, default_value = "3000")]
    port: u16,

    /// Create a static build with embedded files and features.json
    #[arg(long)]
    build: bool,

    /// Output directory for the static build
    #[arg(long, default_value = "build")]
    build_dir: std::path::PathBuf,

    /// Skip computing changes (git commits and decisions) in the output
    #[arg(long)]
    skip_changes: bool,

    /// Find the owner of a specific file or folder
    #[arg(long)]
    find_owner: Option<String>,

    /// Path to the coverage directory (overrides default search)
    #[arg(long)]
    coverage_dir: Option<std::path::PathBuf>,

    /// Include coverage information in the output
    #[arg(long)]
    coverage: bool,

    /// Generate or update CODEOWNERS file
    #[arg(long)]
    generate_codeowners: bool,

    /// Project directory for CODEOWNERS file generation
    #[arg(long)]
    project_dir: Option<std::path::PathBuf>,

    /// Custom path and filename for CODEOWNERS file (default: CODEOWNERS)
    #[arg(long)]
    codeowners_path: Option<std::path::PathBuf>,

    /// Custom prefix for owner names in CODEOWNERS file (default: @)
    #[arg(long, default_value = "@")]
    codeowners_prefix: String,

    /// Ignore a folder and all its subfolders when scanning for features (can be repeated)
    #[arg(long)]
    ignore_path: Vec<std::path::PathBuf>,

    /// Also scan folders skipped by default (node_modules) for features, stats and imports
    #[arg(long)]
    include_skipped_dirs: bool,
}

/// Resolve `--ignore-path` values to canonical absolute paths.
///
/// Relative paths are resolved against `current_dir`. Paths that don't exist are
/// skipped with a warning rather than causing a hard error.
fn resolve_ignore_paths(
    ignore_paths: &[std::path::PathBuf],
    current_dir: &std::path::Path,
) -> Vec<std::path::PathBuf> {
    ignore_paths
        .iter()
        .filter_map(|raw_path| {
            let candidate = if raw_path.is_absolute() {
                raw_path.clone()
            } else {
                current_dir.join(raw_path)
            };

            match std::fs::canonicalize(&candidate) {
                Ok(canonical) => Some(canonical),
                Err(_) => {
                    eprintln!(
                        "Warning: --ignore-path '{}' does not exist, skipping.",
                        raw_path.display()
                    );
                    None
                }
            }
        })
        .collect()
}

fn flatten_features(features: &[Feature]) -> Vec<Feature> {
    let mut flat_features = Vec::new();

    for feature in features {
        // Create a flattened version of this feature (without nested features)
        let flat_feature = Feature {
            name: feature.name.clone(),
            description: feature.description.clone(),
            owner: feature.owner.clone(),
            is_owner_inherited: feature.is_owner_inherited,
            path: feature.path.clone(),
            features: Vec::new(), // Empty for flat structure
            meta: feature.meta.clone(),
            changes: Vec::new(),
            decisions: Vec::new(),
            stats: feature.stats.clone(),
            dependencies: feature.dependencies.clone(),
        };

        flat_features.push(flat_feature);

        // Recursively flatten nested features
        let nested_flat = flatten_features(&feature.features);
        flat_features.extend(nested_flat);
    }

    flat_features
}

#[derive(Debug, serde::Serialize)]
struct OwnerInfo {
    owner: String,
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    inherited: bool,
    feature_name: String,
    feature_path: String,
}

fn find_owner_for_path(
    target_path: &std::path::Path,
    features: &[Feature],
    base_path: &std::path::Path,
) -> Option<OwnerInfo> {
    // Canonicalize the target path
    let canonical_target = std::fs::canonicalize(target_path).ok()?;

    // Helper function to recursively search for the closest feature
    fn find_closest_feature(
        target: &std::path::Path,
        features: &[Feature],
        _parent_owner: Option<&str>,
        base_path: &std::path::Path,
    ) -> Option<OwnerInfo> {
        let mut best_match: Option<OwnerInfo> = None;
        let mut best_match_depth = usize::MAX;

        for feature in features {
            let feature_path = base_path.join(&feature.path);
            if let Ok(canonical_feature_path) = std::fs::canonicalize(&feature_path) {
                // Check if target is within this feature's directory
                if target.starts_with(&canonical_feature_path) {
                    // Calculate depth (how many components between feature and target)
                    let depth = target
                        .strip_prefix(&canonical_feature_path)
                        .ok()
                        .map(|p| p.components().count())
                        .unwrap_or(usize::MAX);

                    // Check nested features first
                    if let Some(nested_match) = find_closest_feature(
                        target,
                        &feature.features,
                        Some(&feature.owner),
                        base_path,
                    ) {
                        if best_match.is_none() || depth < best_match_depth {
                            best_match = Some(nested_match);
                            best_match_depth = depth;
                        }
                    } else {
                        // This is the closest feature so far
                        if depth < best_match_depth {
                            let owner = OwnerInfo {
                                owner: feature.owner.clone(),
                                inherited: feature.is_owner_inherited,
                                feature_name: feature.name.clone(),
                                feature_path: feature.path.clone(),
                            };
                            best_match = Some(owner);
                            best_match_depth = depth;
                        }
                    }
                }
            }
        }

        best_match
    }

    find_closest_feature(&canonical_target, features, None, base_path)
}

/// Add coverage data from .coverage and coverage directories to features
/// Add coverage data to features by searching for coverage reports in multiple locations.
///
/// This function searches for coverage reports in the following priority order:
/// 1. If `coverage_dir_override` is provided, only that directory is checked
/// 2. Otherwise, searches in this order (stops at first directory with coverage data):
///    - `base_path/.coverage`
///    - `base_path/coverage`
///    - `current_dir/.coverage`
///    - `current_dir/coverage`
///    - `project_dir/.coverage` (if project_dir is provided)
///    - `project_dir/coverage` (if project_dir is provided)
///
/// # Arguments
///
/// * `features` - Mutable reference to features that will be updated with coverage data
/// * `base_path` - Base path of the project being analyzed
/// * `coverage_dir_override` - Optional explicit coverage directory (takes precedence over all)
/// * `current_dir` - Current working directory where the CLI is executed
/// * `project_dir` - Optional project directory for additional coverage locations
///
/// # Behavior
///
/// - Stops searching after finding coverage data in the first valid directory
/// - Only processes directories that contain actual coverage files
/// - Updates feature stats with coverage information (line/branch coverage percentages)
fn extract_unique_owners(features: &[Feature]) -> Vec<String> {
    let mut owners_set = HashSet::new();

    fn collect_owners(features: &[Feature], owners_set: &mut HashSet<String>) {
        for feature in features {
            owners_set.insert(feature.owner.clone());
            collect_owners(&feature.features, owners_set);
        }
    }

    collect_owners(features, &mut owners_set);

    let mut owners: Vec<String> = owners_set.into_iter().collect();
    owners.sort(); // Sort alphabetically
    owners
}

#[tokio::main]
async fn main() -> Result<()> {
    let args = Cli::parse();

    // Handle version flag
    if args.version {
        println!("{}", env!("CARGO_PKG_VERSION"));
        return Ok(());
    }

    // Handle find-owner flag - this requires a target path but not the base path
    if let Some(target_file) = &args.find_owner {
        let target_path = std::path::PathBuf::from(target_file);

        if !target_path.exists() {
            eprintln!("Error: Path '{}' does not exist.", target_file);
            std::process::exit(1);
        }

        // Determine the base path to scan for features
        let base_path = if let Some(p) = &args.path {
            p.clone()
        } else {
            // Use current directory or try to find a suitable base
            std::env::current_dir()?
        };

        let current_dir = std::env::current_dir()?;
        let ignore_paths = resolve_ignore_paths(&args.ignore_path, &current_dir);
        let config = ScanConfig::new(&current_dir)
            .skip_changes(args.skip_changes)
            .ignore_paths(ignore_paths)
            .ownership_only(true)
            .include_skipped_dirs(args.include_skipped_dirs);

        let features = scan_features(&base_path, config)?;

        match find_owner_for_path(&target_path, &features, &base_path) {
            Some(owner_info) => {
                if args.json {
                    let json = serde_json::to_string_pretty(&owner_info)?;
                    println!("{}", json);
                } else {
                    println!(
                        "Owner: {}{}",
                        owner_info.owner,
                        if owner_info.inherited {
                            " (inherited)"
                        } else {
                            ""
                        }
                    );
                    println!("Feature: {}", owner_info.feature_name);
                    println!("Feature Path: {}", owner_info.feature_path);
                }
            }
            None => {
                eprintln!("No feature found for path: {}", target_file);
                std::process::exit(1);
            }
        }

        return Ok(());
    }

    // If no path is provided and no special flags are used, show help
    let path = match args.path {
        Some(p) => p,
        None => {
            // If we get here, it means no version/help flag was used
            // This shouldn't happen with arg_required_else_help, but just in case
            eprintln!("Error: The path argument is required.");
            eprintln!("Try 'features --help' for more information.");
            std::process::exit(1);
        }
    };

    // Handle serve flag - show spinner while loading
    let spinner = if args.serve {
        let pb = ProgressBar::new_spinner();
        pb.set_style(
            ProgressStyle::default_spinner()
                .template("{spinner:.green} {msg}")
                .unwrap()
                .tick_strings(&["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]),
        );
        pb.set_message(format!(
            "Starting Features CLI v{}...",
            env!("CARGO_PKG_VERSION")
        ));
        pb.enable_steady_tick(std::time::Duration::from_millis(100));
        Some(pb)
    } else {
        None
    };

    // Build scan configuration
    let current_dir = std::env::current_dir()?;
    let should_add_coverage = args.serve || args.build || args.json || args.coverage;
    let ignore_paths = resolve_ignore_paths(&args.ignore_path, &current_dir);

    // CODEOWNERS only needs ownership; skip the expensive parts of the scan
    // unless another action that uses the full feature data is requested.
    let ownership_only = args.generate_codeowners && !args.serve && !args.build && !args.check;

    let mut config = ScanConfig::new(&current_dir)
        .skip_changes(args.skip_changes)
        .with_coverage(should_add_coverage)
        .ignore_paths(ignore_paths.clone())
        .ownership_only(ownership_only)
        .include_skipped_dirs(args.include_skipped_dirs);

    if let Some(ref coverage_dir) = args.coverage_dir {
        config = config.coverage_dir(coverage_dir);
    }

    if let Some(ref project_dir) = args.project_dir {
        config = config.project_dir(project_dir);
    }

    let features = scan_features(&path, config)?;

    // Generate CODEOWNERS file if requested
    if args.generate_codeowners {
        let output_dir = args.project_dir.as_deref().unwrap_or(&current_dir);
        generate_codeowners(
            &features,
            &path,
            args.project_dir.as_deref(),
            output_dir,
            args.codeowners_path.as_deref(),
            &args.codeowners_prefix,
        )?;
    }

    // Handle main actions - these can be combined with generate-codeowners
    if args.serve {
        if let Some(pb) = spinner {
            pb.set_message("Server is starting...");
            let pb_clone = pb.clone();
            serve_features_with_watching(
                &features,
                args.port,
                path.clone(),
                Some(Box::new(move || {
                    pb_clone.finish_and_clear();
                })),
                args.skip_changes,
                ignore_paths.clone(),
                args.include_skipped_dirs,
            )
            .await?;
        } else {
            serve_features_with_watching(
                &features,
                args.port,
                path.clone(),
                None,
                args.skip_changes,
                ignore_paths.clone(),
                args.include_skipped_dirs,
            )
            .await?;
        }
    } else if args.build {
        let build_config = BuildConfig::new(args.build_dir);
        create_build(&features, build_config, args.skip_changes).await?;
    } else if args.check {
        run_checks(&features)?;
    } else if args.generate_codeowners {
        // If only generate-codeowners flag is set, we've already done the work above
        // No additional output needed
    } else if args.list_owners {
        let unique_owners = extract_unique_owners(&features);

        if args.json {
            let json = serde_json::to_string_pretty(&unique_owners)?;
            println!("{}", json);
        } else {
            eprintln!("Unique owners found in {}:", path.display());
            for owner in unique_owners {
                println!("{}", owner);
            }
        }
    } else {
        let output_features = if args.flat {
            flatten_features(&features)
        } else {
            features
        };

        if args.json {
            let json = serde_json::to_string_pretty(&output_features)?;
            println!("{}", json);
        } else {
            eprintln!("Features found in {}:", path.display());
            if output_features.is_empty() {
                eprintln!("No features found.");
            } else {
                print_features(&output_features, 0, args.description);
            }
        }
    }

    Ok(())
}