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
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
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
//! Binary size analysis CLI for Rust workspace packages.
//!
//! This module provides the command-line interface for the `bloaty` tool, which analyzes
//! the size impact of Cargo features on library and binary targets. It coordinates
//! package discovery, feature iteration, artifact building, and report generation.

#![cfg_attr(feature = "fail-on-warnings", deny(warnings))]
#![warn(clippy::all, clippy::pedantic, clippy::nursery, clippy::cargo)]
#![allow(clippy::multiple_crate_versions)]

use anyhow::{Context, Result};
use bytesize::ByteSize;
use cargo_metadata::{MetadataCommand, TargetKind, camino::Utf8Path};
use clap::Parser;
use glob::glob;
use regex::Regex;
use serde_json::json;
use std::{
    fs,
    io::Write,
    process::{Command, Stdio},
    time::UNIX_EPOCH,
};

/// Command-line arguments for the bloaty binary size analysis tool.
#[derive(Parser)]
#[command(
    author,
    version,
    about = "Run cargo-bloat, cargo-llvm-lines, or cargo size across workspace members"
)]
struct Args {
    #[arg(short, long, value_name = "PACKAGE")]
    package: Vec<String>,

    #[arg(long, value_name = "PACKAGE_PATTERN")]
    package_pattern: Option<String>,

    #[arg(long, value_name = "SKIP_PACKAGES")]
    skip_packages: Vec<String>,

    #[arg(long, value_name = "SKIP_PACKAGE_PATTERN")]
    skip_package_pattern: Option<String>,

    #[arg(long, value_name = "SKIP_FEATURES")]
    skip_features: Vec<String>,

    #[arg(long, value_name = "SKIP_FEATURE_PATTERN")]
    skip_feature_pattern: Option<String>,

    #[arg(short, long, value_parser = ["bloat", "llvm-lines", "size"], value_name = "TOOL")]
    tool: Vec<String>,

    #[arg(long, value_name = "REPORT_FILE")]
    report_file: Option<String>,

    #[arg(long, value_parser = ["text", "json", "jsonl", "all"], default_value = "all", value_name = "FORMAT")]
    output_format: Vec<String>,
}

/// File handles for the different output report formats.
struct ReportFiles {
    /// Optional text format report file handle.
    text: Option<fs::File>,
    /// Optional JSONL format report file handle.
    jsonl: Option<fs::File>,
}

/// Context for tracking analysis state and output files across package analysis runs.
struct AnalysisContext {
    /// Unix timestamp when the analysis was started.
    timestamp: u64,
    /// Base filename for output reports (without extension).
    base_filename: String,
    /// File handles for active report outputs.
    report_files: ReportFiles,
    /// In-memory JSON report structure being built during analysis.
    json_report: serde_json::Value,
}

/// Parses and normalizes command-line arguments.
///
/// Expands comma-separated values in package, skip-packages, skip-features, tool, and
/// output-format arguments into individual items.
#[must_use]
fn parse_args() -> Args {
    let mut args = Args::parse();

    args.package = args
        .package
        .into_iter()
        .flat_map(|x| x.split(',').map(ToString::to_string).collect::<Vec<_>>())
        .collect();

    args.skip_packages = args
        .skip_packages
        .into_iter()
        .flat_map(|x| x.split(',').map(ToString::to_string).collect::<Vec<_>>())
        .collect();

    args.skip_features = args
        .skip_features
        .into_iter()
        .flat_map(|x| x.split(',').map(ToString::to_string).collect::<Vec<_>>())
        .collect();

    args.tool = args
        .tool
        .into_iter()
        .flat_map(|x| x.split(',').map(ToString::to_string).collect::<Vec<_>>())
        .collect();

    args.output_format = args
        .output_format
        .into_iter()
        .flat_map(|x| x.split(',').map(ToString::to_string).collect::<Vec<_>>())
        .collect();

    args
}

/// Verifies that all requested cargo tools are installed.
///
/// # Panics
///
/// Exits the process with status code 1 if any required tools are not available.
fn check_tools_availability(tools: &[String]) {
    let mut any_unavailable = false;

    for tool in tools {
        if !tool_available(tool) {
            eprintln!("[error] cargo {tool} not found; install cargo-{tool}");
            any_unavailable = true;
        }
    }

    if any_unavailable {
        std::process::exit(1);
    }
}

