unfk 1.1.0

A fast, modern CLI tool for scanning and repairing file formatting issues
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
//! Configuration management

mod editorconfig;

use std::path::{Path, PathBuf};

use anyhow::{Context, Result};
use globset::{Glob, GlobSet, GlobSetBuilder};
use serde::{Deserialize, Serialize};

use crate::cli::Cli;
pub use editorconfig::EditorConfigSettings;

/// Main configuration struct
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct Config {
    /// Path to the config file that was loaded (if any)
    #[serde(skip)]
    pub source_path: Option<PathBuf>,

    /// Whether EditorConfig integration is enabled
    #[serde(skip)]
    pub editorconfig_enabled: bool,

    /// Default line ending style
    #[serde(rename = "line-ending")]
    pub line_ending: LineEnding,

    /// Target encoding
    pub encoding: String,

    /// Ensure files end with a newline
    #[serde(rename = "final-newline")]
    pub final_newline: bool,

    /// How to handle trailing whitespace
    #[serde(rename = "trailing-whitespace")]
    pub trailing_whitespace: TrailingWhitespace,

    /// Indentation settings
    pub indent: IndentConfig,

    /// Patterns to ignore
    #[serde(default)]
    pub ignore: Vec<String>,

    /// Per-pattern rules
    #[serde(default)]
    pub rules: Vec<Rule>,

    /// Maximum file size in bytes (default 10MB)
    #[serde(rename = "max-file-size")]
    pub max_file_size: usize,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            source_path: None,
            editorconfig_enabled: true,
            line_ending: LineEnding::Lf,
            encoding: "utf-8".to_string(),
            final_newline: true,
            trailing_whitespace: TrailingWhitespace::Remove,
            indent: IndentConfig::default(),
            ignore: vec![
                "node_modules".to_string(),
                "target".to_string(),
                ".git".to_string(),
                "*.min.js".to_string(),
                "*.min.css".to_string(),
            ],
            rules: Vec::new(),
            max_file_size: 10 * 1024 * 1024, // 10MB
        }
    }
}

impl Config {
    /// Load configuration from file and CLI overrides
    pub fn load(cli: &Cli) -> Result<Self> {
        let mut config = if let Some(path) = &cli.config {
            Self::load_from_file(path)?
        } else {
            Self::discover()?
        };

        // Apply CLI overrides
        config.apply_cli_overrides(cli);

        Ok(config)
    }

    /// Load configuration from a specific file
    fn load_from_file(path: &Path) -> Result<Self> {
        let content = std::fs::read_to_string(path)
            .with_context(|| format!("Failed to read config file: {}", path.display()))?;

        let mut config: Config = toml::from_str(&content)
            .with_context(|| format!("Failed to parse config file: {}", path.display()))?;

        config.source_path = Some(path.to_path_buf());
        Ok(config)
    }

    /// Discover configuration file by searching up the directory tree
    fn discover() -> Result<Self> {
        let current_dir = std::env::current_dir()?;
        let config_names = [".unfkrc.toml", ".unfkrc", "unfk.toml"];

        let mut dir = current_dir.as_path();
        loop {
            for name in &config_names {
                let config_path = dir.join(name);
                if config_path.exists() {
                    return Self::load_from_file(&config_path);
                }
            }

            match dir.parent() {
                Some(parent) => dir = parent,
                None => break,
            }
        }

        // No config file found, use defaults
        Ok(Self::default())
    }

