feluda 1.12.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
mod cache;
mod cli;
mod config;
mod debug;
mod generate;
mod languages;
mod licenses;
mod parser;
mod reporter;
mod sbom;
mod table;
mod utils;

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 licenses::{
    detect_project_license, is_license_compatible, set_github_token, LicenseCompatibility,
};
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(())
            }
        }
    }
}

fn handle_check_command(config: CheckConfig) -> FeludaResult<()> {
    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;

    // 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 mut 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);

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

    // Update each dependency with compatibility information if project license is known
    if let Some(ref proj_license) = project_license {
        log(
            LogLevel::Info,
            &format!("Checking license compatibility against project license: {proj_license}"),
        );

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

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

                log(
                    LogLevel::Info,
                    &format!(
                        "License compatibility for {} {} (no license info)",
                        info.name,
                        if config.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 &mut analyzed_data {
            info.compatibility = LicenseCompatibility::Unknown;
        }
    }

    // Either run the GUI or generate a report
    if config.gui {
        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");
    } else {
        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,
            config.output_file,
            project_license,
            config.gist,
            config.osi,
        );

        // 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}"
            ),
        );

        if (config.fail_on_restrictive && has_restrictive)
            || (config.fail_on_incompatible && 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(())
}