rustledger 0.12.0

Drop-in replacement for Beancount. Pure Rust, 10-30x faster.
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
//! rledger config - Configuration management commands.
//!
//! Provides subcommands for viewing and managing rledger configuration:
//!
//! - `rledger config show` - Show merged configuration
//! - `rledger config path` - Show config file search paths
//! - `rledger config edit` - Open config file in editor
//! - `rledger config init` - Generate a default config file

use crate::config::{self, Config, LoadedConfig};
use anyhow::{Context, Result, bail};
use clap::{Parser, Subcommand};
use std::fs;
use std::io::{self, Write};

/// Configuration management commands.
#[derive(Parser, Debug)]
#[command(name = "config")]
pub struct Args {
    /// Config subcommand to run.
    #[command(subcommand)]
    pub command: ConfigCommand,
}

/// Config subcommands.
#[derive(Subcommand, Debug)]
pub enum ConfigCommand {
    /// Show the merged configuration from all sources.
    Show {
        /// Show raw configs without merging (one per source).
        #[arg(long)]
        raw: bool,

        /// Output format (toml, json).
        #[arg(long, short, default_value = "toml")]
        format: String,
    },

    /// Show config file search paths.
    Path,

    /// Open config file in editor.
    Edit {
        /// Edit project config instead of user config.
        #[arg(long, conflicts_with = "system")]
        project: bool,

        /// Edit system config instead of user config.
        #[arg(long, conflicts_with = "project")]
        system: bool,
    },

    /// Generate a default config file.
    Init {
        /// Create project config (.rledger.toml) instead of user config.
        #[arg(long)]
        project: bool,

        /// Overwrite existing config file.
        #[arg(long, short)]
        force: bool,
    },

    /// List configured aliases.
    Aliases,
}

/// Run the config command.
pub fn run(args: &Args) -> Result<()> {
    match &args.command {
        ConfigCommand::Show { raw, format } => run_show(*raw, format),
        ConfigCommand::Path => run_path(),
        ConfigCommand::Edit { project, system } => run_edit(*project, *system),
        ConfigCommand::Init { project, force } => run_init(*project, *force),
        ConfigCommand::Aliases => run_aliases(),
    }
}

/// Show merged configuration.
fn run_show(raw: bool, format: &str) -> Result<()> {
    let loaded = Config::load()?;

    if raw {
        // Show each config source separately, highest precedence first
        println!("# Configuration sources (highest precedence first)\n");

        for source in loaded.sources.iter().rev() {
            match source {
                config::ConfigSource::Project(path)
                | config::ConfigSource::User(path)
                | config::ConfigSource::System(path) => {
                    println!("# === {source} ===");
                    if let Ok(content) = fs::read_to_string(path) {
                        println!("{content}");
                    }
                    println!();
                }
                config::ConfigSource::Environment => {
                    println!("# === Environment Variables ===");
                    if let Ok(file) = std::env::var("RLEDGER_FILE") {
                        println!("RLEDGER_FILE={file}");
                    }
                    if let Ok(format) = std::env::var("RLEDGER_FORMAT") {
                        println!("RLEDGER_FORMAT={format}");
                    }
                    if std::env::var("NO_COLOR").is_ok() {
                        println!("NO_COLOR=1");
                    }
                    if let Ok(profile) = std::env::var("RLEDGER_PROFILE") {
                        println!("RLEDGER_PROFILE={profile}");
                    }
                    println!();
                }
                _ => {}
            }
        }
    } else {
        // Show merged config
        print_config(&loaded, format)?;
    }

    Ok(())
}

/// Print configuration in the specified format.
fn print_config(loaded: &LoadedConfig, format: &str) -> Result<()> {
    let mut stdout = io::stdout().lock();

    match format {
        "toml" => {
            writeln!(stdout, "# Merged configuration (highest priority wins)")?;
            writeln!(stdout, "# Sources: {}", format_sources(&loaded.sources))?;
            writeln!(stdout)?;

            let toml_str = toml::to_string_pretty(&loaded.config)
                .context("Failed to serialize config to TOML")?;
            writeln!(stdout, "{toml_str}")?;
        }
        "json" => {
            let json_str = serde_json::to_string_pretty(&loaded.config)
                .context("Failed to serialize config to JSON")?;
            writeln!(stdout, "{json_str}")?;
        }
        _ => {
            bail!("Unknown format: {format}. Supported: toml, json");
        }
    }

    Ok(())
}

