debtmap 0.17.0

Code complexity and technical debt analyzer
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
//! Analyze command handler
//!
//! This module contains the handler for the `analyze` subcommand,
//! including parameter extraction and configuration building.

use crate::cli::args::Commands;
use crate::observability::{enable_profiling, get_timing_report};
use std::path::PathBuf;

use crate::cli::config_builder::{
    build_debug_config, build_display_config, build_feature_config, build_language_config,
    build_path_config, build_performance_config, build_threshold_config, compute_multi_pass,
    compute_verbosity, convert_context_providers, convert_disable_context,
    convert_filter_categories, convert_languages, convert_min_priority, convert_output_format,
    convert_threshold_preset, create_formatting_config, should_use_parallel, AnalysisFeatureConfig,
    DebugConfig, DisplayConfig, LanguageConfig, PathConfig, PerformanceConfig, ThresholdConfig,
};
use crate::cli::setup::{apply_environment_setup, get_worker_count, print_metrics_explanation};
use crate::error::{CliError, ConfigError};
use anyhow::Result;

/// Extracts and builds configuration from the Analyze command variant.
///
/// This function handles the destructuring of the 65 CLI parameters from the Commands enum
/// and builds all configuration groups. It's separated to keep the main handler focused
/// on coordination.
///
/// # Returns
///
/// Returns a tuple of configuration groups and special flags needed for handler coordination.
///
/// # Architecture Note
///
/// This is a necessary extraction function. While long, its complexity is structural
/// (destructuring + config building) rather than logical. The destructuring must happen
/// somewhere when working with clap's Commands enum.
#[allow(clippy::type_complexity)]
pub fn extract_analyze_params(
    command: Commands,
) -> Result<(
    PathConfig,
    ThresholdConfig,
    AnalysisFeatureConfig,
    DisplayConfig,
    PerformanceConfig,
    DebugConfig,
    LanguageConfig,
    bool, // explain_metrics flag
    bool, // no_context_aware flag
)> {
    if let Commands::Analyze {
        path,
        format,
        output,
        threshold_complexity,
        threshold_duplication,
        languages,
        coverage_file,
        enable_context,
        context_providers,
        disable_context,
        top,
        tail,
        summary,
        semantic_off,
        verbosity,
        compact,
        verbose_macro_warnings,
        show_macro_stats,
        min_priority,
        min_score,
        filter_categories,
        no_context_aware,
        threshold_preset,
        plain,
        no_parallel,
        jobs,
        no_multi_pass,
        show_attribution,
        aggregate_only,
        no_aggregation,
        aggregation_method,
        min_problematic,
        no_god_object,
        max_files,
        explain_metrics,
        debug_call_graph,
        trace_functions,
        call_graph_stats_only,
        debug_format,
        validate_call_graph,
        ast_functional_analysis,
        functional_analysis_profile,
        show_splits,
        no_tui,
        quiet,
        show_filter_stats,
        profile: _,
        profile_output: _,
    } = command
    {
        // Build configuration groups using pure builder functions
        let path_cfg = build_path_config(
            path,
            output,
            coverage_file,
            max_files,
            min_priority,
            min_score,
            filter_categories,
            min_problematic,
        );

        let threshold_cfg = build_threshold_config(
            threshold_complexity,
            threshold_duplication,
            threshold_preset,
        );

        let feature_cfg = build_feature_config(
            enable_context,
            context_providers,
            disable_context,
            semantic_off,
            no_god_object,
            ast_functional_analysis,
            functional_analysis_profile,
            validate_call_graph,
        );

        let formatting_config = create_formatting_config(plain, show_splits);

        let display_cfg = build_display_config(
            format,
            compute_verbosity(verbosity, compact),
            summary,
            top,
            tail,
            show_attribution,
            no_tui,
            show_filter_stats,
            formatting_config,
            no_context_aware,
        );

        let perf_cfg = build_performance_config(
            should_use_parallel(no_parallel),
            get_worker_count(jobs),
            compute_multi_pass(no_multi_pass),
            aggregate_only,
            no_aggregation,
        );

        let debug_cfg = build_debug_config(
            verbose_macro_warnings,
            show_macro_stats,
            debug_call_graph,
            trace_functions,
            call_graph_stats_only,
            debug_format,
        );

        let lang_cfg = build_language_config(languages, aggregation_method);

        if quiet {
            std::env::set_var("DEBTMAP_QUIET", "true");
        }

        Ok((
            path_cfg,
            threshold_cfg,
            feature_cfg,
            display_cfg,
            perf_cfg,
            debug_cfg,
            lang_cfg,
            explain_metrics,
            no_context_aware,
        ))
    } else {
        Err(anyhow::anyhow!("Invalid command: expected Analyze variant"))
    }
}

