projd 0.1.3

Scan software projects and generate structured reports.
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
use std::fs;
use std::io::{self, IsTerminal};
use std::path::{Path, PathBuf};

use anyhow::{Context, Result, bail};
use clap::{Parser, Subcommand, ValueEnum};
use projd_core::{
    BuildSystemKind, DependencyEcosystem, LanguageKind, ProjectKind, ProjectScan, RiskCode,
    RiskSeverity, render_json, render_markdown, scan_path,
};

#[derive(Debug, Parser)]
#[command(name = "projd")]
#[command(version, about = projd_core::describe())]
struct Cli {
    #[command(subcommand)]
    command: Option<Command>,
}

#[derive(Debug, Subcommand)]
enum Command {
    /// Scan a local project directory.
    Scan {
        /// Project directory to scan.
        path: PathBuf,

        /// Output format.
        #[arg(short, long)]
        format: Option<OutputFormat>,

        /// Output file. If omitted, rendered content is printed to stdout.
        #[arg(short, long)]
        output: Option<PathBuf>,

        /// Replace the output file if it already exists.
        #[arg(long)]
        overwrite: bool,

        /// Disable Unicode drawing characters in terminal output.
        #[arg(long)]
        no_unicode: bool,

        /// Terminal color output policy.
        #[arg(long, default_value_t = ColorChoice::Auto)]
        color: ColorChoice,

        /// Target terminal width for compact dashboard output.
        #[arg(long, default_value_t = 80)]
        width: usize,
    },
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]
enum OutputFormat {
    Terminal,
    Markdown,
    Json,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]
enum ColorChoice {
    Auto,
    Always,
    Never,
}

impl std::fmt::Display for ColorChoice {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let value = match self {
            Self::Auto => "auto",
            Self::Always => "always",
            Self::Never => "never",
        };
        formatter.write_str(value)
    }
}

impl OutputFormat {
    fn detect_path(path: &Path) -> Option<Self> {
        let extension = path.extension()?.to_str()?.to_ascii_lowercase();
        match extension.as_str() {
            "md" | "markdown" => Some(Self::Markdown),
            "json" => Some(Self::Json),
            _ => None,
        }
    }
}

fn main() -> Result<()> {
    let cli = Cli::parse();

    match cli.command {
        Some(Command::Scan {
            path,
            format,
            output,
            overwrite,
            no_unicode,
            color,
            width,
        }) => {
            let stdout_is_terminal = io::stdout().is_terminal();
            let format = choose_output_format(format, output.as_deref(), stdout_is_terminal);
            let scan = scan_path(path)?;
            let rendered = render_scan(
                &scan,
                format,
                TerminalRenderOptions {
                    unicode: !no_unicode,
                    bar_width: bar_width_for_terminal(width),
                    color: color.enabled(stdout_is_terminal),
                },
            )?;
            write_or_print(rendered, output, overwrite)
        }
        None => {
            println!("{} {}", projd_core::NAME, projd_core::VERSION);
            println!("{}", projd_core::describe());
            Ok(())
        }
    }
}

fn choose_output_format(
    format: Option<OutputFormat>,
    output: Option<&Path>,
    stdout_is_terminal: bool,
) -> OutputFormat {
    if let Some(format) = format {
        return format;
    }

    if let Some(format) = output.and_then(OutputFormat::detect_path) {
        return format;
    }

    if output.is_none() && stdout_is_terminal {
        OutputFormat::Terminal
    } else {
        OutputFormat::Markdown
    }
}

fn render_scan(
    scan: &ProjectScan,
    format: OutputFormat,
    terminal_options: TerminalRenderOptions,
) -> Result<String> {
    match format {
        OutputFormat::Terminal => Ok(render_terminal(scan, terminal_options)),
        OutputFormat::Markdown => Ok(render_markdown(scan)),
        OutputFormat::Json => render_json(scan).map(|json| format!("{json}\n")),
    }
}

#[derive(Clone, Copy, Debug)]
struct TerminalRenderOptions {
    unicode: bool,
    bar_width: usize,
    color: bool,
}

