sizelint 0.1.2

Lint your working tree based on file size
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
use crate::cli::{Cli, Commands, RuleAction};
use crate::config::Config;
use crate::discovery::FileDiscovery;
use crate::error::{Result, SizelintError};
use crate::output::{OutputFormatter, print_error, print_progress, print_success};
use crate::rules::{ConfigurableRule, RuleEngine};
use colored::*;
use std::path::PathBuf;
use std::process;
use tracing::{Level, debug, span};

pub struct App {
    cli: Cli,
    config: Config,
}

impl App {
    pub fn new(cli: Cli) -> Result<Self> {
        let _span = span!(Level::DEBUG, "App::new").entered();
        debug!("Creating new App instance");

        let config = Self::load_config(&cli)?;

        debug!("App initialized successfully");
        Ok(Self { cli, config })
    }

    fn load_config(cli: &Cli) -> Result<Config> {
        let _span = span!(Level::DEBUG, "load_config").entered();

        let config = if let Some(config_path) = &cli.config {
            debug!(
                "Loading config from specified path: {}",
                config_path.display()
            );
            Config::load_from_file(config_path)?
        } else {
            let current_dir = std::env::current_dir()
                .map_err(|e| SizelintError::CurrentDirectory { source: e })?;

            debug!(
                "Searching for config file starting from: {}",
                current_dir.display()
            );

            if let Some(config_path) = Config::find_config_file(&current_dir)? {
                debug!("Found config file: {}", config_path.display());
                print_progress(&format!("Found config file: {}", config_path.display()));
                Config::load_with_defaults(config_path)?
            } else {
                debug!("No config file found, using defaults");
                print_progress("No config file found, using defaults");
                Config::default()
            }
        };

        debug!("Config loaded successfully");
        Ok(config)
    }

    pub async fn run(&self) -> Result<()> {
        match self.cli.get_command() {
            Commands::Check { paths, .. } => self.run_check(paths).await,
            Commands::Init {
                force,
                stdout,
                edit,
            } => self.run_init(force, stdout, edit).await,
            Commands::Rules { action } => self.run_rules(action).await,
            Commands::Completions { shell } => Cli::generate_completion(&shell).map_err(|e| {
                SizelintError::config_invalid("shell".to_string(), shell.to_string(), e)
            }),
        }
    }

    async fn run_check(&self, paths: Vec<PathBuf>) -> Result<()> {
        let check_paths = self.determine_check_paths(paths);
        let discovery = self.setup_file_discovery(&check_paths)?;
        let files = self.discover_files(&discovery, &check_paths)?;
        self.validate_and_check_files(files).await
    }

    fn determine_check_paths(&self, paths: Vec<PathBuf>) -> Vec<PathBuf> {
        if paths.is_empty() {
            self.cli.get_paths()
        } else {
            paths
        }
    }

    fn setup_file_discovery(&self, check_paths: &[PathBuf]) -> Result<FileDiscovery> {
        debug!("Initializing file discovery...");
        FileDiscovery::new(
            check_paths.first().unwrap_or(&PathBuf::from(".")),
            &self.config.sizelint.excludes,
        )
    }

    fn discover_files(
        &self,
        discovery: &FileDiscovery,
        check_paths: &[PathBuf],
    ) -> Result<Vec<PathBuf>> {
        debug!("Discovering files...");

        if self.cli.get_staged()
            || (self.config.sizelint.check_staged && discovery.is_in_git_repo())
        {
            discovery.discover_staged_files()
        } else if self.cli.get_working_tree()
            || (self.config.sizelint.check_working_tree && discovery.is_in_git_repo())
        {
            discovery.discover_working_tree_files()
        } else if check_paths.len() == 1 && check_paths[0] == PathBuf::from(".") {
            discovery.discover_files(self.config.sizelint.respect_gitignore)
        } else {
            discovery.discover_specific_paths(check_paths)
        }
    }

    async fn validate_and_check_files(&self, files: Vec<PathBuf>) -> Result<()> {
        if files.is_empty() {
            print_success("No files to check");
            return Ok(());
        }

        print_progress(&format!("Found {} files to check", files.len()));

        debug!("Setting up rules...");
        let rule_engine = self.create_rule_engine()?;

        debug!("Running checks...");
        let violations = rule_engine.check_files(&files)?;

        self.output_results_and_exit(&violations, files.len())
    }