/// Handles the analyze command (coordination only).
///
/// This is the entry point for the analyze command. It coordinates the three main steps:
/// 1. Extract parameters and build configuration
/// 2. Apply environment setup (side effects)
/// 3. Delegate to analysis handler
///
/// # Architecture
///
/// This function follows the "pure core, imperative shell" pattern and serves as a thin
/// coordination layer (30-40 lines). The heavy lifting is delegated to:
/// - `extract_analyze_params`: Parameter extraction and config building
/// - `apply_environment_setup`: Side effects at the boundary
/// - `handle_analyze`: Core analysis logic
///
/// # Returns
///
/// Returns `Result<(), CliError>` for all CLI-related errors (configuration, validation,
/// or analysis execution errors).
///
/// # Specification
///
/// Implements specs 182 and 206: Refactor handle_analyze_command into composable functions
/// with clear error types. This handler is now 30-40 lines (coordination only), with
/// parameter extraction delegated to `extract_analyze_params` and uses typed errors
/// instead of nested Results.
pub fn handle_analyze_command(command: Commands) -> Result<(), CliError> {
    // Extract parameters and build configuration groups
    let (
        path_cfg,
        threshold_cfg,
        feature_cfg,
        display_cfg,
        perf_cfg,
        debug_cfg,
        lang_cfg,
        explain_metrics,
        no_context_aware,
    ) = extract_analyze_params(command).map_err(|e| CliError::InvalidCommand(e.to_string()))?;

    // Apply side effects (I/O at edges)
    apply_environment_setup(no_context_aware)
        .map_err(|e| CliError::Config(ConfigError::ValidationFailed(e.to_string())))?;

    // Handle explain-metrics flag (early return for info display)
    if explain_metrics {
        print_metrics_explanation();
        return Ok(());
    }

    // Build final configuration from component configs (unvalidated)
    let unvalidated_config = build_analyze_config(
        path_cfg,
        threshold_cfg,
        feature_cfg,
        display_cfg,
        perf_cfg,
        debug_cfg,
        lang_cfg,
    );

    // Validate configuration - transition to validated state
    let validated_config = unvalidated_config
        .validate()
        .map_err(|e| CliError::Config(ConfigError::ValidationFailed(e.to_string())))?;

    // Execute with validated configuration - compile-time guarantee of validation
    validated_config
        .execute()
        .map_err(|e| CliError::Config(ConfigError::ValidationFailed(e.to_string())))
}

/// Handle the analyze command with profiling support.
///
/// This function extracts profiling flags from the command, enables profiling if requested,
/// executes the analyze command, and outputs the profiling report. This consolidates
/// the profiling concerns that were previously split between main_inner and the handler.
pub fn handle_analyze_command_with_profiling(command: Commands) -> Result<(), CliError> {
    let (profile, profile_output) = extract_profiling_options(&command);

    if profile {
        enable_profiling();
    }

    handle_analyze_command(command)?;

    if profile {
        output_profiling_report(profile_output)
            .map_err(|e| CliError::InvalidCommand(e.to_string()))?;
    }

    Ok(())
}

/// Extract profiling options from the Analyze command variant.
fn extract_profiling_options(command: &Commands) -> (bool, Option<PathBuf>) {
    if let Commands::Analyze {
        profile,
        profile_output,
        ..
    } = command
    {
        (*profile, profile_output.clone())
    } else {
        (false, None)
    }
}

/// Output profiling report to file or stderr.
fn output_profiling_report(output_path: Option<PathBuf>) -> Result<()> {
    let report = get_timing_report();
    match output_path {
        Some(path) => {
            std::fs::write(&path, report.to_json())
                .map_err(|e| anyhow::anyhow!("Failed to write profile output: {}", e))?;
            eprintln!("Profiling data written to: {}", path.display());
        }
        None => {
            eprintln!("{}", report.to_summary());
        }
    }
    Ok(())
}

