feluda 1.14.0

A CLI tool to check dependency licenses.
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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
mod cache;
mod cli;
mod config;
mod debug;
mod generate;
mod init;
mod languages;
mod licenses;
mod manifest;
mod parser;
mod reporter;
mod sbom;
mod spdx;
mod table;
mod utils;
mod watch;

use clap::Parser;
use cli::{print_version_info, Cli, Commands};
use debug::{log, log_debug, set_debug_mode, FeludaError, FeludaResult, LogLevel};
use generate::handle_generate_command;
use init::handle_init_command;
use licenses::{
    detect_project_license, is_license_compatible, set_github_token, LicenseCompatibility,
    LicenseInfo,
};
use parser::parse_root;
use reporter::{generate_report, ReportConfig};
use sbom::handle_sbom_command;
use sbom::validate::handle_sbom_validate_command;
use std::env;
use std::path::Path;
use std::process;
use table::App;
use tempfile::TempDir;
use utils::clone_repository;

/// Configuration for the check command
#[derive(Debug)]
struct CheckConfig {
    path: String,
    json: bool,
    yaml: bool,
    verbose: bool,
    restrictive: bool,
    gui: bool,
    language: Option<String>,
    ci_format: Option<cli::CiFormat>,
    output_file: Option<String>,
    fail_on_restrictive: bool,
    incompatible: bool,
    fail_on_incompatible: bool,
    project_license: Option<String>,
    gist: bool,
    osi: Option<cli::OsiFilter>,
    strict: bool,
    no_local: bool,
}

fn main() {
    // Check if --version or -V is passed alone
    let args: Vec<String> = env::args().collect();
    if args.len() == 2 && (args[1] == "--version" || args[1] == "-V") {
        print_version_info();
        return;
    }

    match run() {
        Ok(_) => {}
        Err(e) => {
            e.log();
            process::exit(1);
        }
    }
}