    fn output_results_and_exit(
        &self,
        violations: &[crate::rules::Violation],
        file_count: usize,
    ) -> Result<()> {
        let formatter = OutputFormatter::new(self.cli.get_format(), self.cli.get_quiet());
        formatter.output_results(violations, file_count)?;

        if !violations.is_empty() {
            let has_errors = violations
                .iter()
                .any(|v| matches!(v.severity, crate::rules::Severity::Error));

            let fail_on_warn = self.cli.get_fail_on_warn() || self.config.sizelint.fail_on_warn;
            let has_warnings = violations
                .iter()
                .any(|v| matches!(v.severity, crate::rules::Severity::Warning));

            if has_errors || (fail_on_warn && has_warnings) {
                process::exit(1);
            }
        }

        Ok(())
    }

    async fn run_init(&self, force: bool, stdout: bool, edit: bool) -> Result<()> {
        let default_config = Config::create_default_config();

        if stdout {
            println!("{default_config}");
            return Ok(());
        }

        let config_file = PathBuf::from("sizelint.toml");

        if config_file.exists() && !force {
            if edit {
                print_progress(&format!("Opening existing {}", config_file.display()));
                return self.open_editor(&config_file);
            } else {
                print_error(
                    "sizelint.toml already exists. Use --force to overwrite or --edit to open existing file.",
                );
                process::exit(1);
            }
        }

        std::fs::write(&config_file, default_config).map_err(|e| {
            SizelintError::filesystem("write config file".to_string(), config_file.clone(), e)
        })?;

        print_success(&format!("Created {}", config_file.display()));

        if edit {
            self.open_editor(&config_file)?;
        } else {
            println!(
                "You can now customize the configuration and run 'sizelint check' to start linting."
            );
        }

        Ok(())
    }

    fn open_editor(&self, file_path: &PathBuf) -> Result<()> {
        use std::process::Command;

        let editor = std::env::var("VISUAL")
            .or_else(|_| std::env::var("EDITOR"))
            .unwrap_or_else(|_| "vi".to_string());

        print_progress(&format!("Opening {} in {}...", file_path.display(), editor));

        let status = Command::new(&editor).arg(file_path).status().map_err(|e| {
            SizelintError::config_invalid(
                "editor".to_string(),
                editor.clone(),
                format!("Failed to start editor: {e}"),
            )
        })?;

        if !status.success() {
            return Err(SizelintError::config_invalid(
                "editor".to_string(),
                editor,
                "Editor exited with error".to_string(),
            ));
        }

        print_success("Configuration saved");
        Ok(())
    }