/// Format source list for display (highest precedence first).
fn format_sources(sources: &[config::ConfigSource]) -> String {
    if sources.is_empty() {
        "default".to_string()
    } else {
        sources
            .iter()
            .rev() // Reverse to show highest precedence first
            .map(|s| match s {
                config::ConfigSource::Cli => "cli".to_string(),
                config::ConfigSource::Environment => "env".to_string(),
                config::ConfigSource::Project(_) => "project".to_string(),
                config::ConfigSource::User(_) => "user".to_string(),
                config::ConfigSource::System(_) => "system".to_string(),
                config::ConfigSource::Default => "default".to_string(),
            })
            .collect::<Vec<_>>()
            .join(" > ")
    }
}

/// Show config file search paths.
fn run_path() -> Result<()> {
    let paths = config::config_search_paths();

    println!("Configuration file search paths:\n");

    for (level, path, exists) in paths {
        let status = if exists { "(found)" } else { "(not found)" };
        println!("  {level:8} {status:12} {}", path.display());
    }

    println!();
    println!("Environment variables:");
    println!("  RLEDGER_FILE     Default beancount file");
    println!("  RLEDGER_FORMAT   Output format (text, csv, json)");
    println!("  RLEDGER_PROFILE  Active profile name");
    println!("  NO_COLOR         Disable colored output");

    Ok(())
}

/// Open config file in editor.
fn run_edit(project: bool, system: bool) -> Result<()> {
    let path = if system {
        config::system_config_path().context("System config path not available on this platform")?
    } else if project {
        std::env::current_dir()?.join(".rledger.toml")
    } else {
        config::user_config_path().context("User config path not available")?
    };

    // Ensure parent directory exists for user config
    if !project
        && !system
        && let Some(parent) = path.parent()
        && !parent.exists()
    {
        fs::create_dir_all(parent)
            .with_context(|| format!("Failed to create directory: {}", parent.display()))?;
    }

    // Create file with default content if it doesn't exist
    if !path.exists() {
        fs::write(&path, Config::default_config_content())
            .with_context(|| format!("Failed to create config file: {}", path.display()))?;
        println!("Created new config file: {}", path.display());
    }

    // Check if user has a custom editor configured (treat empty/whitespace as unset)
    let custom_editor = Config::load()
        .ok()
        .and_then(|l| l.config.default.editor)
        .and_then(|e| {
            let trimmed = e.trim();
            if trimmed.is_empty() { None } else { Some(e) }
        });

    println!("Opening {}...", path.display());

    if let Some(editor) = custom_editor {
        // User has a custom editor configured - use Command directly
        // Use shell_words to properly parse quoted paths/args (e.g., "C:\Program Files\..." or 'code --wait')
        let parts = shell_words::split(&editor)
            .with_context(|| format!("Invalid editor command syntax: {editor}"))?;

        let (cmd, args) = parts.split_first().context("Editor command is empty")?;

        let status = std::process::Command::new(cmd)
            .args(args)
            .arg(&path)
            .status()
            .with_context(|| format!("Failed to run editor: {editor}"))?;

        if !status.success() {
            match status.code() {
                Some(code) => bail!("Editor exited with error (exit code {code})"),
                None => bail!("Editor terminated by signal"),
            }
        }
    } else {
        // No custom editor - use the `edit` crate for cross-platform auto-detection
        // It handles: VISUAL/EDITOR env vars, platform-specific fallbacks (notepad on Windows),
        // proper PATH/PATHEXT handling, and waiting for the editor to close
        edit::edit_file(&path).with_context(|| {
            "Failed to open editor. Set the EDITOR environment variable or configure \
             'default.editor' in your config file."
        })?;
    }

    Ok(())
}