fn run() -> FeludaResult<()> {
    let args = Cli::parse();

    // Debug mode
    if args.debug {
        set_debug_mode(true);
        log(
            LogLevel::Info,
            &format!("Starting Feluda with args: {args:?}"),
        );
    }

    // Set GitHub API token for authenticated requests
    set_github_token(args.github_token.clone());

    // Handle repository cloning if --repo is provided
    let (analysis_path, _temp_dir) = match &args.repo.clone() {
        Some(repo_url) => {
            log(
                LogLevel::Info,
                &format!("Attempting to clone repository: {repo_url}"),
            );
            let temp_dir = TempDir::new().map_err(|e| {
                FeludaError::TempDir(format!("Failed to create temporary directory: {e}"))
            })?;
            let repo_path = temp_dir.path();

            // Clone the repository
            if let Err(e) = clone_repository(&args, repo_path) {
                log(LogLevel::Error, &format!("Repository cloning failed: {e}"));
                return Err(e);
            }
            log(
                LogLevel::Info,
                &format!("Repository cloned to: {}", repo_path.display()),
            );
            (repo_path.to_path_buf(), Some(temp_dir))
        }
        None => {
            let path = Path::new(&args.path).to_path_buf();
            log(
                LogLevel::Info,
                &format!("Using local path for analysis: {}", path.display()),
            );
            (path, None)
        }
    };

    log(
        LogLevel::Info,
        &format!("Analysing project at: {}", analysis_path.display()),
    );

    // Handle the command based on whether a subcommand was provided
    if args.is_default_command() {
        // Default behavior: license analysis
        let config = CheckConfig {
            path: analysis_path.to_string_lossy().to_string(),
            json: args.json,
            yaml: args.yaml,
            verbose: args.verbose,
            restrictive: args.restrictive,
            gui: args.gui,
            language: args.language,
            ci_format: args.ci_format,
            output_file: args.output_file,
            fail_on_restrictive: args.fail_on_restrictive,
            incompatible: args.incompatible,
            fail_on_incompatible: args.fail_on_incompatible,
            project_license: args.project_license,
            gist: args.gist,
            osi: args.osi,
            strict: args.strict,
            no_local: args.no_local,
        };
        handle_check_command(config)
    } else {
        // Handle subcommands
        let command = args.get_command_args();
        match command {
            Commands::Generate {
                path,
                language,
                project_license,
            } => {
                handle_generate_command(path, language, project_license);
                Ok(())
            }
            Commands::Sbom {
                path,
                format,
                output,
            } => {
                // Determine which format to use
                match format {
                    Some(cli::SbomCommand::Spdx {
                        path: fmt_path,
                        output: fmt_output,
                    }) => {
                        // Use the subcommand path/output if provided, otherwise use the parent command's
                        let final_path = if fmt_path != "./" {
                            fmt_path
                        } else {
                            path.clone()
                        };
                        let final_output = fmt_output.or(output.clone());
                        handle_sbom_command(final_path, &cli::SbomFormat::Spdx, final_output)
                    }
                    Some(cli::SbomCommand::Cyclonedx {
                        path: fmt_path,
                        output: fmt_output,
                    }) => {
                        let final_path = if fmt_path != "./" {
                            fmt_path
                        } else {
                            path.clone()
                        };
                        let final_output = fmt_output.or(output.clone());
                        handle_sbom_command(final_path, &cli::SbomFormat::Cyclonedx, final_output)
                    }
                    Some(cli::SbomCommand::Validate {
                        sbom_file,
                        output: validation_output,
                        json,
                    }) => handle_sbom_validate_command(sbom_file, validation_output, json),
                    None => {
                        // Default: generate both formats
                        handle_sbom_command(path, &cli::SbomFormat::All, output)
                    }
                }
            }
            Commands::Cache { clear } => {
                handle_cache_command(clear)?;
                Ok(())
            }
            Commands::Init {
                path,
                force,
                no_pre_commit,
            } => {
                handle_init_command(path, force, no_pre_commit);
                Ok(())
            }
            Commands::Watch { path, debounce } => {
                if args.gui {
                    eprintln!(
                        "❌ Watch mode does not support --gui (TUI) output. \
                        Run `feluda watch` without --gui."
                    );
                    return Err(FeludaError::InvalidData(
                        "Watch mode does not support --gui (TUI) output".to_string(),
                    ));
                }
                if args.repo.is_some() {
                    eprintln!("❌ Watch mode operates on a local path; --repo is not supported.");
                    return Err(FeludaError::InvalidData(
                        "Watch mode operates on a local path; --repo is not supported".to_string(),
                    ));
                }

                let config = CheckConfig {
                    path,
                    json: args.json,
                    yaml: args.yaml,
                    verbose: args.verbose,
                    restrictive: args.restrictive,
                    gui: false,
                    language: args.language.clone(),
                    ci_format: args.ci_format.clone(),
                    output_file: args.output_file.clone(),
                    fail_on_restrictive: false,
                    incompatible: args.incompatible,
                    fail_on_incompatible: false,
                    project_license: args.project_license.clone(),
                    gist: args.gist,
                    osi: args.osi.clone(),
                    strict: args.strict,
                    no_local: args.no_local,
                };
                watch::handle_watch_command(config, debounce)
            }
        }
    }
}

/// Outcome of a single license analysis run.
///
/// Returned by [`report_analysis`] so callers (single-shot or watch) can decide
/// what to do — e.g. set an exit code — without the analysis itself terminating
/// the process.
#[derive(Debug, Default, Clone, Copy)]
struct ScanSummary {
    has_restrictive: bool,
    has_incompatible: bool,
}

/// Detect the project license and parse + analyze dependencies.
///
/// This is the shared front half of the check pipeline, reused by both the
/// single-shot command and `feluda watch`. It performs no terminal I/O beyond
/// logging and never exits the process.
fn analyze_dependencies(config: &CheckConfig) -> FeludaResult<(Vec<LicenseInfo>, Option<String>)> {
    log(
        LogLevel::Info,
        &format!("Executing check command with path: {}", config.path),
    );

    // Parse project dependencies
    log(
        LogLevel::Info,
        &format!("Parsing dependencies in path: {}", config.path),
    );

    let mut project_license = config.project_license.clone();

    // If no project license is provided via CLI, try to detect it
    if let Some(ref license) = project_license {
        log(
            LogLevel::Info,
            &format!("Using provided project license: {}", *license),
        );
    } else {
        log(
            LogLevel::Info,
            "No project license specified, attempting to detect",
        );
        match detect_project_license(&config.path) {
            Ok(Some(detected)) => {
                log(
                    LogLevel::Info,
                    &format!("Detected project license: {detected}"),
                );
                project_license = Some(detected);
            }
            Ok(None) => {
                log(LogLevel::Warn, "Could not detect project license");
            }
            Err(e) => {
                log(
                    LogLevel::Error,
                    &format!("Error detecting project license: {e}"),
                );
            }
        }
    }

    // Parse and analyze dependencies
    let analyzed_data = parse_root(
        &config.path,
        config.language.as_deref(),
        config.strict,
        config.no_local,
    )
    .map_err(|e| FeludaError::Parser(format!("Failed to parse dependencies: {e}")))?;

    log_debug("Analyzed dependencies", &analyzed_data);

    Ok((analyzed_data, project_license))
}