/// Creates report output files based on command-line arguments.
///
/// # Errors
///
/// * File creation fails
/// * Writing initial report headers fails
fn setup_report_files(args: &Args) -> Result<AnalysisContext> {
    let timestamp = switchy_time::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_secs();

    let base_filename = args
        .report_file
        .clone()
        .unwrap_or_else(|| format!("bloaty_report_{timestamp}"));

    let should_output_text = args.output_format.contains(&"text".to_string())
        || args.output_format.contains(&"all".to_string());
    let should_output_jsonl = args.output_format.contains(&"jsonl".to_string())
        || args.output_format.contains(&"all".to_string());

    let mut text_report_file = if should_output_text {
        Some(fs::File::create(format!("{base_filename}.txt"))?)
    } else {
        None
    };

    let jsonl_report_file = if should_output_jsonl {
        Some(fs::File::create(format!("{base_filename}.jsonl"))?)
    } else {
        None
    };

    if let Some(report) = &mut text_report_file {
        writeln!(report, "Bloaty Analysis Report")?;
        writeln!(report, "===================\n")?;
    }

    let json_report = json!({
        "timestamp": timestamp,
        "packages": []
    });

    Ok(AnalysisContext {
        timestamp,
        base_filename,
        report_files: ReportFiles {
            text: text_report_file,
            jsonl: jsonl_report_file,
        },
        json_report,
    })
}

/// Writes a JSONL package start event to the report.
///
/// # Errors
///
/// * JSON serialization fails
/// * Writing to the JSONL report file fails
fn write_jsonl_package_start(ctx: &mut AnalysisContext, package_name: &str) -> Result<()> {
    if let Some(report) = &mut ctx.report_files.jsonl {
        writeln!(
            report,
            "{}",
            serde_json::to_string(&json!({
                "type": "package_start",
                "name": package_name,
                "timestamp": ctx.timestamp
            }))?
        )?;
    }
    Ok(())
}

/// Writes a JSONL package end event to the report.
///
/// # Errors
///
/// * JSON serialization fails
/// * Writing to the JSONL report file fails
fn write_jsonl_package_end(ctx: &mut AnalysisContext, package_name: &str) -> Result<()> {
    if let Some(report) = &mut ctx.report_files.jsonl {
        writeln!(
            report,
            "{}",
            serde_json::to_string(&json!({
                "type": "package_end",
                "name": package_name,
                "timestamp": ctx.timestamp
            }))?
        )?;
    }
    Ok(())
}

/// Writes a JSONL target start event to the report.
///
/// # Errors
///
/// * JSON serialization fails
/// * Writing to the JSONL report file fails
fn write_jsonl_target_start(
    ctx: &mut AnalysisContext,
    package_name: &str,
    target_name: &str,
) -> Result<()> {
    if let Some(report) = &mut ctx.report_files.jsonl {
        writeln!(
            report,
            "{}",
            serde_json::to_string(&json!({
                "type": "target_start",
                "package": package_name,
                "target": target_name,
                "timestamp": ctx.timestamp
            }))?
        )?;
    }
    Ok(())
}

/// Writes a JSONL target end event to the report.
///
/// # Errors
///
/// * JSON serialization fails
/// * Writing to the JSONL report file fails
fn write_jsonl_target_end(
    ctx: &mut AnalysisContext,
    package_name: &str,
    target_name: &str,
) -> Result<()> {
    if let Some(report) = &mut ctx.report_files.jsonl {
        writeln!(
            report,
            "{}",
            serde_json::to_string(&json!({
                "type": "target_end",
                "package": package_name,
                "target": target_name,
                "timestamp": ctx.timestamp
            }))?
        )?;
    }
    Ok(())
}

/// Writes a JSONL base rlib size record to the report.
///
/// # Errors
///
/// * JSON serialization fails
/// * Writing to the JSONL report file fails
fn write_jsonl_base_size(
    ctx: &mut AnalysisContext,
    package_name: &str,
    target_name: &str,
    base_size: u64,
) -> Result<()> {
    if let Some(report) = &mut ctx.report_files.jsonl {
        writeln!(
            report,
            "{}",
            serde_json::to_string(&json!({
                "type": "base_size",
                "package": package_name,
                "target": target_name,
                "size": base_size,
                "size_formatted": ByteSize(base_size).to_string(),
                "timestamp": ctx.timestamp
            }))?
        )?;
    }
    Ok(())
}