/// Generate a default config file.
fn run_init(project: bool, force: bool) -> Result<()> {
    let path = if project {
        std::env::current_dir()?.join(".rledger.toml")
    } else {
        config::user_config_path().context("User config path not available")?
    };

    // Check if file exists
    if path.exists() && !force {
        bail!(
            "Config file already exists: {}\nUse --force to overwrite",
            path.display()
        );
    }

    // Create parent directory if needed
    if let Some(parent) = path.parent()
        && !parent.exists()
    {
        fs::create_dir_all(parent)
            .with_context(|| format!("Failed to create directory: {}", parent.display()))?;
    }

    // Write default config
    fs::write(&path, Config::default_config_content())
        .with_context(|| format!("Failed to write config file: {}", path.display()))?;

    println!("Created config file: {}", path.display());
    println!();
    println!("Edit this file to set your default beancount file:");
    println!(
        "  rledger config edit{}",
        if project { " --project" } else { "" }
    );

    Ok(())
}

/// List configured aliases.
fn run_aliases() -> Result<()> {
    let loaded = Config::load()?;

    if loaded.config.aliases.is_empty() {
        println!("No aliases configured.");
        println!();
        println!("Add aliases to your config file:");
        println!("  [aliases]");
        println!("  bal = \"report balances\"");
        println!("  inc = \"report income\"");
        return Ok(());
    }

    println!("Configured aliases:\n");

    // Sort aliases by name for consistent output
    let mut aliases: Vec<_> = loaded.config.aliases.iter().collect();
    aliases.sort_by_key(|(name, _)| *name);

    for (name, expansion) in aliases {
        println!("  {name} = \"{expansion}\"");
    }

    println!();
    println!("Usage: rledger <alias> [additional args]");

    Ok(())
}

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

    #[test]
    fn test_format_sources() {
        // Sources are stored in load order (lowest to highest precedence)
        let sources = vec![
            config::ConfigSource::User("/home/user/.config/rledger/config.toml".into()),
            config::ConfigSource::Project("/test/.rledger.toml".into()),
        ];

        // format_sources reverses to show highest precedence first
        let formatted = format_sources(&sources);
        assert_eq!(formatted, "project > user");
    }

    #[test]
    fn test_format_sources_empty() {
        let sources = vec![];
        let formatted = format_sources(&sources);
        assert_eq!(formatted, "default");
    }

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

        // Manually create config since run_init uses fixed paths
        fs::write(&config_path, Config::default_config_content()).unwrap();

        assert!(config_path.exists());
        let content = fs::read_to_string(&config_path).unwrap();
        assert!(content.contains("[default]"));
        assert!(content.contains("# file ="));
    }

    #[test]
    fn test_format_sources_all_types() {
        // Sources in load order (lowest to highest precedence)
        let sources = vec![
            config::ConfigSource::System("/etc/rledger/config.toml".into()),
            config::ConfigSource::User("/home/user/.config/rledger/config.toml".into()),
            config::ConfigSource::Project("/project/.rledger.toml".into()),
            config::ConfigSource::Environment,
        ];

        let formatted = format_sources(&sources);
        // Should be reversed to show highest precedence first
        assert_eq!(formatted, "env > project > user > system");
    }

    #[test]
    fn test_format_sources_cli() {
        let sources = vec![config::ConfigSource::Cli];
        let formatted = format_sources(&sources);
        assert_eq!(formatted, "cli");
    }

    #[test]
    fn test_format_sources_default() {
        let sources = vec![config::ConfigSource::Default];
        let formatted = format_sources(&sources);
        assert_eq!(formatted, "default");
    }

    #[test]
    fn test_config_command_parsing() {
        use clap::Parser;

        // Test show command
        let args = Args::try_parse_from(["config", "show"]).unwrap();
        assert!(matches!(
            args.command,
            ConfigCommand::Show { raw: false, .. }
        ));

        // Test show --raw
        let args = Args::try_parse_from(["config", "show", "--raw"]).unwrap();
        assert!(matches!(
            args.command,
            ConfigCommand::Show { raw: true, .. }
        ));

        // Test show --format json
        let args = Args::try_parse_from(["config", "show", "--format", "json"]).unwrap();
        if let ConfigCommand::Show { format, .. } = args.command {
            assert_eq!(format, "json");
        }

        // Test path command
        let args = Args::try_parse_from(["config", "path"]).unwrap();
        assert!(matches!(args.command, ConfigCommand::Path));

        // Test edit command
        let args = Args::try_parse_from(["config", "edit"]).unwrap();
        assert!(matches!(
            args.command,
            ConfigCommand::Edit {
                project: false,
                system: false
            }
        ));

        // Test edit --project
        let args = Args::try_parse_from(["config", "edit", "--project"]).unwrap();
        assert!(matches!(
            args.command,
            ConfigCommand::Edit {
                project: true,
                system: false
            }
        ));

        // Test edit --system
        let args = Args::try_parse_from(["config", "edit", "--system"]).unwrap();
        assert!(matches!(
            args.command,
            ConfigCommand::Edit {
                project: false,
                system: true
            }
        ));

        // Test init command
        let args = Args::try_parse_from(["config", "init"]).unwrap();
        assert!(matches!(
            args.command,
            ConfigCommand::Init {
                project: false,
                force: false
            }
        ));

        // Test init --project
        let args = Args::try_parse_from(["config", "init", "--project"]).unwrap();
        assert!(matches!(
            args.command,
            ConfigCommand::Init {
                project: true,
                force: false
            }
        ));

        // Test init --force
        let args = Args::try_parse_from(["config", "init", "--force"]).unwrap();
        assert!(matches!(
            args.command,
            ConfigCommand::Init {
                project: false,
                force: true
            }
        ));

        // Test aliases command
        let args = Args::try_parse_from(["config", "aliases"]).unwrap();
        assert!(matches!(args.command, ConfigCommand::Aliases));
    }

    #[test]
    fn test_edit_conflicts_with() {
        use clap::Parser;

        // --project and --system should conflict
        let result = Args::try_parse_from(["config", "edit", "--project", "--system"]);
        assert!(result.is_err());
    }

    #[test]
    fn test_default_config_content_is_valid_toml() {
        let content = Config::default_config_content();
        // Should parse as valid TOML (comments are allowed)
        let result: Result<Config, _> = toml::from_str(&content);
        assert!(result.is_ok());
    }

    #[test]
    fn test_config_show_format_options() {
        // Just verify the format parameter exists and accepts expected values
        use clap::Parser;

        let args = Args::try_parse_from(["config", "show", "-f", "toml"]).unwrap();
        if let ConfigCommand::Show { format, .. } = args.command {
            assert_eq!(format, "toml");
        }

        let args = Args::try_parse_from(["config", "show", "-f", "json"]).unwrap();
        if let ConfigCommand::Show { format, .. } = args.command {
            assert_eq!(format, "json");
        }
    }

    #[test]
    fn test_editor_command_parsing() {
        // Simple command
        let parts = shell_words::split("vim").unwrap();
        assert_eq!(parts, vec!["vim"]);

        // Command with args
        let parts = shell_words::split("code --wait").unwrap();
        assert_eq!(parts, vec!["code", "--wait"]);

        // Quoted path with spaces (Windows-style)
        let parts =
            shell_words::split(r#""C:\Program Files\Notepad++\notepad++.exe" -multiInst"#).unwrap();
        assert_eq!(
            parts,
            vec![r"C:\Program Files\Notepad++\notepad++.exe", "-multiInst"]
        );

        // Single-quoted path
        let parts = shell_words::split("'/usr/bin/my editor' --wait").unwrap();
        assert_eq!(parts, vec!["/usr/bin/my editor", "--wait"]);
    }

    #[test]
    fn test_editor_empty_handling() {
        // Empty string should result in None from our filter
        let editor: Option<String> = Some(String::new());
        let filtered = editor.and_then(|e| {
            let trimmed = e.trim();
            if trimmed.is_empty() { None } else { Some(e) }
        });
        assert!(filtered.is_none());

        // Whitespace-only should also result in None
        let editor: Option<String> = Some(String::from("   "));
        let filtered = editor.and_then(|e| {
            let trimmed = e.trim();
            if trimmed.is_empty() { None } else { Some(e) }
        });
        assert!(filtered.is_none());

        // Non-empty should pass through
        let editor: Option<String> = Some(String::from("vim"));
        let filtered = editor.and_then(|e| {
            let trimmed = e.trim();
            if trimmed.is_empty() { None } else { Some(e) }
        });
        assert_eq!(filtered, Some(String::from("vim")));
    }
}