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
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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
use regex::Regex;
use std::collections::{HashMap, HashSet};
use std::fs;
use std::path::Path;
use std::process::Command;

use crate::config::FeludaConfig;
use crate::debug::{log, log_debug, log_error, LogLevel};
use crate::licenses::{
    fetch_licenses_from_github, is_license_restrictive, LicenseCompatibility, LicenseInfo,
};

pub fn analyze_c_licenses(project_path: &str, config: &FeludaConfig) -> Vec<LicenseInfo> {
    log(
        LogLevel::Info,
        &format!("Analyzing C dependencies from: {project_path}"),
    );

    let known_licenses = match fetch_licenses_from_github() {
        Ok(licenses) => {
            log(
                LogLevel::Info,
                &format!("Fetched {} known licenses from GitHub", licenses.len()),
            );
            licenses
        }
        Err(err) => {
            log_error("Failed to fetch licenses from GitHub", &err);
            HashMap::new()
        }
    };

    let direct_dependencies = detect_c_dependencies(project_path, config);
    log(
        LogLevel::Info,
        &format!("Found {} direct C dependencies", direct_dependencies.len()),
    );
    log_debug("Direct C dependencies", &direct_dependencies);

    let max_depth = config.dependencies.max_depth;
    log(
        LogLevel::Info,
        &format!("Using max dependency depth: {max_depth}"),
    );

    let all_deps = resolve_c_dependencies(project_path, &direct_dependencies, max_depth);
    log(
        LogLevel::Info,
        &format!(
            "Total C dependencies (including transitive): {}",
            all_deps.len()
        ),
    );
    log_debug("All C dependencies", &all_deps);

    let dependencies = all_deps;

    dependencies
        .into_iter()
        .map(|(name, version)| {
            log(
                LogLevel::Info,
                &format!("Processing dependency: {name} ({version})"),
            );

            let license_result = fetch_license_for_c_dependency(&name, &version);
            let license = Some(license_result);
            let is_restrictive = is_license_restrictive(&license, &known_licenses, config.strict);

            if is_restrictive {
                log(
                    LogLevel::Warn,
                    &format!("Restrictive license found: {license:?} for {name}"),
                );
            }

            LicenseInfo {
                name,
                version,
                license: license.clone(),
                is_restrictive,
                compatibility: LicenseCompatibility::Unknown,
                osi_status: match &license {
                    Some(l) => crate::licenses::get_osi_status(l),
                    None => crate::licenses::OsiStatus::Unknown,
                },
            }
        })
        .collect()
}

fn detect_c_dependencies(project_path: &str, config: &FeludaConfig) -> Vec<(String, String)> {
    let mut dependencies = Vec::new();
    let project_dir = Path::new(project_path).parent().unwrap_or(Path::new("."));

    if let Ok(autotools_deps) = parse_autotools_dependencies(project_dir, config) {
        log(
            LogLevel::Info,
            &format!("Found {} autotools dependencies", autotools_deps.len()),
        );
        dependencies.extend(autotools_deps);
    }

    if dependencies.is_empty() {
        if let Ok(makefile_deps) = parse_makefile_dependencies(project_dir, config) {
            log(
                LogLevel::Info,
                &format!("Found {} makefile dependencies", makefile_deps.len()),
            );
            dependencies.extend(makefile_deps);
        }
    }

    if dependencies.is_empty() {
        if let Ok(pkgconfig_deps) = parse_pkgconfig_dependencies(project_dir, config) {
            log(
                LogLevel::Info,
                &format!("Found {} pkg-config dependencies", pkgconfig_deps.len()),
            );
            dependencies.extend(pkgconfig_deps);
        }
    }

    dependencies
}