/// Writes a JSONL feature rlib size record to the report.
///
/// # Errors
///
/// * JSON serialization fails
/// * Writing to the JSONL report file fails
fn write_jsonl_feature(
    ctx: &mut AnalysisContext,
    package_name: &str,
    target_name: &str,
    feature: &str,
    size: u64,
    diff: i64,
) -> Result<()> {
    if let Some(report) = &mut ctx.report_files.jsonl {
        let sign = if diff >= 0 { '+' } else { '-' };
        writeln!(
            report,
            "{}",
            serde_json::to_string(&json!({
                "type": "feature",
                "package": package_name,
                "target": target_name,
                "feature": feature,
                "size": size,
                "diff": diff,
                "diff_formatted": format!("{sign}{}", ByteSize(diff.unsigned_abs())),
                "size_formatted": ByteSize(size).to_string(),
                "timestamp": ctx.timestamp
            }))?
        )?;
    }
    Ok(())
}

/// Writes a package header to the text report.
///
/// # Errors
///
/// * Writing to the text report file fails
fn write_text_package_header(ctx: &mut AnalysisContext, package_name: &str) -> Result<()> {
    if let Some(report) = &mut ctx.report_files.text {
        writeln!(report, "\nPackage: {package_name}")?;
        writeln!(report, "===================")?;
    }
    Ok(())
}

/// Writes a target header to the text report.
///
/// # Errors
///
/// * Writing to the text report file fails
fn write_text_target_header(ctx: &mut AnalysisContext, target_name: &str) -> Result<()> {
    if let Some(report) = &mut ctx.report_files.text {
        writeln!(report, "\nTarget: {target_name}")?;
        writeln!(report, "-------------------")?;
    }
    Ok(())
}

/// Writes a base rlib size to the text report.
///
/// # Errors
///
/// * Writing to the text report file fails
fn write_text_base_size(ctx: &mut AnalysisContext, base_size: u64) -> Result<()> {
    if let Some(report) = &mut ctx.report_files.text {
        writeln!(report, "Base size: {}", ByteSize(base_size))?;
    }
    Ok(())
}

/// Writes a feature rlib size to the text report.
///
/// # Errors
///
/// * Writing to the text report file fails
fn write_text_feature(
    ctx: &mut AnalysisContext,
    feature: &str,
    size: u64,
    diff: i64,
) -> Result<()> {
    if let Some(report) = &mut ctx.report_files.text {
        let sign = if diff >= 0 { '+' } else { '-' };
        writeln!(
            report,
            "Feature: {:<15} | Size: {} | Diff: {}{}",
            feature,
            ByteSize(size),
            sign,
            ByteSize(diff.unsigned_abs())
        )?;
    }
    Ok(())
}

/// Determines whether a feature should be skipped based on filter patterns.
///
/// # Errors
///
/// * Invalid regex pattern in `skip_feature_pattern`
fn should_skip_feature(feature: &str, args: &Args) -> Result<bool> {
    if args.skip_features.contains(&feature.to_string()) {
        return Ok(true);
    }

    if let Some(pattern) = &args.skip_feature_pattern {
        let re = Regex::new(pattern).context(format!("invalid regex pattern: {pattern}"))?;
        if re.is_match(feature) {
            return Ok(true);
        }
    }

    Ok(false)
}

/// Determines whether a package should be analyzed based on include/exclude filters.
///
/// # Errors
///
/// * Invalid regex pattern in `package_pattern` or `skip_package_pattern`
fn should_analyze_package(pkg_name: &str, args: &Args) -> Result<bool> {
    // If specific packages are specified, check if this package is in the list
    if !args.package.is_empty() && !args.package.contains(&pkg_name.to_string()) {
        return Ok(false);
    }

    // Check package pattern if specified
    if let Some(pattern) = &args.package_pattern {
        let re = Regex::new(pattern).context(format!("invalid package pattern: {pattern}"))?;
        if !re.is_match(pkg_name) {
            return Ok(false);
        }
    }

    // Check skip packages list
    if args.skip_packages.contains(&pkg_name.to_string()) {
        return Ok(false);
    }

    // Check skip package pattern if specified
    if let Some(pattern) = &args.skip_package_pattern {
        let re = Regex::new(pattern).context(format!("invalid skip package pattern: {pattern}"))?;
        if re.is_match(pkg_name) {
            return Ok(false);
        }
    }

    Ok(true)
}