/// Annotate each dependency with license-compatibility information relative to
/// the project license. Mutates `analyzed_data` in place.
fn annotate_compatibility(
    analyzed_data: &mut [LicenseInfo],
    project_license: &Option<String>,
    strict: bool,
) {
    // Update each dependency with compatibility information if project license is known
    if let Some(proj_license) = project_license {
        log(
            LogLevel::Info,
            &format!("Checking license compatibility against project license: {proj_license}"),
        );

        for info in analyzed_data.iter_mut() {
            if let Some(ref dep_license) = info.license {
                info.compatibility = is_license_compatible(dep_license, proj_license, strict);

                log(
                    LogLevel::Info,
                    &format!(
                        "License compatibility for {} ({}): {:?}",
                        info.name, dep_license, info.compatibility
                    ),
                );
            } else {
                info.compatibility = if strict {
                    LicenseCompatibility::Incompatible
                } else {
                    LicenseCompatibility::Unknown
                };

                log(
                    LogLevel::Info,
                    &format!(
                        "License compatibility for {} {} (no license info)",
                        info.name,
                        if strict { "incompatible" } else { "unknown" }
                    ),
                );
            }
        }
    } else {
        // If no project license is known, mark all as unknown compatibility
        log(
            LogLevel::Warn,
            "No project license specified or detected, marking all dependencies as unknown compatibility",
        );

        for info in analyzed_data.iter_mut() {
            info.compatibility = LicenseCompatibility::Unknown;
        }
    }
}

/// Render the interactive TUI table for the analyzed dependencies.
///
/// GUI mode is single-shot only (it takes over the terminal and `color_eyre`
/// can only be installed once per process), so it is intentionally not used by
/// `feluda watch`.
fn run_gui(
    mut analyzed_data: Vec<LicenseInfo>,
    project_license: Option<String>,
    config: &CheckConfig,
) -> FeludaResult<()> {
    let original_count = analyzed_data.len();

    // Filter for restrictive and incompatible
    if config.restrictive || config.incompatible {
        if project_license.is_some() {
            log(
                LogLevel::Info,
                "Restrictive and incompatible mode enabled, filtering for restrictive and incompatible licenses",
            );
            analyzed_data.retain(|info| {
                (config.restrictive && *info.is_restrictive())
                    || (config.incompatible
                        && info.compatibility == LicenseCompatibility::Incompatible)
            });

            log(
                LogLevel::Info,
                &format!(
                    "Filtered for restrictive and incompatible licenses: {} of {} dependencies",
                    analyzed_data.len(),
                    original_count
                ),
            );
        } else {
            log(
                LogLevel::Warn,
                "Incompatible mode enabled but no project license specified, cannot filter for incompatible licenses",
            );
        }
    } else if config.restrictive {
        // Filter for restrictive
        log(
            LogLevel::Info,
            "Restrictive mode enabled, filtering for restrictive licenses",
        );
        analyzed_data.retain(|info| *info.is_restrictive());

        log(
            LogLevel::Info,
            &format!(
                "Filtered for restrictive licenses: {} of {} dependencies",
                analyzed_data.len(),
                original_count
            ),
        );
    } else if config.incompatible {
        // Filter for incompatible if requested
        if project_license.is_some() {
            log(
                LogLevel::Info,
                "Incompatible mode enabled, filtering for incompatible licenses",
            );
            analyzed_data.retain(|info| info.compatibility == LicenseCompatibility::Incompatible);

            log(
                LogLevel::Info,
                &format!(
                    "Filtered for incompatible licenses: {} of {} dependencies",
                    analyzed_data.len(),
                    original_count
                ),
            );
        } else {
            log(
                LogLevel::Warn,
                "Incompatible mode enabled but no project license specified, cannot filter for incompatible licenses",
            );
        }
    }

    // Apply OSI filtering
    if let Some(osi_filter) = &config.osi {
        let before_count = analyzed_data.len();
        match osi_filter {
            cli::OsiFilter::Approved => {
                analyzed_data.retain(|info| info.osi_status == licenses::OsiStatus::Approved);
                log(
                    LogLevel::Info,
                    &format!(
                        "Filtered for OSI approved licenses: {} of {} dependencies",
                        analyzed_data.len(),
                        before_count
                    ),
                );
            }
            cli::OsiFilter::NotApproved => {
                analyzed_data.retain(|info| info.osi_status == licenses::OsiStatus::NotApproved);
                log(
                    LogLevel::Info,
                    &format!(
                        "Filtered for non-OSI approved licenses: {} of {} dependencies",
                        analyzed_data.len(),
                        before_count
                    ),
                );
            }
            cli::OsiFilter::Unknown => {
                analyzed_data.retain(|info| info.osi_status == licenses::OsiStatus::Unknown);
                log(
                    LogLevel::Info,
                    &format!(
                        "Filtered for unknown OSI status licenses: {} of {} dependencies",
                        analyzed_data.len(),
                        before_count
                    ),
                );
            }
        }
    }

    log(LogLevel::Info, "Starting TUI mode");

    // Initialize the terminal
    color_eyre::install()
        .map_err(|e| FeludaError::TuiInit(format!("Failed to initialize color_eyre: {e}")))?;

    let terminal = ratatui::init();
    log(LogLevel::Info, "Terminal initialized for TUI");

    // TUI app with project license info
    let app_result = App::new(analyzed_data, project_license).run(terminal);
    ratatui::restore();

    // Handle any errors from the TUI
    app_result.map_err(|e| FeludaError::TuiRuntime(format!("TUI error: {e}")))?;

    log(LogLevel::Info, "TUI session completed successfully");

    Ok(())
}