    /// Apply CLI flag overrides to the configuration
    fn apply_cli_overrides(&mut self, cli: &Cli) {
        if let Some(line_ending) = &cli.line_ending {
            self.line_ending = match line_ending {
                crate::cli::LineEndingArg::Lf => LineEnding::Lf,
                crate::cli::LineEndingArg::Crlf => LineEnding::Crlf,
                crate::cli::LineEndingArg::Auto => LineEnding::Auto,
            };
        }

        if let Some(indent) = &cli.indent {
            self.indent = IndentConfig::parse(indent);
        }

        if let Some(encoding) = &cli.encoding {
            self.encoding = encoding.clone();
        }

        if let Some(max_size) = &cli.max_size {
            if let Some(size) = parse_size(max_size) {
                self.max_file_size = size;
            }
        }

        // Add CLI excludes to ignore list
        self.ignore.extend(cli.exclude.clone());

        // Handle --no-editorconfig flag
        if cli.no_editorconfig {
            self.editorconfig_enabled = false;
        }
    }

    /// Build a GlobSet from the ignore patterns
    pub fn build_ignore_globset(&self) -> Result<GlobSet> {
        let mut builder = GlobSetBuilder::new();
        for pattern in &self.ignore {
            builder.add(Glob::new(pattern)?);
        }
        Ok(builder.build()?)
    }

    /// Build a GlobSet from include patterns
    pub fn build_include_globset(&self, patterns: &[String]) -> Result<Option<GlobSet>> {
        if patterns.is_empty() {
            return Ok(None);
        }
        let mut builder = GlobSetBuilder::new();
        for pattern in patterns {
            builder.add(Glob::new(pattern)?);
        }
        Ok(Some(builder.build()?))
    }

    /// Get the effective settings for a specific file
    ///
    /// Precedence order (highest to lowest):
    /// 1. Per-pattern rules from unfk config
    /// 2. EditorConfig settings (if enabled)
    /// 3. Global unfk config settings
    /// 4. Built-in defaults
    pub fn settings_for_file(&self, path: &Path) -> FileSettings {
        // Start with unfk config defaults (or built-in defaults if no config)
        let mut settings = FileSettings {
            line_ending: self.line_ending,
            indent: self.indent.clone(),
            final_newline: self.final_newline,
            trailing_whitespace: self.trailing_whitespace,
            encoding: self.encoding.clone(),
        };

        // Apply EditorConfig settings (if enabled)
        // EditorConfig overrides defaults but is overridden by explicit unfk config
        if self.editorconfig_enabled {
            let ec_settings = EditorConfigSettings::for_file(path);

            // Only apply EditorConfig values if unfk config is using defaults
            // (i.e., no explicit config file was loaded)
            if self.source_path.is_none() {
                // No unfk config file - EditorConfig overrides defaults
                if let Some(le) = ec_settings.line_ending {
                    settings.line_ending = le;
                }
                if let Some(indent) = ec_settings.to_indent_config() {
                    settings.indent = indent;
                }
                if let Some(fnl) = ec_settings.insert_final_newline {
                    settings.final_newline = fnl;
                }
                if let Some(tw) = ec_settings.trim_trailing_whitespace {
                    settings.trailing_whitespace = tw;
                }
                if let Some(charset) = ec_settings.charset {
                    settings.encoding = charset;
                }
            }
            // If unfk config exists, it takes precedence over EditorConfig
            // (EditorConfig values are not applied to override explicit config)
        }

        // Apply per-pattern rules from unfk config (highest precedence)
        let path_str = path.to_string_lossy();
        for rule in &self.rules {
            if rule.matches(&path_str) {
                rule.apply_to(&mut settings);
            }
        }

        settings
    }
}

/// Line ending style
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum LineEnding {
    /// Unix-style LF
    #[default]
    Lf,
    /// Windows-style CRLF
    Crlf,
    /// Auto-detect from file
    Auto,
}

/// Trailing whitespace handling
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum TrailingWhitespace {
    /// Remove trailing whitespace
    #[default]
    Remove,
    /// Keep trailing whitespace
    Keep,
}

/// Indentation configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct IndentConfig {
    /// Style: tabs or spaces
    pub style: IndentStyle,
    /// Width in spaces (for space indentation or tab display width)
    pub width: usize,
}