fn resolve_c_dependencies(
    _project_path: &str,
    direct_deps: &[(String, String)],
    max_depth: u32,
) -> Vec<(String, String)> {
    log(
        LogLevel::Info,
        &format!("Resolving C dependencies (including transitive up to depth {max_depth})"),
    );

    let mut all_dependencies = Vec::new();
    let mut visited = HashSet::new();
    let mut depth_stats = HashMap::new();

    // Add direct dependencies first
    for (name, version) in direct_deps {
        all_dependencies.push((name.clone(), version.clone()));
        visited.insert(name.clone());
        *depth_stats.entry(0u32).or_insert(0) += 1;
    }

    // Queue for BFS: (package_name, version, depth)
    let mut to_process: Vec<(String, String, u32)> = direct_deps
        .iter()
        .map(|(name, version)| (name.clone(), version.clone(), 0))
        .collect();

    while let Some((name, version, depth)) = to_process.pop() {
        if depth >= max_depth {
            log(
                LogLevel::Trace,
                &format!("Skipping {name} - exceeded max depth {max_depth}"),
            );
            continue;
        }

        log(
            LogLevel::Trace,
            &format!("Resolving transitive dependencies for: {name} (depth {depth})"),
        );

        if let Ok(transitive_deps) = resolve_c_transitive_deps(&name, &version) {
            log(
                LogLevel::Trace,
                &format!(
                    "Found {} transitive dependencies for {} at depth {}",
                    transitive_deps.len(),
                    name,
                    depth
                ),
            );

            for (dep_name, dep_version) in transitive_deps {
                if !visited.contains(&dep_name) {
                    visited.insert(dep_name.clone());
                    all_dependencies.push((dep_name.clone(), dep_version.clone()));
                    to_process.push((dep_name, dep_version, depth + 1));
                    *depth_stats.entry(depth + 1).or_insert(0) += 1;
                }
            }
        }
    }

    // Log depth statistics
    for depth in 0..=max_depth {
        if let Some(count) = depth_stats.get(&depth) {
            log(
                LogLevel::Info,
                &format!("Depth {depth}: {count} dependencies"),
            );
        }
    }

    log(
        LogLevel::Info,
        &format!(
            "C dependency resolution completed. Total dependencies: {} (explored up to depth {})",
            all_dependencies.len(),
            max_depth
        ),
    );

    all_dependencies
}

fn resolve_c_transitive_deps(
    package_name: &str,
    version: &str,
) -> Result<Vec<(String, String)>, String> {
    let mut dependencies = Vec::new();

    // Try pkg-config for transitive dependencies
    if let Ok(pkg_deps) = get_pkgconfig_requires(package_name) {
        dependencies.extend(pkg_deps);
    }

    // Try parsing .pc file directly
    if let Ok(pc_deps) = parse_pc_file_requires(package_name) {
        dependencies.extend(pc_deps);
    }

    // Try system package dependencies
    if version == "system" {
        if let Ok(sys_deps) = get_system_package_dependencies(package_name) {
            dependencies.extend(sys_deps);
        }
    }

    Ok(dependencies)
}

fn get_pkgconfig_requires(package_name: &str) -> Result<Vec<(String, String)>, String> {
    let output = Command::new("pkg-config")
        .args(["--print-requires", package_name])
        .output()
        .map_err(|e| format!("Failed to run pkg-config --print-requires: {e}"))?;

    if !output.status.success() {
        return Ok(Vec::new());
    }

    let stdout_str = String::from_utf8_lossy(&output.stdout);
    let mut dependencies = Vec::new();

    for line in stdout_str.lines() {
        let trimmed = line.trim();
        if !trimmed.is_empty() {
            let parts: Vec<&str> = trimmed.split_whitespace().collect();
            if let Some(pkg_name) = parts.first() {
                let version = if parts.len() > 2
                    && (parts[1] == ">=" || parts[1] == "=" || parts[1] == ">")
                {
                    parts[2].to_string()
                } else {
                    "system".to_string()
                };
                dependencies.push((pkg_name.to_string(), version));
            }
        }
    }

    // Also check private requires
    let private_output = Command::new("pkg-config")
        .args(["--print-requires-private", package_name])
        .output();

    if let Ok(private_out) = private_output {
        if private_out.status.success() {
            let private_str = String::from_utf8_lossy(&private_out.stdout);
            for line in private_str.lines() {
                let trimmed = line.trim();
                if !trimmed.is_empty() {
                    let parts: Vec<&str> = trimmed.split_whitespace().collect();
                    if let Some(pkg_name) = parts.first() {
                        let version = if parts.len() > 2
                            && (parts[1] == ">=" || parts[1] == "=" || parts[1] == ">")
                        {
                            parts[2].to_string()
                        } else {
                            "system".to_string()
                        };
                        dependencies.push((pkg_name.to_string(), version));
                    }
                }
            }
        }
    }

    Ok(dependencies)
}

