zim-studio 1.3.6

A Terminal-Based Audio Project Scaffold and Metadata System
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
//! Application configuration management.
//!
//! This module handles the persistent configuration for zim-studio, including
//! the root directory for projects, default folders to create, artist information,
//! and various preferences. Configuration is stored in the user's config directory
//! (typically ~/.config/zim/config.toml) and supports customization of project
//! structure and behavior.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::error::Error;
use std::fs;
use std::path::PathBuf;

#[derive(Debug, Serialize, Deserialize)]
pub struct Config {
    #[serde(default = "default_artist")]
    pub default_artist: String,
    #[serde(default = "default_folders")]
    pub default_folders: Vec<String>,
    #[serde(default = "default_gitignore")]
    pub default_gitignore: Vec<String>,
    #[serde(default = "default_include_readmes")]
    pub include_readmes: bool,
    #[serde(default = "default_normalize_project_names")]
    pub normalize_project_names: bool,
    #[serde(default = "default_daw_folders")]
    pub daw_folders: Vec<String>,
    #[serde(default = "default_tag_mappings")]
    pub tag_mappings: HashMap<String, String>,
}

fn default_artist() -> String {
    // Try to get username and capitalize first letter
    std::env::var("USER")
        .or_else(|_| std::env::var("USERNAME")) // Windows fallback
        .ok()
        .and_then(|name| {
            if name.is_empty() {
                None
            } else {
                let mut chars = name.chars();
                chars.next().map(|first| {
                    first.to_uppercase().collect::<String>() + &chars.as_str().to_lowercase()
                })
            }
        })
        .unwrap_or_default()
}

fn default_folders() -> Vec<String> {
    vec![
        "sources".to_string(),
        "edits".to_string(),
        "bounced".to_string(),
        "mixes".to_string(),
        "masters".to_string(),
        "project".to_string(),
    ]
}

fn default_gitignore() -> Vec<String> {
    vec![
        // Audio files
        "*.wav".to_string(),
        "*.flac".to_string(),
        "*.aiff".to_string(),
        "*.aif".to_string(),
        "*.asd".to_string(),
        "*.mp3".to_string(),
        "*.m4a".to_string(),
        // Visual media files
        "*.jpg".to_string(),
        "*.jpeg".to_string(),
        "*.png".to_string(),
        "*.gif".to_string(),
        "*.mp4".to_string(),
        "*.mov".to_string(),
        "*.avi".to_string(),
        "*.webm".to_string(),
        "*.tiff".to_string(),
        "*.bmp".to_string(),
        "*.heic".to_string(),
        "*.heif".to_string(),
        // DAW temp files
        "*.als~".to_string(),
        "project/*/temp/".to_string(),
    ]
}

fn default_include_readmes() -> bool {
    true
}

fn default_normalize_project_names() -> bool {
    true
}

fn default_daw_folders() -> Vec<String> {
    vec![
        "live".to_string(),
        "reaper".to_string(),
        "bitwig".to_string(),
        "renoise".to_string(),
    ]
}

fn default_tag_mappings() -> HashMap<String, String> {
    let mut mappings = HashMap::new();
    // Common audio interface/hardware patterns
    mappings.insert("ES-9".to_string(), "eurorack".to_string());
    mappings.insert("ES-8".to_string(), "eurorack".to_string());
    mappings.insert("ES-3".to_string(), "eurorack".to_string());
    mappings.insert("modular".to_string(), "eurorack".to_string());
    // DAW patterns
    mappings.insert("ableton".to_string(), "ableton-live".to_string());
    mappings.insert("reaper".to_string(), "reaper".to_string());
    mappings.insert("bitwig".to_string(), "bitwig".to_string());
    mappings.insert("renoise".to_string(), "renoise".to_string());
    // Common descriptors
    mappings.insert("loop".to_string(), "loop".to_string());
    mappings.insert("drum".to_string(), "drums".to_string());
    mappings.insert("bass".to_string(), "bass".to_string());
    mappings.insert("kick".to_string(), "drums".to_string());
    mappings.insert("snare".to_string(), "drums".to_string());
    mappings.insert("hihat".to_string(), "drums".to_string());
    mappings.insert("synth".to_string(), "synth".to_string());
    mappings.insert("vocal".to_string(), "vocals".to_string());
    mappings.insert("vox".to_string(), "vocals".to_string());
    mappings.insert("field-recording".to_string(), "field-recording".to_string());
    mappings.insert("ambient".to_string(), "ambient".to_string());
    mappings
}

