pixelsrc 0.2.0

Pixelsrc - GenAI-native pixel art format and compiler
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
//! Configuration loading and discovery for `pxl.toml`
//!
//! Provides functions to find, load, and merge configuration.

use super::schema::{
    AnimationsConfig, DefaultsConfig, ExportsConfig, ProjectConfig, PxlConfig, ValidateConfig,
    WatchConfig,
};
use std::collections::HashMap;
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use thiserror::Error;

/// Configuration loading error
#[derive(Debug, Error)]
pub enum ConfigError {
    /// File I/O error
    #[error("Failed to read config: {0}")]
    Io(#[from] std::io::Error),
    /// TOML parsing error
    #[error("Failed to parse pxl.toml: {0}")]
    Parse(#[from] toml::de::Error),
    /// Validation error
    #[error("Config validation failed:\n{}", .0.iter().map(|e| format!("  - {}", e)).collect::<Vec<_>>().join("\n"))]
    Validation(Vec<String>),
}

/// CLI arguments that can override config values
#[derive(Debug, Default, Clone)]
pub struct CliOverrides {
    /// Override output directory
    pub out: Option<PathBuf>,
    /// Override source directory
    pub src: Option<PathBuf>,
    /// Override scale factor
    pub scale: Option<u32>,
    /// Override padding
    pub padding: Option<u32>,
    /// Build specific atlas only
    pub atlas: Option<String>,
    /// Build specific export format only
    pub export: Option<String>,
    /// Enable strict validation
    pub strict: Option<bool>,
    /// Number of parallel jobs
    pub jobs: Option<usize>,
}

/// Find pxl.toml by walking up from the current working directory.
///
/// Starts from the current directory and walks up parent directories
/// until a `pxl.toml` file is found or the filesystem root is reached.
///
/// # Returns
/// - `Some(path)` if a pxl.toml file is found
/// - `None` if no config file is found
///
/// # Example
/// ```ignore
/// if let Some(config_path) = find_config() {
///     println!("Found config at: {}", config_path.display());
/// }
/// ```
pub fn find_config() -> Option<PathBuf> {
    find_config_from(env::current_dir().ok()?)
}

/// Find pxl.toml by walking up from a specific directory.
///
/// This is the internal implementation that allows specifying the start directory,
/// useful for testing.
pub fn find_config_from(start: PathBuf) -> Option<PathBuf> {
    let mut current = start;

    loop {
        let config_path = current.join("pxl.toml");
        if config_path.exists() {
            return Some(config_path);
        }

        // Move to parent directory
        if !current.pop() {
            // Reached root, no config found
            return None;
        }
    }
}

/// Load configuration from a pxl.toml file.
///
/// If a path is provided, loads from that file. Otherwise, uses `find_config()`
/// to locate the config file. If no config file is found, returns a default
/// configuration.
///
/// # Arguments
/// - `path` - Optional path to a pxl.toml file
///
/// # Returns
/// - `Ok(PxlConfig)` on success
/// - `Err(ConfigError)` if the file cannot be read or parsed
///
/// # Example
/// ```ignore
/// // Load from discovered config
/// let config = load_config(None)?;
///
/// // Load from specific path
/// let config = load_config(Some(Path::new("my-project/pxl.toml")))?;
/// ```
pub fn load_config(path: Option<&Path>) -> Result<PxlConfig, ConfigError> {
    let config_path = match path {
        Some(p) => Some(p.to_path_buf()),
        None => find_config(),
    };

    match config_path {
        Some(p) => load_config_file(&p),
        None => Ok(default_config()),
    }
}

/// Load configuration from a specific file path.
fn load_config_file(path: &Path) -> Result<PxlConfig, ConfigError> {
    let contents = fs::read_to_string(path)?;
    let config: PxlConfig = toml::from_str(&contents)?;

    // Validate the config
    let errors = config.validate();
    if !errors.is_empty() {
        return Err(ConfigError::Validation(errors.into_iter().map(|e| e.to_string()).collect()));
    }

    Ok(config)
}

/// Create a default configuration when no pxl.toml is found.
///
/// Returns a minimal valid configuration with the project name set to
/// the current directory name.
pub fn default_config() -> PxlConfig {
    let project_name = env::current_dir()
        .ok()
        .and_then(|p| p.file_name().map(|n| n.to_string_lossy().into_owned()))
        .unwrap_or_else(|| "unnamed".to_string());

    PxlConfig {
        project: ProjectConfig {
            name: project_name,
            version: "0.1.0".to_string(),
            src: PathBuf::from("src/pxl"),
            out: PathBuf::from("build"),
        },
        defaults: DefaultsConfig::default(),
        atlases: HashMap::new(),
        animations: AnimationsConfig::default(),
        exports: ExportsConfig::default(),
        validate: ValidateConfig::default(),
        watch: WatchConfig::default(),
    }
}

/// Merge CLI overrides into a configuration.
///
/// CLI arguments take precedence over config file values.
///
/// # Arguments
/// - `config` - The configuration to modify
/// - `overrides` - CLI overrides to apply
///
/// # Example
/// ```ignore
/// let mut config = load_config(None)?;
/// let overrides = CliOverrides {
///     out: Some(PathBuf::from("dist")),
///     strict: Some(true),
///     ..Default::default()
/// };
/// merge_cli_overrides(&mut config, &overrides);
/// ```
pub fn merge_cli_overrides(config: &mut PxlConfig, overrides: &CliOverrides) {
    // Override output directory
    if let Some(ref out) = overrides.out {
        config.project.out = out.clone();
    }

    // Override source directory
    if let Some(ref src) = overrides.src {
        config.project.src = src.clone();
    }

    // Override scale
    if let Some(scale) = overrides.scale {
        config.defaults.scale = scale;
    }

    // Override padding
    if let Some(padding) = overrides.padding {
        config.defaults.padding = padding;
    }

    // Override strict mode
    if let Some(strict) = overrides.strict {
        config.validate.strict = strict;
    }
}

/// Get the project root directory from a config file path.
///
/// Returns the parent directory of the pxl.toml file.
pub fn project_root(config_path: &Path) -> Option<&Path> {
    config_path.parent()
}

/// Resolve a path relative to the project root.
///
/// If the path is absolute, returns it unchanged.
/// If relative, joins it with the project root.
pub fn resolve_path(project_root: &Path, path: &Path) -> PathBuf {
    if path.is_absolute() {
        path.to_path_buf()
    } else {
        project_root.join(path)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs::File;
    use std::io::Write;
    use tempfile::TempDir;

    #[test]
    fn test_find_config_in_current_dir() {
        let temp = TempDir::new().unwrap();
        let config_path = temp.path().join("pxl.toml");
        File::create(&config_path).unwrap().write_all(b"[project]\nname = \"test\"").unwrap();

        let found = find_config_from(temp.path().to_path_buf());
        assert_eq!(found, Some(config_path));
    }

    #[test]
    fn test_find_config_in_parent_dir() {
        let temp = TempDir::new().unwrap();
        let config_path = temp.path().join("pxl.toml");
        File::create(&config_path).unwrap().write_all(b"[project]\nname = \"test\"").unwrap();

        // Create a subdirectory
        let subdir = temp.path().join("src").join("sprites");
        fs::create_dir_all(&subdir).unwrap();

        let found = find_config_from(subdir);
        assert_eq!(found, Some(config_path));
    }

    #[test]
    fn test_find_config_not_found() {
        let temp = TempDir::new().unwrap();
        let found = find_config_from(temp.path().to_path_buf());
        assert_eq!(found, None);
    }

    #[test]
    fn test_load_config_from_file() {
        let temp = TempDir::new().unwrap();
        let config_path = temp.path().join("pxl.toml");
        File::create(&config_path)
            .unwrap()
            .write_all(
                br#"
[project]
name = "test-project"
version = "2.0.0"

[defaults]
scale = 3
padding = 2

[atlases.main]
sources = ["sprites/**"]
max_size = [512, 512]
"#,
            )
            .unwrap();

        let config = load_config(Some(&config_path)).unwrap();
        assert_eq!(config.project.name, "test-project");
        assert_eq!(config.project.version, "2.0.0");
        assert_eq!(config.defaults.scale, 3);
        assert_eq!(config.defaults.padding, 2);
        assert!(config.atlases.contains_key("main"));
    }

    #[test]
    fn test_load_config_missing_file_uses_defaults() {
        let temp = TempDir::new().unwrap();
        let config_path = temp.path().join("nonexistent.toml");

        // When file doesn't exist, load_config with explicit path should error
        let result = load_config(Some(&config_path));
        assert!(result.is_err());
    }

    #[test]
    fn test_load_config_no_path_no_file_uses_defaults() {
        // When no config is found via find_config_from, default_config() is used
        let temp = TempDir::new().unwrap();

        // find_config_from returns None when no pxl.toml exists
        let found = find_config_from(temp.path().to_path_buf());
        assert!(found.is_none());

        // default_config should return sensible defaults
        let config = default_config();
        assert_eq!(config.project.src, PathBuf::from("src/pxl"));
        assert_eq!(config.project.out, PathBuf::from("build"));
        assert_eq!(config.defaults.scale, 1);
        assert_eq!(config.defaults.padding, 1);
    }

    #[test]
    fn test_load_config_invalid_toml() {
        let temp = TempDir::new().unwrap();
        let config_path = temp.path().join("pxl.toml");
        File::create(&config_path).unwrap().write_all(b"this is not valid toml {{{").unwrap();

        let result = load_config(Some(&config_path));
        assert!(matches!(result, Err(ConfigError::Parse(_))));
    }

    #[test]
    fn test_load_config_validation_error() {
        let temp = TempDir::new().unwrap();
        let config_path = temp.path().join("pxl.toml");
        File::create(&config_path)
            .unwrap()
            .write_all(
                br#"
[project]
name = ""

[defaults]
scale = 0
"#,
            )
            .unwrap();

        let result = load_config(Some(&config_path));
        assert!(matches!(result, Err(ConfigError::Validation(_))));
    }

    #[test]
    fn test_merge_cli_overrides_out() {
        let mut config = default_config();
        let overrides = CliOverrides { out: Some(PathBuf::from("dist")), ..Default::default() };

        merge_cli_overrides(&mut config, &overrides);
        assert_eq!(config.project.out, PathBuf::from("dist"));
    }

    #[test]
    fn test_merge_cli_overrides_src() {
        let mut config = default_config();
        let overrides =
            CliOverrides { src: Some(PathBuf::from("assets/pxl")), ..Default::default() };

        merge_cli_overrides(&mut config, &overrides);
        assert_eq!(config.project.src, PathBuf::from("assets/pxl"));
    }

    #[test]
    fn test_merge_cli_overrides_scale() {
        let mut config = default_config();
        let overrides = CliOverrides { scale: Some(4), ..Default::default() };

        merge_cli_overrides(&mut config, &overrides);
        assert_eq!(config.defaults.scale, 4);
    }

    #[test]
    fn test_merge_cli_overrides_strict() {
        let mut config = default_config();
        assert!(!config.validate.strict);

        let overrides = CliOverrides { strict: Some(true), ..Default::default() };

        merge_cli_overrides(&mut config, &overrides);
        assert!(config.validate.strict);
    }

    #[test]
    fn test_merge_cli_overrides_multiple() {
        let mut config = default_config();
        let overrides = CliOverrides {
            out: Some(PathBuf::from("output")),
            scale: Some(2),
            padding: Some(4),
            strict: Some(true),
            ..Default::default()
        };

        merge_cli_overrides(&mut config, &overrides);
        assert_eq!(config.project.out, PathBuf::from("output"));
        assert_eq!(config.defaults.scale, 2);
        assert_eq!(config.defaults.padding, 4);
        assert!(config.validate.strict);
    }

    #[test]
    fn test_resolve_path_absolute() {
        let root = Path::new("/project");
        let absolute = Path::new("/other/path");
        assert_eq!(resolve_path(root, absolute), PathBuf::from("/other/path"));
    }

    #[test]
    fn test_resolve_path_relative() {
        let root = Path::new("/project");
        let relative = Path::new("src/pxl");
        assert_eq!(resolve_path(root, relative), PathBuf::from("/project/src/pxl"));
    }

    #[test]
    fn test_project_root() {
        let config_path = Path::new("/project/pxl.toml");
        assert_eq!(project_root(config_path), Some(Path::new("/project")));
    }

    #[test]
    fn test_default_config() {
        let config = default_config();
        assert!(!config.project.name.is_empty());
        assert_eq!(config.project.version, "0.1.0");
        assert_eq!(config.project.src, PathBuf::from("src/pxl"));
        assert_eq!(config.project.out, PathBuf::from("build"));
    }
}