fn parse_pc_file_requires(package_name: &str) -> Result<Vec<(String, String)>, String> {
    let potential_paths = [
        format!("/usr/lib/pkgconfig/{package_name}.pc"),
        format!("/usr/local/lib/pkgconfig/{package_name}.pc"),
        format!("/usr/share/pkgconfig/{package_name}.pc"),
        format!("/usr/local/share/pkgconfig/{package_name}.pc"),
        format!("/opt/homebrew/lib/pkgconfig/{package_name}.pc"),
    ];

    for pc_path in &potential_paths {
        if let Ok(content) = fs::read_to_string(pc_path) {
            return parse_pc_content(&content);
        }
    }

    Ok(Vec::new())
}

fn parse_pc_content(content: &str) -> Result<Vec<(String, String)>, String> {
    let mut dependencies = Vec::new();
    let requires_regex = Regex::new(r"^Requires(?:\.private)?\s*:\s*(.+)$")
        .map_err(|e| format!("Failed to compile requires regex: {e}"))?;

    for line in content.lines() {
        if let Some(cap) = requires_regex.captures(line) {
            if let Some(requires_str) = cap.get(1) {
                let requires = requires_str.as_str().trim();
                for dep in requires.split(',') {
                    let dep = dep.trim();
                    if !dep.is_empty() {
                        let parts: Vec<&str> = dep.split_whitespace().collect();
                        if let Some(pkg_name) = parts.first() {
                            let version = if parts.len() > 2
                                && (parts[1] == ">=" || parts[1] == "=" || parts[1] == ">")
                            {
                                parts[2].to_string()
                            } else {
                                "system".to_string()
                            };
                            dependencies.push((pkg_name.to_string(), version));
                        }
                    }
                }
            }
        }
    }

    Ok(dependencies)
}

fn get_system_package_dependencies(package_name: &str) -> Result<Vec<(String, String)>, String> {
    // Try dpkg (Debian/Ubuntu)
    if let Ok(output) = Command::new("dpkg-query")
        .args(["-W", "-f", "${Depends}\\n", package_name])
        .output()
    {
        if output.status.success() {
            let depends_str = String::from_utf8_lossy(&output.stdout);
            return parse_debian_dependencies(&depends_str);
        }
    }

    // Try rpm (RedHat/CentOS/Fedora)
    if let Ok(output) = Command::new("rpm")
        .args(["-q", "--requires", package_name])
        .output()
    {
        if output.status.success() {
            let requires_str = String::from_utf8_lossy(&output.stdout);
            return parse_rpm_dependencies(&requires_str);
        }
    }

    Ok(Vec::new())
}

fn parse_debian_dependencies(depends_str: &str) -> Result<Vec<(String, String)>, String> {
    let mut dependencies = Vec::new();

    for dep in depends_str.split(',') {
        let dep = dep.trim();
        if !dep.is_empty() && !dep.starts_with("${") {
            // Remove version constraints and alternatives
            let parts: Vec<&str> = dep.split_whitespace().collect();
            if let Some(pkg_name) = parts.first() {
                let clean_name = pkg_name.split('|').next().unwrap_or(pkg_name).trim();
                if !clean_name.is_empty() {
                    dependencies.push((clean_name.to_string(), "system".to_string()));
                }
            }
        }
    }

    Ok(dependencies)
}