fn default_zimignore_content() -> String {
    r#"# ZIM Studio Default .zimignore
# 
# This file defines patterns for files and directories that should be ignored
# when running "zim update" to generate sidecar files. The syntax is similar
# to .gitignore with support for glob patterns.

# DAW Project Files and Directories
project/live/
project/reaper/
project/bitwig/
project/renoise/

# DAW-specific temporary and backup files
*.als-backup
*.rpp-bak
*.bwproject-backup
*.xrns-backup

# Common DAW auto-save and backup directories
**/Backup/
**/Auto Save/
**/AutoSave/
**/Ableton Project Info/

# Cache and temporary directories
**/.cache/
**/temp/
**/tmp/
**/.tmp/

# System files
.DS_Store
Thumbs.db
desktop.ini

# Log files
*.log

# Example: Keep important files even if they match patterns above
# Use ! to negate patterns
# !important.als
# !project/live/important-session.als
"#
    .to_string()
}

impl Default for Config {
    fn default() -> Self {
        Self::new()
    }
}

impl Config {
    pub fn new() -> Self {
        Self {
            default_artist: default_artist(),
            default_folders: default_folders(),
            default_gitignore: default_gitignore(),
            include_readmes: default_include_readmes(),
            normalize_project_names: default_normalize_project_names(),
            daw_folders: default_daw_folders(),
            tag_mappings: default_tag_mappings(),
        }
    }

    pub fn config_dir() -> Result<PathBuf, Box<dyn Error>> {
        // Check for XDG_CONFIG_HOME first (useful for testing)
        let config_dir = if let Ok(xdg_config) = std::env::var("XDG_CONFIG_HOME") {
            PathBuf::from(xdg_config).join("zim")
        } else {
            dirs::config_dir()
                .ok_or("Unable to find config directory")?
                .join("zim")
        };
        Ok(config_dir)
    }

    pub fn config_path() -> Result<PathBuf, Box<dyn Error>> {
        Ok(Self::config_dir()?.join("config.toml"))
    }

    pub fn default_zimignore_path() -> Result<PathBuf, Box<dyn Error>> {
        Ok(Self::config_dir()?.join("default.zimignore"))
    }

    pub fn load() -> Result<Self, Box<dyn Error>> {
        let config_path = Self::config_path()?;

        if !config_path.exists() {
            // Return default config instead of error
            return Ok(Default::default());
        }

        let contents = fs::read_to_string(&config_path)?;
        let config: Config = toml::from_str(&contents)?;
        Ok(config)
    }

    pub fn save(&self) -> Result<(), Box<dyn Error>> {
        let config_dir = Self::config_dir()?;

        if !config_dir.exists() {
            fs::create_dir_all(&config_dir)?;
        }

        let config_path = Self::config_path()?;
        let toml_string = toml::to_string_pretty(self)?;
        fs::write(&config_path, toml_string)?;

        Ok(())
    }

    pub fn exists() -> Result<bool, Box<dyn Error>> {
        Ok(Self::config_path()?.exists())
    }

    /// Create the default .zimignore template if it doesn't exist
    pub fn ensure_default_zimignore() -> Result<(), Box<dyn Error>> {
        let zimignore_path = Self::default_zimignore_path()?;

        if !zimignore_path.exists() {
            let config_dir = Self::config_dir()?;
            if !config_dir.exists() {
                fs::create_dir_all(&config_dir)?;
            }

            let default_content = default_zimignore_content();
            fs::write(&zimignore_path, default_content)?;
        }

        Ok(())
    }

    /// Load the default .zimignore template content
    pub fn load_default_zimignore() -> Result<String, Box<dyn Error>> {
        let zimignore_path = Self::default_zimignore_path()?;

        if zimignore_path.exists() {
            Ok(fs::read_to_string(&zimignore_path)?)
        } else {
            Ok(default_zimignore_content())
        }
    }