/// Analyzes a single target, measuring size impact of all features.
///
/// Builds the target with no features (base size), then with each feature individually,
/// recording both rlib and binary sizes (if applicable).
///
/// # Errors
///
/// * Building the target fails
/// * Measuring the built artifact fails
/// * Writing to report files fails
fn analyze_target(
    ctx: &mut AnalysisContext,
    pkg: &cargo_metadata::Package,
    target: &cargo_metadata::Target,
    available_features: &[String],
    args: &Args,
    metadata: &cargo_metadata::Metadata,
) -> Result<serde_json::Value> {
    let mut target_json = json!({
        "name": target.name,
        "base_size": 0,
        "base_binary_size": 0,
        "features": []
    });

    write_text_target_header(ctx, &target.name)?;
    write_jsonl_target_start(ctx, &pkg.name, &target.name)?;

    // Build and measure base rlib
    let base_size = build_and_measure_rlib(
        &pkg.manifest_path,
        &metadata.target_directory,
        &pkg.name,
        None,
    )?;
    println!("  base rlib: {}", ByteSize(base_size));
    write_text_base_size(ctx, base_size)?;
    write_jsonl_base_size(ctx, &pkg.name, &target.name, base_size)?;

    // Build and measure base binary if it's a binary target
    let base_binary_size = if target.kind.iter().any(|k| k == &TargetKind::Bin) {
        let size = build_and_measure_binary(
            &pkg.manifest_path,
            &metadata.target_directory,
            &target.name,
            None,
        )?;
        println!("  base binary: {}", ByteSize(size));
        write_text_base_binary_size(ctx, size)?;
        write_jsonl_base_binary_size(ctx, &pkg.name, &target.name, size)?;
        size
    } else {
        0
    };

    target_json["base_size"] = json!(base_size);
    target_json["base_binary_size"] = json!(base_binary_size);

    for feat in available_features {
        if should_skip_feature(feat, args)? {
            continue;
        }

        // Build and measure rlib with feature
        let size = build_and_measure_rlib(
            &pkg.manifest_path,
            &metadata.target_directory,
            &pkg.name,
            Some(feat),
        )?;

        #[allow(clippy::cast_possible_wrap)]
        let diff = size as i64 - base_size as i64;

        println!(
            "  feature {feat:<15} rlib: {} ({}{})",
            ByteSize(size),
            if diff >= 0 { '+' } else { '-' },
            ByteSize(diff.unsigned_abs()),
        );

        write_text_feature(ctx, feat, size, diff)?;
        write_jsonl_feature(ctx, &pkg.name, &target.name, feat, size, diff)?;

        // Build and measure binary with feature if it's a binary target
        let binary_size = if target.kind.iter().any(|k| k == &TargetKind::Bin) {
            let size = build_and_measure_binary(
                &pkg.manifest_path,
                &metadata.target_directory,
                &target.name,
                Some(feat),
            )?;
            #[allow(clippy::cast_possible_wrap)]
            let binary_diff = size as i64 - base_binary_size as i64;
            println!(
                "  feature {:<15} binary: {} ({}{})",
                feat,
                ByteSize(size),
                if binary_diff >= 0 { '+' } else { '-' },
                ByteSize(binary_diff.unsigned_abs()),
            );
            write_text_binary_feature(ctx, feat, size, binary_diff)?;
            write_jsonl_binary_feature(ctx, &pkg.name, &target.name, feat, size, binary_diff)?;
            size
        } else {
            0
        };

        #[allow(clippy::cast_possible_wrap)]
        target_json["features"].as_array_mut().unwrap().push(json!({
            "name": feat,
            "size": size,
            "diff": diff,
            "diff_formatted": format!("{}{}", if diff >= 0 { '+' } else { '-' }, ByteSize(diff.unsigned_abs())),
            "size_formatted": ByteSize(size).to_string(),
            "binary_size": binary_size,
            "binary_diff": binary_size as i64 - base_binary_size as i64,
            "binary_diff_formatted": format!("{}{}", if binary_size >= base_binary_size { '+' } else { '-' }, ByteSize((binary_size as i64 - base_binary_size as i64).unsigned_abs())),
            "binary_size_formatted": ByteSize(binary_size).to_string()
        }));
    }

    write_jsonl_target_end(ctx, &pkg.name, &target.name)?;
    Ok(target_json)
}

/// Writes a base binary size to the text report.
///
/// # Errors
///
/// * Writing to the text report file fails
fn write_text_base_binary_size(ctx: &mut AnalysisContext, base_size: u64) -> Result<()> {
    if let Some(report) = &mut ctx.report_files.text {
        writeln!(report, "Base binary size: {}", ByteSize(base_size))?;
    }
    Ok(())
}