fn parse_rpm_dependencies(requires_str: &str) -> Result<Vec<(String, String)>, String> {
    let mut dependencies = Vec::new();

    for line in requires_str.lines() {
        let line = line.trim();
        if !line.is_empty() && !line.starts_with("rpmlib(") && !line.starts_with('/') {
            let parts: Vec<&str> = line.split_whitespace().collect();
            if let Some(pkg_name) = parts.first() {
                dependencies.push((pkg_name.to_string(), "system".to_string()));
            }
        }
    }

    Ok(dependencies)
}

fn parse_autotools_dependencies(
    project_dir: &Path,
    _config: &FeludaConfig,
) -> Result<Vec<(String, String)>, String> {
    let configure_ac = project_dir.join("configure.ac");
    let configure_in = project_dir.join("configure.in");

    let config_file = if configure_ac.exists() {
        configure_ac
    } else if configure_in.exists() {
        configure_in
    } else {
        return Err("No autotools configuration file found".to_string());
    };

    let content = fs::read_to_string(&config_file)
        .map_err(|e| format!("Failed to read autotools config: {e}"))?;

    let mut dependencies = Vec::new();

    let pkg_check_regex = Regex::new(r"PKG_CHECK_MODULES\s*\(\s*\w+\s*,\s*([^,\)]+)")
        .map_err(|e| format!("Failed to compile PKG_CHECK_MODULES regex: {e}"))?;

    for cap in pkg_check_regex.captures_iter(&content) {
        if let Some(pkg_spec) = cap.get(1) {
            let spec = pkg_spec
                .as_str()
                .trim()
                .trim_matches('"')
                .trim_matches('\'');

            let parts: Vec<&str> = spec.split_whitespace().collect();
            if let Some(pkg_name) = parts.first() {
                let version = if parts.len() > 2
                    && (parts[1] == ">=" || parts[1] == "=" || parts[1] == ">")
                {
                    parts[2].to_string()
                } else {
                    "system".to_string()
                };
                dependencies.push((pkg_name.to_string(), version));
            }
        }
    }

    let ac_check_lib_regex = Regex::new(r"AC_CHECK_LIB\s*\(\s*([^,\)]+)")
        .map_err(|e| format!("Failed to compile AC_CHECK_LIB regex: {e}"))?;

    for cap in ac_check_lib_regex.captures_iter(&content) {
        if let Some(lib_name) = cap.get(1) {
            let name = lib_name
                .as_str()
                .trim()
                .trim_matches('"')
                .trim_matches('\'');
            dependencies.push((name.to_string(), "system".to_string()));
        }
    }

    Ok(dependencies)
}

fn parse_makefile_dependencies(
    project_dir: &Path,
    _config: &FeludaConfig,
) -> Result<Vec<(String, String)>, String> {
    let makefile_paths = ["Makefile", "makefile", "GNUmakefile"];

    for &makefile_name in &makefile_paths {
        let makefile_path = project_dir.join(makefile_name);
        if makefile_path.exists() {
            let content = fs::read_to_string(&makefile_path)
                .map_err(|e| format!("Failed to read {makefile_name}: {e}"))?;

            return parse_makefile_content(&content);
        }
    }

    Err("No Makefile found".to_string())
}

fn parse_makefile_content(content: &str) -> Result<Vec<(String, String)>, String> {
    let mut dependencies = Vec::new();

    let ldflags_regex = Regex::new(r"-l([a-zA-Z0-9_-]+)")
        .map_err(|e| format!("Failed to compile ldflags regex: {e}"))?;

    for cap in ldflags_regex.captures_iter(content) {
        if let Some(lib_name) = cap.get(1) {
            let name = lib_name.as_str();
            if !name.is_empty() && name != "c" && name != "m" {
                dependencies.push((format!("lib{name}"), "system".to_string()));
            }
        }
    }

    let pkgconfig_regex = Regex::new(r"`pkg-config\s+--[^`]*\s+([a-zA-Z0-9_-]+)")
        .map_err(|e| format!("Failed to compile pkg-config regex: {e}"))?;

    for cap in pkgconfig_regex.captures_iter(content) {
        if let Some(pkg_name) = cap.get(1) {
            dependencies.push((pkg_name.as_str().to_string(), "system".to_string()));
        }
    }

    Ok(dependencies)
}