impl Default for IndentConfig {
    fn default() -> Self {
        Self {
            style: IndentStyle::Spaces,
            width: 2,
        }
    }
}

impl IndentConfig {
    /// Parse an indent string like "tabs" or "spaces:4"
    pub fn parse(s: &str) -> Self {
        if s == "tabs" {
            Self {
                style: IndentStyle::Tabs,
                width: 4,
            }
        } else if let Some(width_str) = s.strip_prefix("spaces:") {
            let width = width_str.parse().unwrap_or(2);
            Self {
                style: IndentStyle::Spaces,
                width,
            }
        } else if s == "spaces" {
            Self {
                style: IndentStyle::Spaces,
                width: 2,
            }
        } else {
            Self::default()
        }
    }
}

/// Indentation style
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum IndentStyle {
    /// Use tabs
    Tabs,
    /// Use spaces
    #[default]
    Spaces,
}

/// Per-pattern rule
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Rule {
    /// Glob pattern to match
    pub pattern: String,

    /// Line ending override
    #[serde(rename = "line-ending")]
    pub line_ending: Option<LineEnding>,

    /// Indentation override
    pub indent: Option<IndentConfig>,

    /// Final newline override
    #[serde(rename = "final-newline")]
    pub final_newline: Option<bool>,

    /// Trailing whitespace override
    #[serde(rename = "trailing-whitespace")]
    pub trailing_whitespace: Option<TrailingWhitespace>,
}

impl Rule {
    /// Check if this rule matches a path
    pub fn matches(&self, path: &str) -> bool {
        if let Ok(glob) = Glob::new(&self.pattern) {
            glob.compile_matcher().is_match(path)
        } else {
            false
        }
    }

    /// Apply this rule's overrides to file settings
    pub fn apply_to(&self, settings: &mut FileSettings) {
        if let Some(le) = self.line_ending {
            settings.line_ending = le;
        }
        if let Some(indent) = &self.indent {
            settings.indent = indent.clone();
        }
        if let Some(fnl) = self.final_newline {
            settings.final_newline = fnl;
        }
        if let Some(tw) = self.trailing_whitespace {
            settings.trailing_whitespace = tw;
        }
    }
}

/// Effective settings for a specific file
#[derive(Debug, Clone)]
pub struct FileSettings {
    pub line_ending: LineEnding,
    pub indent: IndentConfig,
    pub final_newline: bool,
    pub trailing_whitespace: TrailingWhitespace,
    pub encoding: String,
}

/// Parse a size string like "10MB" or "1024"
fn parse_size(s: &str) -> Option<usize> {
    let s = s.trim().to_uppercase();
    if let Some(num) = s.strip_suffix("GB") {
        num.trim().parse::<usize>().ok().map(|n| n * 1024 * 1024 * 1024)
    } else if let Some(num) = s.strip_suffix("MB") {
        num.trim().parse::<usize>().ok().map(|n| n * 1024 * 1024)
    } else if let Some(num) = s.strip_suffix("KB") {
        num.trim().parse::<usize>().ok().map(|n| n * 1024)
    } else if let Some(num) = s.strip_suffix('B') {
        num.trim().parse().ok()
    } else {
        s.parse().ok()
    }
}

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

    #[test]
    fn test_parse_size() {
        assert_eq!(parse_size("1024"), Some(1024));
        assert_eq!(parse_size("10KB"), Some(10 * 1024));
        assert_eq!(parse_size("10MB"), Some(10 * 1024 * 1024));
        assert_eq!(parse_size("1GB"), Some(1024 * 1024 * 1024));
    }

    #[test]
    fn test_indent_config_parse() {
        let tabs = IndentConfig::parse("tabs");
        assert_eq!(tabs.style, IndentStyle::Tabs);

        let spaces4 = IndentConfig::parse("spaces:4");
        assert_eq!(spaces4.style, IndentStyle::Spaces);
        assert_eq!(spaces4.width, 4);
    }
}