summaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 108ef1dc880d7022787803c20704c02b8abe5da3 (plain)
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
use clap::Parser;
use std::process;
use tracing::{error, debug};

use spandx::{SpandxError, SpandxResult};
use spandx::cli::{Cli, Commands};
use spandx::cli::commands::{ScanCommand, PullCommand, BuildCommand, VersionCommand};

#[tokio::main]
async fn main() {
    if let Err(exit_code) = run().await {
        process::exit(exit_code);
    }
}

async fn run() -> Result<(), i32> {
    let cli = Cli::parse();

    // Initialize tracing based on log level
    spandx::init_tracing();

    let result: SpandxResult<()> = match cli.command {
        Commands::Scan { 
            path, 
            recursive, 
            airgap, 
            logfile: _,  // TODO: Use logfile for tracing configuration
            format, 
            pull, 
            require: _, // TODO: Implement module loading
        } => {
            let scan_cmd = ScanCommand::new(path, recursive, airgap, format, pull);
            scan_cmd.execute().await
        }

        Commands::Pull => {
            let pull_cmd = PullCommand::new();
            pull_cmd.execute().await.map_err(|e| e.into())
        }

        Commands::Build { 
            directory, 
            logfile: _, // TODO: Use logfile for tracing configuration
            index 
        } => {
            let build_cmd = BuildCommand::new(directory, index);
            build_cmd.execute().await.map_err(|e| e.into())
        }

        Commands::Version => {
            let version_cmd = VersionCommand::new();
            version_cmd.execute().await.map_err(|e| e.into())
        }
    };

    if let Err(e) = result {
        handle_error(&e)
    } else {
        Ok(())
    }
}

/// Enhanced error handling with user-friendly messages and proper exit codes
fn handle_error(error: &SpandxError) -> Result<(), i32> {
    // Log the full error for debugging
    debug!("Full error details: {:?}", error);
    
    // Display user-friendly error message
    eprintln!("Error: {}", error.user_message());
    
    // Show additional context for certain error types
    match error {
        SpandxError::FileNotFound { path } => {
            eprintln!("  The file '{}' could not be found.", path);
            eprintln!("  Please check the path and try again.");
        }
        SpandxError::DirectoryNotFound { path } => {
            eprintln!("  The directory '{}' could not be found.", path);
            eprintln!("  Please check the path and try again.");
        }
        SpandxError::PermissionDenied { path } => {
            eprintln!("  Permission denied accessing '{}'.", path);
            eprintln!("  Please check file permissions and try again.");
        }
        SpandxError::NetworkError { url, .. } => {
            eprintln!("  Failed to access: {}", url);
            eprintln!("  Please check your internet connection and try again.");
            if error.is_retriable() {
                if let Some(retry_ms) = error.retry_delay_ms() {
                    eprintln!("  You can retry after {} seconds.", retry_ms / 1000);
                }
            }
        }
        SpandxError::PackageNotFound { package, version, registry } => {
            eprintln!("  Package '{}@{}' not found in {}.", package, version, registry);
            eprintln!("  Please verify the package name and version.");
        }
        SpandxError::InvalidArguments { .. } => {
            eprintln!("  Use --help for usage information.");
        }
        SpandxError::ConfigError { .. } => {
            eprintln!("  Check your configuration and try again.");
        }
        SpandxError::NotImplemented { feature } => {
            eprintln!("  The feature '{}' is not yet implemented.", feature);
            eprintln!("  Please check the documentation for supported features.");
        }
        _ => {
            // For other errors, show category and suggest actions
            eprintln!("  Category: {}", error.category());
            
            if error.is_retriable() {
                eprintln!("  This error may be temporary. You can try again.");
            } else {
                eprintln!("  Please check the error details and fix any issues.");
            }
        }
    }
    
    // Return appropriate exit code
    let exit_code = match error.category() {
        spandx::error::ErrorCategory::Cli => 2,        // Invalid usage
        spandx::error::ErrorCategory::FileSystem => 3,  // File system issues
        spandx::error::ErrorCategory::Network => 4,     // Network issues
        spandx::error::ErrorCategory::Parse => 5,       // Parse errors
        spandx::error::ErrorCategory::Config => 6,      // Configuration errors
        _ => 1,                                          // General error
    };
    
    error!("Command failed with error category: {} (exit code: {})", error.category(), exit_code);
    Err(exit_code)
}

#[cfg(test)]
mod tests {
    use super::*;
    use assert_cmd::Command;
    use predicates::prelude::*;

    #[test]
    fn test_version_command() {
        let mut cmd = Command::cargo_bin("spandx").unwrap();
        cmd.arg("version");
        
        cmd.assert()
            .success()
            .stdout(predicate::str::starts_with("v"));
    }

    #[test]
    fn test_help_command() {
        let mut cmd = Command::cargo_bin("spandx").unwrap();
        cmd.arg("--help");
        
        cmd.assert()
            .success()
            .stdout(predicate::str::contains("spandx"))
            .stdout(predicate::str::contains("Rust interface to the SPDX catalogue"));
    }

    #[test]
    fn test_scan_help() {
        let mut cmd = Command::cargo_bin("spandx").unwrap();
        cmd.args(&["scan", "--help"]);
        
        cmd.assert()
            .success()
            .stdout(predicate::str::contains("Scan a lockfile"));
    }

    #[test]
    fn test_pull_help() {
        let mut cmd = Command::cargo_bin("spandx").unwrap();
        cmd.args(&["pull", "--help"]);
        
        cmd.assert()
            .success()
            .stdout(predicate::str::contains("Pull the latest offline cache"));
    }

    #[test]
    fn test_build_help() {
        let mut cmd = Command::cargo_bin("spandx").unwrap();
        cmd.args(&["build", "--help"]);
        
        cmd.assert()
            .success()
            .stdout(predicate::str::contains("Build a package index"));
    }
}