    async fn run_rules(&self, action: RuleAction) -> Result<()> {
        match action {
            RuleAction::List => {
                let rule_engine = self.create_rule_engine()?;
                let rule_info = rule_engine.get_all_rule_info(&self.config);

                if rule_info.is_empty() {
                    println!("No rules configured or available.");
                    return Ok(());
                }

                println!("{}", "Configured Rules:".bold().blue());
                println!();

                for info in &rule_info {
                    let status = if info.enabled {
                        "✓ enabled".green()
                    } else {
                        "✗ disabled".red()
                    };

                    println!("  {} - {} [{}]", info.name.bold(), info.description, status);
                }

                println!();
                let enabled_count = rule_info.iter().filter(|r| r.enabled).count();
                let disabled_count = rule_info.iter().filter(|r| !r.enabled).count();
                println!(
                    "{}",
                    format!("Runtime: {enabled_count} active, {disabled_count} inactive rules")
                        .bold()
                );

                if enabled_count > 0 {
                    println!("\n{}", "Active Rules:".bold().green());
                }
                for info in rule_info.iter().filter(|r| r.enabled) {
                    let mut details = Vec::new();

                    if let Some(priority) = info.priority {
                        details.push(format!("priority={priority}"));
                    } else {
                        details.push("priority=default".to_string());
                    }
                    if let Some(max_str) = &info.max_size_str {
                        details.push(format!("max={max_str}"));
                    }
                    if let Some(warn_str) = &info.warn_size_str {
                        details.push(format!("warn={warn_str}"));
                    }
                    if !info.includes.is_empty() {
                        details.push(format!("includes={}", info.includes.len()));
                    } else {
                        details.push("includes=[]".to_string());
                    }
                    if !info.excludes.is_empty() {
                        details.push(format!("excludes={}", info.excludes.len()));
                    } else {
                        details.push("excludes=[]".to_string());
                    }
                    if info.warn_on_match {
                        details.push("warn_on_match=true".to_string());
                    }
                    if info.error_on_match {
                        details.push("error_on_match=true".to_string());
                    }

                    println!("{}: {}", info.name, details.join(", "));
                }

                if disabled_count > 0 {
                    println!("\n{}", "Inactive Rules:".bold().red());
                    for info in rule_info.iter().filter(|r| !r.enabled) {
                        let mut details = Vec::new();

                        if let Some(priority) = info.priority {
                            details.push(format!("priority={priority}"));
                        } else {
                            details.push("priority=default".to_string());
                        }
                        if let Some(max_str) = &info.max_size_str {
                            details.push(format!("max={max_str}"));
                        }
                        if let Some(warn_str) = &info.warn_size_str {
                            details.push(format!("warn={warn_str}"));
                        }
                        if !info.includes.is_empty() {
                            details.push(format!("includes={}", info.includes.len()));
                        } else {
                            details.push("includes=[]".to_string());
                        }
                        if !info.excludes.is_empty() {
                            details.push(format!("excludes={}", info.excludes.len()));
                        } else {
                            details.push("excludes=[]".to_string());
                        }
                        if info.warn_on_match {
                            details.push("warn_on_match=true".to_string());
                        }
                        if info.error_on_match {
                            details.push("error_on_match=true".to_string());
                        }

                        println!("{}: {}", info.name, details.join(", "));
                    }
                }
            }
            RuleAction::Describe { rule } => {
                let rule_engine = self.create_rule_engine()?;
                let rule_info = rule_engine.get_all_rule_info(&self.config);

                if let Some(info) = rule_info.iter().find(|r| r.name == rule) {
                    println!("{}", format!("Rule: {}", info.name).bold().blue());
                    println!("{}", "".repeat(50).blue());
                    println!();
                    println!("Description: {}", info.description);
                    println!(
                        "Status: {}",
                        if info.enabled {
                            "✓ enabled".green()
                        } else {
                            "✗ disabled".red()
                        }
                    );

                    let mut severities = Vec::new();
                    if info.max_size.is_some() {
                        severities.push("Error".red().to_string());
                    }
                    if info.warn_size.is_some() {
                        severities.push("Warning".yellow().to_string());
                    }
                    if !severities.is_empty() {
                        println!("Can generate: {}", severities.join(", "));
                    }
                    println!();

                    println!("{}", "Configuration:".bold());
                    if let Some(priority) = info.priority {
                        println!("  Priority: {priority}");
                    } else {
                        println!("  Priority: default (lowest)");
                    }
                    if let Some(max_str) = &info.max_size_str {
                        let bytes_info = if let Some(bytes) = info.max_size {
                            format!(" ({bytes} bytes)")
                        } else {
                            String::new()
                        };
                        println!("  Max size: {max_str}{bytes_info}");
                    }
                    if let Some(warn_str) = &info.warn_size_str {
                        let bytes_info = if let Some(bytes) = info.warn_size {
                            format!(" ({bytes} bytes)")
                        } else {
                            String::new()
                        };
                        println!("  Warning size: {warn_str}{bytes_info}");
                    }
                    if !info.includes.is_empty() {
                        println!("  Includes: {:?}", info.includes);
                    } else {
                        println!("  Includes: all files");
                    }
                    if !info.excludes.is_empty() {
                        println!("  Excludes: {:?}", info.excludes);
                    } else {
                        println!("  Excludes: none");
                    }
                    if info.warn_on_match {
                        println!("  Warn on match: enabled");
                    }
                    if info.error_on_match {
                        println!("  Error on match: enabled");
                    }
                } else {
                    print_error(&format!("Unknown rule: {rule}"));
                    process::exit(1);
                }
            }
        }

        Ok(())
    }

    fn create_rule_engine(&self) -> Result<RuleEngine> {
        let mut engine = RuleEngine::new();

        // Always add a default rule that catches all files not matched by specific rules
        self.add_default_rule(&mut engine)?;

        // Add any specific rules from configuration
        if let Some(rules_config) = &self.config.rules {
            let enabled_rules = rules_config.get_enabled_rules();
            for (rule_name, rule_def) in enabled_rules {
                let mut rule_definition = rule_def.clone();

                if rule_definition.max_size.is_none() {
                    rule_definition.max_size = self.config.sizelint.max_file_size.clone();
                }
                if rule_definition.warn_size.is_none() {
                    rule_definition.warn_size = self.config.sizelint.warn_file_size.clone();
                }

                let rule = ConfigurableRule::new(rule_name.clone(), rule_definition)?;
                engine.add_rule(rule);
            }
        }

        Ok(engine)
    }

    fn add_default_rule(&self, engine: &mut RuleEngine) -> Result<()> {
        use crate::config::RuleDefinition;

        let default_rule = RuleDefinition {
            enabled: true,
            description: "Default file size check".to_string(),
            priority: 1000,
            max_size: self.config.sizelint.max_file_size.clone(),
            warn_size: self.config.sizelint.warn_file_size.clone(),
            includes: vec![],
            excludes: vec![],
            ..Default::default()
        };

        let rule = ConfigurableRule::new("default".to_string(), default_rule)?;
        engine.add_rule(rule);
        Ok(())
    }
}