fn render_terminal(scan: &ProjectScan, options: TerminalRenderOptions) -> String {
    let mut output = String::new();
    let separator = if options.unicode { " · " } else { " | " };
    let version = scan
        .identity
        .version
        .as_deref()
        .map(|version| format!(" v{version}"))
        .unwrap_or_default();

    output.push_str("Projd Scan Report\n");
    output.push_str(&format!(
        "{}{}{}{}{}{} files scanned\n",
        scan.identity.name,
        version,
        separator,
        project_kind_label(scan.identity.kind),
        separator,
        scan.files_scanned,
    ));
    output.push_str(&format!("Root: {}\n\n", scan.root.display()));

    output.push_str(&heading("Health", options));
    output.push_str(&status_line(
        "README",
        scan.documentation.has_readme,
        options,
    ));
    output.push_str(&status_line(
        "License",
        scan.documentation.has_license,
        options,
    ));
    output.push_str(&status_line(
        "docs/",
        scan.documentation.has_docs_dir,
        options,
    ));
    output.push_str(&status_line("CI", scan.ci.has_github_actions, options));
    output.push_str(&status_line(
        "Tests",
        scan.tests.test_files > 0 || !scan.tests.commands.is_empty(),
        options,
    ));
    output.push_str(&status_line("Lockfiles", lockfiles_ok(scan), options));

    output.push('\n');
    output.push_str(&heading("Languages", options));
    if scan.languages.is_empty() {
        output.push_str("  none detected\n");
    } else {
        let total_files = scan
            .languages
            .iter()
            .map(|language| language.files)
            .sum::<usize>();
        let mut languages = scan.languages.iter().collect::<Vec<_>>();
        languages.sort_by(|left, right| {
            right
                .files
                .cmp(&left.files)
                .then_with(|| language_label(left.kind).cmp(language_label(right.kind)))
        });

        for language in languages {
            let percent = percentage(language.files, total_files);
            output.push_str(&format!(
                "  {:<12} {} {:>3}% {:>4} file(s)\n",
                language_label(language.kind),
                style(
                    &bar(language.files, total_files, options),
                    AnsiStyle::Blue,
                    options
                ),
                percent,
                language.files
            ));
        }
    }

    output.push('\n');
    output.push_str(&heading("Build Systems", options));
    if scan.build_systems.is_empty() {
        output.push_str("  none detected\n");
    } else {
        for build_system in aggregate_build_systems(scan) {
            output.push_str(&format!(
                "  {:<12} {:>3} manifest(s)\n",
                build_system.label, build_system.count
            ));
        }
    }

    output.push('\n');
    output.push_str(&heading("Dependencies", options));
    output.push_str(&format!(
        "  {:<12} {}\n",
        "Manifests", scan.dependencies.total_manifests
    ));
    output.push_str(&format!(
        "  {:<12} {}\n",
        "Entries", scan.dependencies.total_dependencies
    ));
    if scan.dependencies.ecosystems.is_empty() {
        output.push_str("  none detected\n");
    } else {
        let total_dependencies = scan.dependencies.total_dependencies;
        for summary in aggregate_dependencies(scan) {
            output.push_str(&format!(
                "  {:<12} {:>3} manifest(s)  {} {:>4} dep(s)  {} lockfile(s), {} missing\n",
                summary.label,
                summary.manifests,
                style(
                    &bar(summary.total_dependencies, total_dependencies, options),
                    AnsiStyle::Blue,
                    options
                ),
                summary.total_dependencies,
                style(&summary.lockfiles.to_string(), AnsiStyle::Green, options),
                style(
                    &summary.missing_lockfiles.to_string(),
                    if summary.missing_lockfiles == 0 {
                        AnsiStyle::Green
                    } else {
                        AnsiStyle::Yellow
                    },
                    options
                ),
            ));
        }
    }

    output.push('\n');
    output.push_str(&heading("Tests", options));
    output.push_str(&format!(
        "  {:<12} {}\n",
        "Directories",
        scan.tests.test_directories.len()
    ));
    output.push_str(&format!("  {:<12} {}\n", "Files", scan.tests.test_files));
    if scan.tests.commands.is_empty() {
        output.push_str("  Commands     none detected\n");
    } else {
        for command in aggregate_test_commands(scan) {
            output.push_str(&format!(
                "  {:<12} {:>3} source(s)\n",
                command.command, command.sources
            ));
        }
    }

    output.push('\n');
    output.push_str(&heading("Risks", options));
    if scan.risks.findings.is_empty() {
        output.push_str("  none detected\n");
    } else {
        output.push_str(&format!(
            "  {:<12} high {}, medium {}, low {}, info {}\n",
            "Counts", scan.risks.high, scan.risks.medium, scan.risks.low, scan.risks.info
        ));
        for risk in &scan.risks.findings {
            let severity = risk_severity_label(risk.severity);
            output.push_str(&format!(
                "  {:<8} {:<30} {}\n",
                style(severity, risk_severity_style(risk.severity), options),
                risk_code_label(risk.code),
                risk.message
            ));
        }
    }

    output
}