/// Build analyze configuration from grouped configuration structs (spec 204)
fn build_analyze_config(
    p: PathConfig,
    t: ThresholdConfig,
    f: AnalysisFeatureConfig,
    d: DisplayConfig,
    pf: PerformanceConfig,
    db: DebugConfig,
    l: LanguageConfig,
) -> crate::commands::AnalyzeConfig<crate::commands::Unvalidated> {
    crate::commands::AnalyzeConfig::new(
        p.path,
        convert_output_format(d.format),
        p.output,
        t.complexity,
        t.duplication,
        convert_languages(l.languages),
        p.coverage_file,
        f.enable_context,
        convert_context_providers(f.context_providers),
        convert_disable_context(f.disable_context),
        d.top,
        d.tail,
        d.summary,
        f.semantic_off,
        d.verbosity,
        db.verbose_macro_warnings,
        db.show_macro_stats,
        convert_min_priority(p.min_priority),
        p.min_score,
        convert_filter_categories(p.filter_categories),
        d.no_context_aware,
        convert_threshold_preset(t.preset),
        d.formatting_config,
        pf.parallel,
        pf.jobs,
        pf.multi_pass,
        d.show_attribution,
        pf.aggregate_only,
        pf.no_aggregation,
        l.aggregation_method,
        p.min_problematic,
        f.no_god_object,
        p.max_files,
        db.debug_call_graph,
        db.trace_functions,
        db.call_graph_stats_only,
        db.debug_format,
        f.validate_call_graph,
        f.ast_functional_analysis,
        f.functional_analysis_profile,
        d.no_tui,
        d.show_filter_stats,
        chrono::Utc::now(),
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::CliError;

    #[test]
    fn test_error_mapping_cli_to_app() {
        let cli_error = CliError::InvalidCommand("test error".to_string());
        let error_string = format!("{}", cli_error);
        assert!(error_string.contains("test error"));
    }

    #[test]
    fn test_handler_composition_with_errors() {
        // Simulate a Result from analyze domain
        let analyze_result: Result<(), anyhow::Error> = Err(anyhow::anyhow!("analysis failed"));

        // Map to CLI error domain
        let cli_result: Result<(), CliError> = analyze_result
            .map_err(|e| CliError::Config(ConfigError::ValidationFailed(e.to_string())));

        // Verify error was properly mapped
        assert!(cli_result.is_err());
        match cli_result.unwrap_err() {
            CliError::Config(ConfigError::ValidationFailed(msg)) => {
                assert!(msg.contains("analysis failed"));
            }
            _ => panic!("Wrong error type"),
        }
    }

    #[test]
    fn test_pipeline_error_handling() {
        // Create a pipeline of Result transformations
        let result = Ok::<i32, String>(42)
            .map(|x| x * 2)
            .map_err(|e| format!("Stage 1: {}", e))
            .and_then(|x| {
                if x > 50 {
                    Ok(x)
                } else {
                    Err("Too small".to_string())
                }
            })
            .map_err(|e| format!("Stage 2: {}", e));

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), 84);
    }

    #[test]
    fn test_error_context_preservation() {
        use anyhow::Context;

        // Simulate a nested operation that adds context
        let result: Result<(), anyhow::Error> = Err(anyhow::anyhow!("root cause"))
            .context("Operation failed")
            .context("Command failed");

        // Map to CLI error preserving context chain
        let cli_result: Result<(), CliError> =
            result.map_err(|e| CliError::Config(ConfigError::ValidationFailed(format!("{:#}", e))));

        // Verify context is preserved
        assert!(cli_result.is_err());
        let error_msg = format!("{}", cli_result.unwrap_err());
        assert!(error_msg.contains("Command failed"));
    }

    #[test]
    fn test_extract_profiling_options_from_analyze() {
        use crate::cli::Cli;
        use clap::Parser;

        let cli = Cli::parse_from(["debtmap", "analyze", ".", "--profile"]);
        let (profile, profile_output) = extract_profiling_options(&cli.command);
        assert!(profile);
        assert!(profile_output.is_none());
    }

    #[test]
    fn test_extract_profiling_options_with_output() {
        use crate::cli::Cli;
        use clap::Parser;

        let cli = Cli::parse_from([
            "debtmap",
            "analyze",
            ".",
            "--profile",
            "--profile-output",
            "output.json",
        ]);
        let (profile, profile_output) = extract_profiling_options(&cli.command);
        assert!(profile);
        assert_eq!(profile_output, Some(PathBuf::from("output.json")));
    }

    #[test]
    fn test_extract_profiling_options_no_profile() {
        use crate::cli::Cli;
        use clap::Parser;

        let cli = Cli::parse_from(["debtmap", "analyze", "."]);
        let (profile, profile_output) = extract_profiling_options(&cli.command);
        assert!(!profile);
        assert!(profile_output.is_none());
    }

    #[test]
    fn test_extract_profiling_options_non_analyze_command() {
        use crate::cli::Cli;
        use clap::Parser;

        let cli = Cli::parse_from(["debtmap", "init"]);
        let (profile, profile_output) = extract_profiling_options(&cli.command);
        assert!(!profile);
        assert!(profile_output.is_none());
    }

    #[test]
    fn test_output_profiling_report_to_file() {
        use tempfile::tempdir;

        let dir = tempdir().unwrap();
        let output_path = dir.path().join("profile.json");

        let result = output_profiling_report(Some(output_path.clone()));
        assert!(result.is_ok());
        assert!(output_path.exists());

        let content = std::fs::read_to_string(&output_path).unwrap();
        // JSON output should contain opening brace or timing data
        assert!(
            content.contains("{") || content.contains("timing"),
            "Expected JSON output, got: {}",
            content
        );
    }

    #[test]
    fn test_output_profiling_report_to_stderr() {
        // This just verifies no panic occurs when outputting to stderr
        let result = output_profiling_report(None);
        assert!(result.is_ok());
    }
}