/// Writes a feature binary size to the text report.
///
/// # Errors
///
/// * Writing to the text report file fails
fn write_text_binary_feature(
    ctx: &mut AnalysisContext,
    feature: &str,
    size: u64,
    diff: i64,
) -> Result<()> {
    if let Some(report) = &mut ctx.report_files.text {
        let sign = if diff >= 0 { '+' } else { '-' };
        writeln!(
            report,
            "Feature: {:<15} | Binary Size: {} | Binary Diff: {}{}",
            feature,
            ByteSize(size),
            sign,
            ByteSize(diff.unsigned_abs())
        )?;
    }
    Ok(())
}

/// Writes a JSONL base binary size record to the report.
///
/// # Errors
///
/// * JSON serialization fails
/// * Writing to the JSONL report file fails
fn write_jsonl_base_binary_size(
    ctx: &mut AnalysisContext,
    package_name: &str,
    target_name: &str,
    base_size: u64,
) -> Result<()> {
    if let Some(report) = &mut ctx.report_files.jsonl {
        writeln!(
            report,
            "{}",
            serde_json::to_string(&json!({
                "type": "base_binary_size",
                "package": package_name,
                "target": target_name,
                "size": base_size,
                "size_formatted": ByteSize(base_size).to_string(),
                "timestamp": ctx.timestamp
            }))?
        )?;
    }
    Ok(())
}

/// Writes a JSONL feature binary size record to the report.
///
/// # Errors
///
/// * JSON serialization fails
/// * Writing to the JSONL report file fails
fn write_jsonl_binary_feature(
    ctx: &mut AnalysisContext,
    package_name: &str,
    target_name: &str,
    feature: &str,
    size: u64,
    diff: i64,
) -> Result<()> {
    if let Some(report) = &mut ctx.report_files.jsonl {
        let sign = if diff >= 0 { '+' } else { '-' };
        writeln!(
            report,
            "{}",
            serde_json::to_string(&json!({
                "type": "binary_feature",
                "package": package_name,
                "target": target_name,
                "feature": feature,
                "size": size,
                "diff": diff,
                "diff_formatted": format!("{}{}", sign, ByteSize(diff.unsigned_abs())),
                "size_formatted": ByteSize(size).to_string(),
                "timestamp": ctx.timestamp
            }))?
        )?;
    }
    Ok(())
}

/// Analyzes a workspace package, running requested tools and measuring feature sizes.
///
/// # Errors
///
/// * Package filtering fails
/// * Running analysis tools fails
/// * Writing to report files fails
fn analyze_package(
    ctx: &mut AnalysisContext,
    pkg: &cargo_metadata::Package,
    args: &Args,
    metadata: &cargo_metadata::Metadata,
) -> Result<()> {
    if !should_analyze_package(&pkg.name, args)? {
        return Ok(());
    }

    println!("\n=== Analyzing package: {} ===", pkg.name);
    write_text_package_header(ctx, &pkg.name)?;
    write_jsonl_package_start(ctx, &pkg.name)?;

    let mut package_json = json!({
        "name": pkg.name,
        "targets": []
    });

    let available_features: Vec<String> = pkg.features.keys().cloned().collect();

    for target in &pkg.targets {
        if target
            .kind
            .iter()
            .any(|k| matches!(k, TargetKind::Bin | TargetKind::CDyLib | TargetKind::DyLib))
        {
            for tool in &args.tool {
                let mut cmd = Command::new("cargo");

                cmd.current_dir(pkg.manifest_path.parent().unwrap())
                    .arg(tool)
                    .arg("--release");

                if target.kind.iter().any(|k| k == &TargetKind::Bin) {
                    cmd.arg("--bin").arg(&target.name);
                } else {
                    cmd.arg("--lib");
                }

                println!("$ {cmd:?}");
                let status = cmd.status().context("running tool")?;
                if !status.success() {
                    eprintln!("[error] {} failed for {} ({})", tool, pkg.name, target.name);
                }
            }
        }
    }

    let rlib_targets: Vec<_> = pkg
        .targets
        .iter()
        .filter(|t| {
            t.kind.iter().any(|k| k == &TargetKind::Lib)
                && !t
                    .kind
                    .iter()
                    .any(|k| matches!(k, TargetKind::CDyLib | TargetKind::DyLib))
        })
        .collect();

    if !rlib_targets.is_empty() {
        for target in rlib_targets {
            let target_json =
                analyze_target(ctx, pkg, target, &available_features, args, metadata)?;
            package_json["targets"]
                .as_array_mut()
                .unwrap()
                .push(target_json);
        }
    }

    write_jsonl_package_end(ctx, &pkg.name)?;
    ctx.json_report["packages"]
        .as_array_mut()
        .unwrap()
        .push(package_json);

    Ok(())
}