fn heading(label: &str, options: TerminalRenderOptions) -> String {
    format!("{}\n", style(label, AnsiStyle::BoldCyan, options))
}

fn status_line(label: &str, ok: bool, options: TerminalRenderOptions) -> String {
    let status = if ok {
        style("OK", AnsiStyle::Green, options)
    } else {
        style("Missing", AnsiStyle::Yellow, options)
    };
    format!("  {label:<12} {status}\n")
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum AnsiStyle {
    BoldCyan,
    Blue,
    Green,
    Yellow,
    Red,
    Dim,
}

fn style(value: &str, style: AnsiStyle, options: TerminalRenderOptions) -> String {
    if !options.color {
        return value.to_owned();
    }

    let code = match style {
        AnsiStyle::BoldCyan => "1;36",
        AnsiStyle::Blue => "34",
        AnsiStyle::Green => "32",
        AnsiStyle::Yellow => "33",
        AnsiStyle::Red => "31",
        AnsiStyle::Dim => "2",
    };

    format!("\x1b[{code}m{value}\x1b[0m")
}

fn risk_severity_style(severity: RiskSeverity) -> AnsiStyle {
    match severity {
        RiskSeverity::High => AnsiStyle::Red,
        RiskSeverity::Medium => AnsiStyle::Yellow,
        RiskSeverity::Low => AnsiStyle::Blue,
        RiskSeverity::Info => AnsiStyle::Dim,
    }
}

fn lockfiles_ok(scan: &ProjectScan) -> bool {
    scan.dependencies
        .ecosystems
        .iter()
        .all(|summary| summary.total == 0 || summary.lockfile.is_some())
}

fn bar(value: usize, total: usize, options: TerminalRenderOptions) -> String {
    let width = options.bar_width.max(4);
    let filled = if total == 0 {
        0
    } else {
        ((value * width) + (total / 2)) / total
    }
    .min(width);
    let empty = width - filled;
    let (filled_char, empty_char) = if options.unicode {
        ('â–ˆ', 'â–‘')
    } else {
        ('#', '.')
    };

    format!(
        "{}{}",
        filled_char.to_string().repeat(filled),
        empty_char.to_string().repeat(empty)
    )
}

fn bar_width_for_terminal(width: usize) -> usize {
    width.saturating_sub(34).clamp(10, 32)
}

impl ColorChoice {
    fn enabled(self, stdout_is_terminal: bool) -> bool {
        match self {
            Self::Auto => stdout_is_terminal,
            Self::Always => true,
            Self::Never => false,
        }
    }
}

#[derive(Debug, Eq, PartialEq)]
struct BuildSystemAggregate {
    label: &'static str,
    count: usize,
}

fn aggregate_build_systems(scan: &ProjectScan) -> Vec<BuildSystemAggregate> {
    let mut aggregates = Vec::<BuildSystemAggregate>::new();

    for build_system in &scan.build_systems {
        let label = build_system_label(build_system.kind);
        if let Some(existing) = aggregates.iter_mut().find(|item| item.label == label) {
            existing.count += 1;
        } else {
            aggregates.push(BuildSystemAggregate { label, count: 1 });
        }
    }

    aggregates.sort_by(|left, right| {
        right
            .count
            .cmp(&left.count)
            .then_with(|| left.label.cmp(right.label))
    });
    aggregates
}

#[derive(Debug, Eq, PartialEq)]
struct DependencyAggregate {
    label: &'static str,
    manifests: usize,
    total_dependencies: usize,
    lockfiles: usize,
    missing_lockfiles: usize,
}

fn aggregate_dependencies(scan: &ProjectScan) -> Vec<DependencyAggregate> {
    let mut aggregates = Vec::<DependencyAggregate>::new();

    for summary in &scan.dependencies.ecosystems {
        let label = dependency_label(summary.ecosystem);
        let has_lockfile = summary.lockfile.is_some();
        if let Some(existing) = aggregates.iter_mut().find(|item| item.label == label) {
            existing.manifests += 1;
            existing.total_dependencies += summary.total;
            if has_lockfile {
                existing.lockfiles += 1;
            } else if summary.total > 0 {
                existing.missing_lockfiles += 1;
            }
        } else {
            aggregates.push(DependencyAggregate {
                label,
                manifests: 1,
                total_dependencies: summary.total,
                lockfiles: usize::from(has_lockfile),
                missing_lockfiles: usize::from(!has_lockfile && summary.total > 0),
            });
        }
    }

    aggregates.sort_by(|left, right| {
        right
            .total_dependencies
            .cmp(&left.total_dependencies)
            .then_with(|| left.label.cmp(right.label))
    });
    aggregates
}

#[derive(Debug, Eq, PartialEq)]
struct TestCommandAggregate {
    command: String,
    sources: usize,
}

fn aggregate_test_commands(scan: &ProjectScan) -> Vec<TestCommandAggregate> {
    let mut aggregates = Vec::<TestCommandAggregate>::new();

    for command in &scan.tests.commands {
        if let Some(existing) = aggregates
            .iter_mut()
            .find(|item| item.command == command.command)
        {
            existing.sources += 1;
        } else {
            aggregates.push(TestCommandAggregate {
                command: command.command.clone(),
                sources: 1,
            });
        }
    }

    aggregates.sort_by(|left, right| {
        right
            .sources
            .cmp(&left.sources)
            .then_with(|| left.command.cmp(&right.command))
    });
    aggregates
}

fn percentage(value: usize, total: usize) -> usize {
    if total == 0 {
        0
    } else {
        ((value * 100) + (total / 2)) / total
    }
}

fn project_kind_label(kind: ProjectKind) -> &'static str {
    match kind {
        ProjectKind::RustWorkspace => "Rust workspace",
        ProjectKind::RustPackage => "Rust package",
        ProjectKind::NodePackage => "Node package",
        ProjectKind::PythonProject => "Python project",
        ProjectKind::Generic => "Generic project",
    }
}