fn parse_pkgconfig_dependencies(
    project_dir: &Path,
    _config: &FeludaConfig,
) -> Result<Vec<(String, String)>, String> {
    let output = Command::new("pkg-config")
        .args(["--list-all"])
        .current_dir(project_dir)
        .output()
        .map_err(|e| format!("Failed to run pkg-config: {e}"))?;

    if !output.status.success() {
        return Err("pkg-config command failed".to_string());
    }

    let stdout_str = String::from_utf8_lossy(&output.stdout);
    let mut dependencies = Vec::new();

    for line in stdout_str.lines().take(10) {
        if let Some(space_pos) = line.find(' ') {
            let pkg_name = &line[..space_pos];
            if !pkg_name.is_empty() {
                dependencies.push((pkg_name.to_string(), "system".to_string()));
            }
        }
    }

    Ok(dependencies)
}

fn fetch_license_for_c_dependency(name: &str, version: &str) -> String {
    if version == "system" {
        if let Ok(license) = get_system_package_license(name) {
            return license;
        }
    }

    format!("Unknown license for {name}: {version}")
}

fn get_system_package_license(package_name: &str) -> Result<String, String> {
    if let Ok(output) = Command::new("dpkg-query")
        .args(["-f", "${Package} ${License}\n", "-W", package_name])
        .output()
    {
        if output.status.success() {
            let stdout_str = String::from_utf8_lossy(&output.stdout);
            if let Some(line) = stdout_str.lines().next() {
                if let Some(space_pos) = line.find(' ') {
                    return Ok(line[space_pos + 1..].to_string());
                }
            }
        }
    }

    if let Ok(output) = Command::new("rpm")
        .args(["-q", "--qf", "%{LICENSE}\n", package_name])
        .output()
    {
        if output.status.success() {
            let license = String::from_utf8_lossy(&output.stdout).trim().to_string();
            if !license.is_empty() && license != "(none)" {
                return Ok(license);
            }
        }
    }

    Err(format!("Could not determine license for {package_name}"))
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    #[test]
    fn test_parse_autotools_dependencies() {
        let temp_dir = TempDir::new().unwrap();
        let configure_ac = temp_dir.path().join("configure.ac");

        fs::write(
            &configure_ac,
            r#"AC_INIT([test], [1.0])
PKG_CHECK_MODULES([GLIB], [glib-2.0 >= 2.40])
PKG_CHECK_MODULES([GTK], [gtk+-3.0])
AC_CHECK_LIB([z], [inflate])
AC_CHECK_LIB([ssl], [SSL_new])
"#,
        )
        .unwrap();

        let config = FeludaConfig::default();
        let result = parse_autotools_dependencies(temp_dir.path(), &config);

        // Just verify it doesn't crash - dependency parsing is complex
        assert!(result.is_ok());
    }

    #[test]
    fn test_parse_makefile_dependencies() {
        let makefile_content = r#"
CFLAGS = -Wall -O2
LDFLAGS = -lz -lssl -lpthread
LIBS = `pkg-config --libs gtk+-3.0`

test: test.o
	$(CC) -o test test.o $(LDFLAGS)
"#;

        let result = parse_makefile_content(makefile_content).unwrap();

        assert!(!result.is_empty());
        assert!(result.iter().any(|(name, _)| name == "libz"));
        assert!(result.iter().any(|(name, _)| name == "libssl"));
        assert!(result.iter().any(|(name, _)| name == "libpthread"));
    }

    #[test]
    fn test_analyze_c_licenses_empty() {
        let temp_dir = TempDir::new().unwrap();
        let dummy_file = temp_dir.path().join("dummy");
        fs::write(&dummy_file, "").unwrap();

        let config = FeludaConfig::default();
        let dependencies = detect_c_dependencies(dummy_file.to_str().unwrap(), &config);

        // Should be empty or small since no autotools/makefile files exist
        // pkg-config might return some system packages, so just check it doesn't crash
        assert!(dependencies.len() <= 20);
    }
}