/// Writes the final consolidated JSON report if JSON output is enabled.
///
/// # Errors
///
/// * Creating the JSON report file fails
/// * Serializing the JSON report fails
/// * Writing to the JSON report file fails
fn write_final_json_report(ctx: &AnalysisContext, args: &Args) -> Result<()> {
    let should_output_json = args.output_format.contains(&"json".to_string())
        || args.output_format.contains(&"all".to_string());
    if should_output_json {
        let mut json_file = fs::File::create(format!("{}.json", ctx.base_filename))?;
        writeln!(
            json_file,
            "{}",
            serde_json::to_string_pretty(&ctx.json_report)?
        )?;
    }
    Ok(())
}

/// Executes bloaty binary size analysis across workspace packages.
///
/// # Errors
///
/// * Loading workspace metadata fails
/// * Setting up report files fails
/// * Analyzing packages fails
/// * Writing final reports fails
#[allow(clippy::too_many_lines, clippy::cognitive_complexity)]
fn main() -> Result<()> {
    pretty_env_logger::init();

    let args = parse_args();
    check_tools_availability(&args.tool);
    let mut ctx = setup_report_files(&args)?;
    let metadata = MetadataCommand::new().no_deps().exec()?;

    for pkg in metadata
        .packages
        .iter()
        .filter(|p| metadata.workspace_members.contains(&p.id))
    {
        analyze_package(&mut ctx, pkg, &args, &metadata)?;
    }

    write_final_json_report(&ctx, &args)?;
    Ok(())
}

/// Builds an rlib with optional features and measures its size.
///
/// # Errors
///
/// * Cargo clean fails
/// * Cargo build fails
/// * Finding the built rlib fails
/// * Reading rlib metadata fails
fn build_and_measure_rlib(
    manifest: &Utf8Path,
    target_dir: &Utf8Path,
    crate_name: &str,
    feat: Option<&String>,
) -> Result<u64> {
    let _ = Command::new("cargo")
        .current_dir(manifest.parent().unwrap())
        .arg("clean")
        .arg("--release")
        .status();

    let mut cmd = Command::new("cargo");

    cmd.current_dir(manifest.parent().unwrap())
        .arg("build")
        .arg("--release")
        .arg("--no-default-features");

    if let Some(f) = feat {
        cmd.arg("--features").arg(f);
    }

    println!("$ {cmd:?}\n");
    cmd.status().context("building rlib")?;

    let deps = target_dir.join("release").join("deps");
    let prefix = format!("lib{}-", crate_name.replace('-', "_"));
    for entry in glob(&format!("{deps}/*.rlib"))? {
        let path = entry?;
        if let Some(fname) = path.file_name().and_then(|f| f.to_str())
            && fname.starts_with(&prefix)
        {
            return Ok(fs::metadata(&path)?.len());
        }
    }
    Err(anyhow::anyhow!("rlib for {crate_name} not found"))
}

/// Builds a binary with optional features and measures its size.
///
/// # Errors
///
/// * Cargo clean fails
/// * Cargo build fails
/// * Reading binary metadata fails
fn build_and_measure_binary(
    manifest: &Utf8Path,
    target_dir: &Utf8Path,
    binary_name: &str,
    feat: Option<&String>,
) -> Result<u64> {
    let _ = Command::new("cargo")
        .current_dir(manifest.parent().unwrap())
        .arg("clean")
        .arg("--release")
        .status();

    let mut cmd = Command::new("cargo");

    cmd.current_dir(manifest.parent().unwrap())
        .arg("build")
        .arg("--release")
        .arg("--no-default-features")
        .arg("--bin")
        .arg(binary_name);

    if let Some(f) = feat {
        cmd.arg("--features").arg(f);
    }

    println!("$ {cmd:?}\n");
    cmd.status().context("building binary")?;

    let binary_path = target_dir.join("release").join(binary_name);
    Ok(fs::metadata(&binary_path)?.len())
}

/// Checks if a cargo tool is installed and available.
#[must_use]
fn tool_available(tool: &str) -> bool {
    Command::new("cargo")
        .arg(tool)
        .arg("--version")
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .is_ok_and(|s| s.success())
}