/// Generate a (non-interactive) dependency report and return the outcome.
///
/// Unlike the previous inline implementation, this never calls `process::exit`;
/// the caller inspects the returned [`ScanSummary`] to decide on exit codes.
/// This makes it safe to call repeatedly from `feluda watch`.
fn report_analysis(
    analyzed_data: Vec<LicenseInfo>,
    project_license: Option<String>,
    config: &CheckConfig,
) -> ScanSummary {
    log(LogLevel::Info, "Generating dependency report");

    // Create ReportConfig from CLI arguments
    let report_config = ReportConfig::new(
        config.json,
        config.yaml,
        config.verbose,
        config.restrictive,
        config.incompatible,
        config.ci_format.clone(),
        config.output_file.clone(),
        project_license,
        config.gist,
        config.osi.clone(),
    );

    // Generate a report based on the analyzed data
    let (has_restrictive, has_incompatible) = generate_report(analyzed_data, report_config);

    log(
        LogLevel::Info,
        &format!(
            "Report generated, has_restrictive: {has_restrictive}, has_incompatible: {has_incompatible}"
        ),
    );

    ScanSummary {
        has_restrictive,
        has_incompatible,
    }
}

fn handle_check_command(config: CheckConfig) -> FeludaResult<()> {
    let (mut analyzed_data, project_license) = analyze_dependencies(&config)?;

    if analyzed_data.is_empty() {
        log(LogLevel::Warn, "No dependencies found to analyze. Exiting.");
        return Ok(());
    }

    annotate_compatibility(&mut analyzed_data, &project_license, config.strict);

    // Either run the GUI or generate a report
    if config.gui {
        run_gui(analyzed_data, project_license, &config)?;
    } else {
        let summary = report_analysis(analyzed_data, project_license, &config);

        if (config.fail_on_restrictive && summary.has_restrictive)
            || (config.fail_on_incompatible && summary.has_incompatible)
        {
            log(
                LogLevel::Warn,
                "Exiting with non-zero status due to license issues",
            );
            process::exit(1);
        }
    }

    log(LogLevel::Info, "Feluda completed successfully");

    Ok(())
}

fn handle_cache_command(clear: bool) -> FeludaResult<()> {
    if clear {
        cache::clear_github_licenses_cache()?;
        println!("✓ Cache cleared successfully\n");
    } else {
        let status = cache::get_cache_status()?;
        status.print_status();
    }
    Ok(())
}