    pub fn set_value(&mut self, key: &str, value: &str) -> Result<(), Box<dyn Error>> {
        match key {
            "default_artist" => self.default_artist = value.to_string(),
            "normalize_project_names" => {
                self.normalize_project_names = value
                    .parse::<bool>()
                    .map_err(|_| "Value must be 'true' or 'false'")?;
            }
            _ => return Err(format!("Unknown configuration key: {key}").into()),
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::Mutex;
    use tempfile::TempDir;

    // Use a mutex to ensure tests that modify environment variables don't run concurrently
    static ENV_MUTEX: Mutex<()> = Mutex::new(());

    #[test]
    fn test_default_artist() {
        let artist = default_artist();
        // Should either be empty or start with uppercase
        if !artist.is_empty() {
            assert!(artist.chars().next().unwrap().is_uppercase());
        }
    }

    #[test]
    fn test_default_folders() {
        let folders = default_folders();
        assert!(folders.contains(&"sources".to_string()));
        assert!(folders.contains(&"edits".to_string()));
        assert!(folders.contains(&"bounced".to_string()));
        assert!(folders.contains(&"mixes".to_string()));
        assert!(folders.contains(&"masters".to_string()));
        assert!(folders.contains(&"project".to_string()));
        assert_eq!(folders.len(), 6);
    }

    #[test]
    fn test_default_daw_folders() {
        let folders = default_daw_folders();
        assert!(folders.contains(&"live".to_string()));
        assert!(folders.contains(&"reaper".to_string()));
        assert!(folders.contains(&"bitwig".to_string()));
        assert!(folders.contains(&"renoise".to_string()));
    }

    #[test]
    fn test_default_gitignore() {
        let gitignore = default_gitignore();
        assert!(gitignore.contains(&"*.wav".to_string()));
        assert!(gitignore.contains(&"*.aif".to_string()));
        assert!(gitignore.contains(&"*.flac".to_string()));
        assert!(gitignore.contains(&"*.mp3".to_string()));
        assert!(gitignore.contains(&"*.jpg".to_string()));
        // Check that it has many entries
        assert!(gitignore.len() > 15);
    }

    #[test]
    fn test_config_new() {
        let config = Config::new();
        assert_eq!(config.default_folders, default_folders());
        assert_eq!(config.default_gitignore, default_gitignore());
        assert_eq!(config.include_readmes, true);
        assert_eq!(config.normalize_project_names, true);
    }

    #[test]
    fn test_config_default() {
        let config: Config = Default::default();
        assert_eq!(config.default_folders, default_folders());
        assert_eq!(config.default_gitignore, default_gitignore());
        assert_eq!(config.include_readmes, true);
        assert_eq!(config.normalize_project_names, true);
    }

    #[test]
    fn test_set_value() {
        let mut config = Config::new();

        // Test default_artist
        config.set_value("default_artist", "TestArtist").unwrap();
        assert_eq!(config.default_artist, "TestArtist");

        // Test normalize_project_names
        config.set_value("normalize_project_names", "true").unwrap();
        assert_eq!(config.normalize_project_names, true);

        config
            .set_value("normalize_project_names", "false")
            .unwrap();
        assert_eq!(config.normalize_project_names, false);

        // Test invalid boolean
        let result = config.set_value("normalize_project_names", "invalid");
        assert!(result.is_err());

        // Test unknown key
        let result = config.set_value("unknown_key", "value");
        assert!(result.is_err());
    }

    #[test]
    fn test_config_save_and_load() {
        let _guard = ENV_MUTEX.lock().unwrap();

        let temp_dir = TempDir::new().unwrap();
        let original_xdg = std::env::var("XDG_CONFIG_HOME").ok();
        unsafe {
            std::env::set_var("XDG_CONFIG_HOME", temp_dir.path());
        }

        // Create a unique test config
        let mut config = Config::new();
        config.default_artist = "TestArtist".to_string();
        config.save().unwrap();

        // Verify the config file was created in the temp directory
        let config_path = Config::config_path().unwrap();
        assert!(config_path.exists());

        // The path should be under temp_dir/zim/config.toml
        let expected_dir = temp_dir.path().join("zim");
        assert!(config_path.starts_with(&expected_dir));

        let loaded = Config::load().unwrap();
        assert_eq!(loaded.default_artist, "TestArtist");
        assert_eq!(loaded.default_folders, default_folders());

        // Clean up - restore original value if it existed
        unsafe {
            if let Some(original) = original_xdg {
                std::env::set_var("XDG_CONFIG_HOME", original);
            } else {
                std::env::remove_var("XDG_CONFIG_HOME");
            }
        }
    }

    #[test]
    fn test_config_exists() {
        let _guard = ENV_MUTEX.lock().unwrap();

        let temp_dir = TempDir::new().unwrap();
        let original_xdg = std::env::var("XDG_CONFIG_HOME").ok();
        unsafe {
            std::env::set_var("XDG_CONFIG_HOME", temp_dir.path());
        }

        // Verify we're checking in the temp directory
        let expected_path = temp_dir.path().join("zim").join("config.toml");
        assert!(!expected_path.exists());
        assert!(!Config::exists().unwrap());

        let config = Config::new();
        config.save().unwrap();

        assert!(expected_path.exists());
        assert!(Config::exists().unwrap());

        // Clean up - restore original value if it existed
        unsafe {
            if let Some(original) = original_xdg {
                std::env::set_var("XDG_CONFIG_HOME", original);
            } else {
                std::env::remove_var("XDG_CONFIG_HOME");
            }
        }
    }
}