fn language_label(kind: LanguageKind) -> &'static str {
    match kind {
        LanguageKind::Rust => "Rust",
        LanguageKind::TypeScript => "TypeScript",
        LanguageKind::JavaScript => "JavaScript",
        LanguageKind::Python => "Python",
        LanguageKind::C => "C",
        LanguageKind::Cpp => "C++",
        LanguageKind::Go => "Go",
    }
}

fn build_system_label(kind: BuildSystemKind) -> &'static str {
    match kind {
        BuildSystemKind::Cargo => "Cargo",
        BuildSystemKind::NodePackage => "Node",
        BuildSystemKind::PythonProject => "Python",
        BuildSystemKind::PythonRequirements => "Requirements",
        BuildSystemKind::CMake => "CMake",
        BuildSystemKind::GoModule => "Go module",
    }
}

fn dependency_label(ecosystem: DependencyEcosystem) -> &'static str {
    match ecosystem {
        DependencyEcosystem::Rust => "Rust",
        DependencyEcosystem::Node => "Node",
        DependencyEcosystem::Python => "Python",
    }
}

fn risk_severity_label(severity: RiskSeverity) -> &'static str {
    match severity {
        RiskSeverity::High => "HIGH",
        RiskSeverity::Medium => "MEDIUM",
        RiskSeverity::Low => "LOW",
        RiskSeverity::Info => "INFO",
    }
}

fn risk_code_label(code: RiskCode) -> &'static str {
    match code {
        RiskCode::MissingReadme => "missing-readme",
        RiskCode::MissingLicense => "missing-license",
        RiskCode::MissingCi => "missing-ci",
        RiskCode::NoTestsDetected => "no-tests-detected",
        RiskCode::ManifestWithoutLockfile => "manifest-without-lockfile",
        RiskCode::LargeProjectWithoutIgnoreRules => "large-without-ignore-rules",
    }
}

fn write_or_print(rendered: String, output: Option<PathBuf>, overwrite: bool) -> Result<()> {
    let Some(output) = output else {
        print!("{rendered}");
        return Ok(());
    };

    if output.exists() && !overwrite {
        bail!(
            "refusing to overwrite existing output file `{}`",
            output.display()
        );
    }

    fs::write(&output, rendered)
        .with_context(|| format!("failed to write output file `{}`", output.display()))?;
    Ok(())
}