aboutsummaryrefslogtreecommitdiffstats
path: root/crates/client/src/atuin_client/settings/mod.rs
blob: bcec25db23bd448629213fc689fcf11df7584e65 (plain) (blame)
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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
use std::{collections::HashMap, fmt, path::PathBuf, str::FromStr, sync::OnceLock};

use clap::ValueEnum;
use config::{
    Config, ConfigBuilder, Environment, File as ConfigFile, FileFormat, builder::DefaultState,
};
use eyre::{Context, Error, Result, bail, eyre};
use fs_err::create_dir_all;
use regex::RegexSet;
use serde::{Deserialize, Serialize};
use serde_with::DeserializeFromStr;
use time::{UtcOffset, format_description::FormatItem, macros::format_description};
use tracing::info;
use turtle_common::utils;

static DATA_DIR: OnceLock<PathBuf> = OnceLock::new();

#[derive(Clone, Debug, Deserialize, Copy, Serialize)]
pub(crate) enum ExitMode {
    #[serde(rename = "return-original")]
    ReturnOriginal,

    #[serde(rename = "return-query")]
    ReturnQuery,
}

// FIXME: Can use upstream Dialect enum if https://github.com/stevedonovan/chrono-english/pull/16 is merged
// FIXME: Above PR was merged, but dependency was changed to interim (fork of chrono-english) in the ... interim
#[derive(Clone, Debug, Deserialize, Copy, Serialize)]
pub(crate) enum Dialect {
    #[serde(rename = "us")]
    Us,

    #[serde(rename = "uk")]
    Uk,
}

impl From<Dialect> for interim::Dialect {
    fn from(d: Dialect) -> Self {
        match d {
            Dialect::Uk => Self::Uk,
            Dialect::Us => Self::Us,
        }
    }
}

/// Type wrapper around `time::UtcOffset` to support a wider variety of timezone formats.
///
/// Note that the parsing of this struct needs to be done before starting any
/// multithreaded runtime, otherwise it will fail on most Unix systems.
///
/// See: <https://github.com/atuinsh/atuin/pull/1517#discussion_r1447516426>
#[derive(Clone, Copy, Debug, Eq, PartialEq, DeserializeFromStr, Serialize)]
pub(crate) struct Timezone(pub(crate) UtcOffset);
impl fmt::Display for Timezone {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}
/// format: <+|-><hour>[:<minute>[:<second>]]
static OFFSET_FMT: &[FormatItem<'_>] = format_description!(
    "[offset_hour sign:mandatory padding:none][optional [:[offset_minute padding:none][optional [:[offset_second padding:none]]]]]"
);
impl FromStr for Timezone {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self> {
        // local timezone
        if matches!(s.to_lowercase().as_str(), "l" | "local") {
            // There have been some timezone issues, related to errors fetching it on some
            // platforms
            // Rather than fail to start, fallback to UTC. The user should still be able to specify
            // their timezone manually in the config file.
            let offset = UtcOffset::current_local_offset().unwrap_or(UtcOffset::UTC);
            return Ok(Self(offset));
        }

        if matches!(s.to_lowercase().as_str(), "0" | "utc") {
            let offset = UtcOffset::UTC;
            return Ok(Self(offset));
        }

        // offset from UTC
        if let Ok(offset) = UtcOffset::parse(s, OFFSET_FMT) {
            return Ok(Self(offset));
        }

        // IDEA: Currently named timezones are not supported, because the well-known crate
        // for this is `chrono_tz`, which is not really interoperable with the datetime crate
        // that we currently use - `time`. If ever we migrate to using `chrono`, this would
        // be a good feature to add.

        bail!(r#""{s}" is not a valid timezone spec"#)
    }
}

#[derive(Clone, Debug, Deserialize, Copy, Serialize)]
pub(crate) enum Style {
    #[serde(rename = "auto")]
    Auto,

    #[serde(rename = "full")]
    Full,

    #[serde(rename = "compact")]
    Compact,
}

#[derive(Clone, Debug, Deserialize, Copy, Serialize)]
pub(crate) enum WordJumpMode {
    #[serde(rename = "emacs")]
    Emacs,

    #[serde(rename = "subl")]
    Subl,
}

#[derive(Clone, Debug, Deserialize, Copy, PartialEq, Eq, ValueEnum, Serialize)]
pub(crate) enum KeymapMode {
    #[serde(rename = "emacs")]
    Emacs,

    #[serde(rename = "vim-normal")]
    VimNormal,

    #[serde(rename = "vim-insert")]
    VimInsert,

    #[serde(rename = "auto")]
    Auto,
}

// We want to translate the config to crossterm::cursor::SetCursorStyle, but
// the original type does not implement trait serde::Deserialize unfortunately.
// It seems impossible to implement Deserialize for external types when it is
// used in HashMap (https://stackoverflow.com/questions/67142663).  We instead
// define an adapter type.
#[derive(Clone, Debug, Deserialize, Copy, PartialEq, Eq, ValueEnum, Serialize)]
pub(crate) enum CursorStyle {
    #[serde(rename = "default")]
    DefaultUserShape,

    #[serde(rename = "blink-block")]
    BlinkingBlock,

    #[serde(rename = "steady-block")]
    SteadyBlock,

    #[serde(rename = "blink-underline")]
    BlinkingUnderScore,

    #[serde(rename = "steady-underline")]
    SteadyUnderScore,

    #[serde(rename = "blink-bar")]
    BlinkingBar,

    #[serde(rename = "steady-bar")]
    SteadyBar,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub(crate) struct Stats {
    #[serde(default = "Stats::common_prefix_default")]
    pub(crate) common_prefix: Vec<String>, // sudo, etc. commands we want to strip off
    #[serde(default = "Stats::common_subcommands_default")]
    pub(crate) common_subcommands: Vec<String>, // kubectl, commands we should consider subcommands for
    #[serde(default = "Stats::ignored_commands_default")]
    pub(crate) ignored_commands: Vec<String>, // cd, ls, etc. commands we want to completely hide from stats
}

impl Stats {
    fn common_prefix_default() -> Vec<String> {
        vec!["sudo", "doas"].into_iter().map(String::from).collect()
    }

    fn common_subcommands_default() -> Vec<String> {
        vec![
            "apt",
            "cargo",
            "composer",
            "dnf",
            "docker",
            "dotnet",
            "git",
            "go",
            "ip",
            "jj",
            "kubectl",
            "nix",
            "nmcli",
            "npm",
            "pecl",
            "pnpm",
            "podman",
            "port",
            "systemctl",
            "tmux",
            "yarn",
        ]
        .into_iter()
        .map(String::from)
        .collect()
    }

    fn ignored_commands_default() -> Vec<String> {
        vec![]
    }
}

impl Default for Stats {
    fn default() -> Self {
        Self {
            common_prefix: Self::common_prefix_default(),
            common_subcommands: Self::common_subcommands_default(),
            ignored_commands: Self::ignored_commands_default(),
        }
    }
}

#[derive(Clone, Debug, Deserialize, Default, Serialize)]
#[expect(clippy::struct_excessive_bools)]
pub(crate) struct Keys {
    pub(crate) scroll_exits: bool,
    pub(crate) exit_past_line_start: bool,
    pub(crate) accept_past_line_end: bool,
    pub(crate) accept_past_line_start: bool,
    pub(crate) accept_with_backspace: bool,
    pub(crate) prefix: String,
}

impl Keys {
    /// The standard default values for all `[keys]` options.
    /// These match the config defaults set in `builder_with_data_dir()`.
    pub(crate) fn standard_defaults() -> Self {
        Self {
            scroll_exits: true,
            exit_past_line_start: true,
            accept_past_line_end: true,
            accept_past_line_start: false,
            accept_with_backspace: false,
            prefix: "a".to_string(),
        }
    }
}

/// A single rule within a conditional keybinding config.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub(crate) struct KeyRuleConfig {
    /// Optional condition expression (e.g. "cursor-at-start", "input-empty && no-results").
    /// If absent, the rule always matches.
    #[serde(default)]
    pub(crate) when: Option<String>,
    /// The action to perform (e.g. "exit", "cursor-left", "accept").
    pub(crate) action: String,
}

/// A keybinding config value: either a simple action string or an ordered list of conditional rules.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub(crate) enum KeyBindingConfig {
    /// Simple unconditional binding: `"ctrl-c" = "return-original"`
    Simple(String),
    /// Conditional binding: `"left" = [{ when = "cursor-at-start", action = "exit" }, { action = "cursor-left" }]`
    Rules(Vec<KeyRuleConfig>),
}

/// User-facing keymap configuration. Each mode maps key strings to bindings.
/// Keys present here override the defaults for that key; unmentioned keys keep defaults.
#[derive(Clone, Debug, Deserialize, Serialize, Default)]
pub(crate) struct KeymapConfig {
    #[serde(default)]
    pub(crate) emacs: HashMap<String, KeyBindingConfig>,
    #[serde(default, rename = "vim-normal")]
    pub(crate) vim_normal: HashMap<String, KeyBindingConfig>,
    #[serde(default, rename = "vim-insert")]
    pub(crate) vim_insert: HashMap<String, KeyBindingConfig>,
    #[serde(default)]
    pub(crate) inspector: HashMap<String, KeyBindingConfig>,
    #[serde(default)]
    pub(crate) prefix: HashMap<String, KeyBindingConfig>,
}

impl KeymapConfig {
    /// Returns true if no keybinding overrides are configured in any mode.
    pub(crate) fn is_empty(&self) -> bool {
        self.emacs.is_empty()
            && self.vim_normal.is_empty()
            && self.vim_insert.is_empty()
            && self.inspector.is_empty()
            && self.prefix.is_empty()
    }
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub(crate) struct Preview {
    pub(crate) strategy: PreviewStrategy,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub(crate) struct Daemon {
    /// The path to the unix socket used by the daemon
    pub(crate) socket_path: String,

    /// Use a socket passed via systemd's socket activation protocol, instead of the path
    pub(crate) systemd_socket: bool,
}

/// Log level for file logging. Maps to tracing's [`LevelFilter`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub(crate) enum LogLevel {
    Trace,
    Debug,
    #[default]
    Info,
    Warn,
    Error,
}

impl LogLevel {
    /// Convert to a tracing directive string for use with [`EnvFilter`].
    pub(crate) fn as_directive(self) -> &'static str {
        match self {
            Self::Trace => "trace",
            Self::Debug => "debug",
            Self::Info => "info",
            Self::Warn => "warn",
            Self::Error => "error",
        }
    }
}

/// Configuration for a specific log type (search or daemon).
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub(crate) struct LogConfig {
    /// Log file name (relative to dir) or absolute path.
    pub(crate) file: String,

    /// Override global enabled setting for this log type.
    pub(crate) enabled: Option<bool>,

    /// Override global level setting for this log type.
    pub(crate) level: Option<LogLevel>,

    /// Override global retention days setting for this log type.
    pub(crate) retention: Option<u64>,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub(crate) struct Logs {
    /// Enable file logging globally. Defaults to true.
    #[serde(default = "Logs::default_enabled")]
    pub(crate) enabled: bool,

    /// Directory for log files. Defaults to ~/.atuin/logs
    pub(crate) dir: String,

    /// Default log level for file logging. Defaults to "info".
    /// Note: [`ATUIN_LOG`] environment variable overrides this.
    #[serde(default)]
    pub(crate) level: LogLevel,

    /// Default retention days for log files. Defaults to 4.
    #[serde(default = "Logs::default_retention")]
    pub(crate) retention: u64,
}

impl Default for Preview {
    fn default() -> Self {
        Self {
            strategy: PreviewStrategy::Auto,
        }
    }
}

impl Default for Daemon {
    fn default() -> Self {
        Self {
            socket_path: String::new(),
            systemd_socket: false,
        }
    }
}

impl Default for Logs {
    fn default() -> Self {
        Self {
            enabled: true,
            dir: String::new(),
            level: LogLevel::default(),
            retention: Self::default_retention(),
        }
    }
}

impl Logs {
    fn default_enabled() -> bool {
        true
    }

    fn default_retention() -> u64 {
        4
    }
}

// The preview height strategy also takes max_preview_height into account.
#[derive(Clone, Debug, Deserialize, Copy, PartialEq, Eq, ValueEnum, Serialize)]
pub(crate) enum PreviewStrategy {
    // Preview height is calculated for the length of the selected command.
    #[serde(rename = "auto")]
    Auto,

    // Preview height is calculated for the length of the longest command stored in the history.
    #[serde(rename = "static")]
    Static,

    // max_preview_height is used as fixed height.
    #[serde(rename = "fixed")]
    Fixed,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
#[expect(clippy::struct_excessive_bools)]
pub(crate) struct Settings {
    pub(crate) data_dir: Option<String>,
    pub(crate) dialect: Dialect,
    pub(crate) timezone: Timezone,
    pub(crate) style: Style,

    pub(crate) shell_up_key_binding: bool,
    pub(crate) invert: bool,
    pub(crate) show_preview: bool,
    pub(crate) max_preview_height: u16,
    pub(crate) show_help: bool,
    pub(crate) show_tabs: bool,
    pub(crate) show_numeric_shortcuts: bool,
    pub(crate) auto_hide_height: u16,
    pub(crate) exit_mode: ExitMode,
    pub(crate) keymap_mode: KeymapMode,
    pub(crate) keymap_mode_shell: KeymapMode,
    pub(crate) keymap_cursor: HashMap<String, CursorStyle>,
    pub(crate) word_jump_mode: WordJumpMode,
    pub(crate) word_chars: String,
    pub(crate) scroll_context_lines: usize,
    pub(crate) history_format: String,
    pub(crate) strip_trailing_whitespace: bool,
    pub(crate) prefers_reduced_motion: bool,
    pub(crate) store_failed: bool,
    pub(crate) no_mouse: bool,

    #[serde(with = "serde_regex", default = "RegexSet::empty", skip_serializing)]
    pub(crate) history_filter: RegexSet,

    #[serde(with = "serde_regex", default = "RegexSet::empty", skip_serializing)]
    pub(crate) cwd_filter: RegexSet,

    pub(crate) secrets_filter: bool,
    pub(crate) workspaces: bool,
    pub(crate) ctrl_n_shortcuts: bool,

    pub(crate) network_connect_timeout: u64,
    pub(crate) network_timeout: u64,
    pub(crate) local_timeout: f64,
    pub(crate) enter_accept: bool,
    pub(crate) smart_sort: bool,
    pub(crate) command_chaining: bool,

    #[serde(default)]
    pub(crate) stats: Stats,

    #[serde(default)]
    pub(crate) keys: Keys,

    #[serde(default)]
    pub(crate) keymap: KeymapConfig,

    #[serde(default)]
    pub(crate) preview: Preview,

    #[serde(default)]
    pub(crate) daemon: Daemon,

    #[serde(default)]
    pub(crate) logs: Logs,
}

impl Settings {
    pub(crate) fn builder() -> Result<ConfigBuilder<DefaultState>> {
        Self::builder_with_data_dir(&utils::data_dir())
    }

    #[expect(clippy::too_many_lines)]
    fn builder_with_data_dir(data_dir: &std::path::Path) -> Result<ConfigBuilder<DefaultState>> {
        let db_path = data_dir.join("history.db");
        let record_store_path = data_dir.join("records.db");
        let kv_path = data_dir.join("kv.db");
        let scripts_path = data_dir.join("scripts.db");
        let socket_path = utils::runtime_dir().join("atuin.sock");
        let pidfile_path = data_dir.join("atuin-daemon.pid");
        let logs_dir = utils::logs_dir();

        let key_path = data_dir.join("key");

        Ok(Config::builder()
            .set_default("history_format", "{time}\t{command}\t{duration}")?
            .set_default("db_path", db_path.to_str())?
            .set_default("record_store_path", record_store_path.to_str())?
            .set_default("key_path", key_path.to_str())?
            .set_default("dialect", "us")?
            .set_default("timezone", "local")?
            .set_default("auto_sync", true)?
            .set_default("sync.address", "https://api.atuin.sh")?
            .set_default("sync_frequency", "5m")?
            .set_default("search_mode", "fuzzy")?
            .set_default("filter_mode", None::<String>)?
            .set_default("style", "compact")?
            .set_default("inline_height", 40)?
            .set_default("show_preview", true)?
            .set_default("preview.strategy", "auto")?
            .set_default("max_preview_height", 4)?
            .set_default("show_help", true)?
            .set_default("show_tabs", true)?
            .set_default("show_numeric_shortcuts", true)?
            .set_default("auto_hide_height", 8)?
            .set_default("invert", false)?
            .set_default("exit_mode", "return-original")?
            .set_default("word_jump_mode", "emacs")?
            .set_default(
                "word_chars",
                "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
            )?
            .set_default("scroll_context_lines", 1)?
            .set_default("shell_up_key_binding", false)?
            .set_default("workspaces", false)?
            .set_default("ctrl_n_shortcuts", false)?
            .set_default("secrets_filter", true)?
            .set_default("strip_trailing_whitespace", true)?
            .set_default("network_connect_timeout", 5)?
            .set_default("network_timeout", 30)?
            .set_default("local_timeout", 2.0)?
            // enter_accept defaults to false here, but true in the default config file. The dissonance is
            // intentional!
            // Existing users will get the default "False", so we don't mess with any potential
            // muscle memory.
            // New users will get the new default, that is more similar to what they are used to.
            .set_default("enter_accept", false)?
            .set_default("keys.scroll_exits", true)?
            .set_default("keys.accept_past_line_end", true)?
            .set_default("keys.exit_past_line_start", true)?
            .set_default("keys.accept_past_line_start", false)?
            .set_default("keys.accept_with_backspace", false)?
            .set_default("keys.prefix", "a")?
            .set_default("keymap_mode", "emacs")?
            .set_default("keymap_mode_shell", "auto")?
            .set_default("keymap_cursor", HashMap::<String, String>::new())?
            .set_default("smart_sort", false)?
            .set_default("command_chaining", false)?
            .set_default("store_failed", true)?
            .set_default("daemon.sync_frequency", 300)?
            .set_default("daemon.socket_path", socket_path.to_str())?
            .set_default("daemon.pidfile_path", pidfile_path.to_str())?
            .set_default("daemon.systemd_socket", false)?
            .set_default("daemon.tcp_port", 8889)?
            .set_default("logs.enabled", true)?
            .set_default("logs.dir", logs_dir.to_str())?
            .set_default("logs.level", "info")?
            .set_default("logs.search.file", "search.log")?
            .set_default("logs.daemon.file", "daemon.log")?
            .set_default("logs.ai.file", "ai.log")?
            .set_default("kv.db_path", kv_path.to_str())?
            .set_default("scripts.db_path", scripts_path.to_str())?
            .set_default("search.recency_score_multiplier", 1.0)?
            .set_default("search.frequency_score_multiplier", 1.0)?
            .set_default("search.frecency_score_multiplier", 1.0)?
            .set_default("ai.session_continue_minutes", 60)?
            .set_default("ai.send_cwd", false)?
            .set_default("ai.opening.send_cwd", false)?
            .set_default("ai.opening.send_last_command", false)?
            .set_default(
                "search.filters",
                vec![
                    "global",
                    "host",
                    "session",
                    "workspace",
                    "directory",
                    "session-preload",
                ],
            )?
            .set_default("theme.name", "default")?
            .set_default("theme.debug", None::<bool>)?
            .set_default("tmux.enabled", false)?
            .set_default("tmux.width", "80%")?
            .set_default("tmux.height", "60%")?
            .set_default(
                "prefers_reduced_motion",
                std::env::var("NO_MOTION").ok().map_or_else(
                    || config::Value::new(None, config::ValueKind::Boolean(false)),
                    |_| config::Value::new(None, config::ValueKind::Boolean(true)),
                ),
            )?
            .set_default("no_mouse", false)?
            .add_source(
                Environment::with_prefix("atuin")
                    .prefix_separator("_")
                    .separator("__"),
            ))
    }

    pub(crate) fn get_config_path() -> Result<PathBuf> {
        let config_dir = utils::config_dir();

        create_dir_all(&config_dir)
            .wrap_err_with(|| format!("could not create dir {}", config_dir.display()))?;

        let mut config_file = std::env::var("ATUIN_CONFIG_DIR").map_or_else(
            |_| {
                let mut config_file = PathBuf::new();
                config_file.push(config_dir);
                config_file
            },
            PathBuf::from,
        );

        config_file.push("config.toml");

        Ok(config_file)
    }

    /// Build a merged `Config` from defaults, config file, and environment.
    ///
    /// This resolves `data_dir`, initializes the data directory on disk,
    /// and layers defaults → config file → env overrides. Both `new()` and
    /// `get_config_value()` use this so the resolution logic lives in one place.
    fn build_config() -> Result<Config> {
        let config_file = Self::get_config_path()?;

        // extract data_dir first so we can use it as the base for other path defaults
        let effective_data_dir = if config_file.exists() {
            #[derive(Deserialize, Default)]
            struct DataDirOnly {
                data_dir: Option<String>,
            }

            let config_file_str = config_file
                .to_str()
                .ok_or_else(|| eyre!("config file path is not valid UTF-8"))?;

            let partial_config = Config::builder()
                .add_source(ConfigFile::new(config_file_str, FileFormat::Toml))
                .add_source(
                    Environment::with_prefix("atuin")
                        .prefix_separator("_")
                        .separator("__"),
                )
                .build()
                .ok();

            let custom_data_dir = partial_config
                .and_then(|c| c.try_deserialize::<DataDirOnly>().ok())
                .and_then(|d| d.data_dir);

            match custom_data_dir {
                Some(dir) => {
                    let expanded = shellexpand::full(&dir)
                        .map_err(|e| eyre!("failed to expand data_dir path: {}", e))?;
                    PathBuf::from(expanded.as_ref())
                }
                None => utils::data_dir(),
            }
        } else {
            utils::data_dir()
        };

        DATA_DIR.set(effective_data_dir.clone()).ok();

        create_dir_all(&effective_data_dir)
            .wrap_err_with(|| format!("could not create dir {}", effective_data_dir.display()))?;

        let mut config_builder = Self::builder_with_data_dir(&effective_data_dir)?;

        config_builder = if config_file.exists() {
            let config_file_str = config_file
                .to_str()
                .ok_or_else(|| eyre!("config file path is not valid UTF-8"))?;
            config_builder.add_source(ConfigFile::new(config_file_str, FileFormat::Toml))
        } else {
            // TODO(@bpeetz): Rework the config handling, so that we can actually auto-write a
            // file with defaults. <2026-06-13>
            create_dir_all(config_file.parent().unwrap())?;

            info!(
                "No config file at: `{}`. Not adding one.",
                config_file.display()
            );

            config_builder
        };

        // all paths should be expanded
        let built = config_builder.build_cloned()?;
        config_builder = [
            "db_path",
            "record_store_path",
            "key_path",
            "daemon.socket_path",
            "daemon.pidfile_path",
            "logs.dir",
            "logs.search.file",
            "logs.daemon.file",
        ]
        .iter()
        .map(|key| (key, built.get_string(key).unwrap_or_default()))
        .filter_map(|(key, value)| match Self::expand_path(&value) {
            Ok(expanded) => Some((key, expanded)),
            Err(e) => {
                log::warn!("failed to expand path for {key}: {e}");
                None
            }
        })
        .fold(config_builder, |builder, (key, value)| {
            builder
                .set_override(key, value)
                .unwrap_or_else(|_| panic!("failed to set absolute path override for {key}"))
        });

        config_builder.build().map_err(Into::into)
    }

    /// Look up a single config value by dotted key (e.g. `"daemon.sync_frequency"`).
    ///
    /// Returns the effective value after merging defaults, config file, and
    /// environment — without the side-effects of full `Settings` construction
    /// (meta store init, path expansion, etc.).
    pub(crate) fn get_config_value(key: &str) -> Result<String> {
        let config = Self::build_config()?;
        let value: config::Value = config
            .get(key)
            .map_err(|e| eyre!("failed to get config value '{}': {}", key, e))?;
        Ok(Self::format_resolved_value(&value, key))
    }

    fn format_resolved_value(value: &config::Value, prefix: &str) -> String {
        use config::ValueKind;

        match &value.kind {
            ValueKind::Nil => String::new(),
            ValueKind::Boolean(b) => b.to_string(),
            ValueKind::I64(i) => i.to_string(),
            ValueKind::I128(i) => i.to_string(),
            ValueKind::U64(u) => u.to_string(),
            ValueKind::U128(u) => u.to_string(),
            ValueKind::Float(f) => f.to_string(),
            ValueKind::String(s) => s.clone(),
            ValueKind::Array(arr) => {
                let items: Vec<String> = arr
                    .iter()
                    .map(|v| Self::format_resolved_value(v, ""))
                    .collect();
                format!("[{}]", items.join(", "))
            }
            ValueKind::Table(map) => {
                let mut lines = Vec::new();
                let mut keys: Vec<_> = map.keys().collect();
                keys.sort();

                for k in keys {
                    let v = &map[k];
                    let full_key = if prefix.is_empty() {
                        k.clone()
                    } else {
                        format!("{prefix}.{k}")
                    };

                    match &v.kind {
                        ValueKind::Table(_) => {
                            lines.push(Self::format_resolved_value(v, &full_key));
                        }
                        _ => {
                            lines.push(format!(
                                "{} = {}",
                                full_key,
                                Self::format_resolved_value(v, "")
                            ));
                        }
                    }
                }

                lines.join("\n")
            }
        }
    }

    pub(crate) fn new() -> Result<Self> {
        let config = Self::build_config()?;
        let settings: Self = config
            .try_deserialize()
            .map_err(|e| eyre!("failed to deserialize: {}", e))?;

        Ok(settings)
    }

    fn expand_path(path: &str) -> Result<String> {
        shellexpand::full(&path)
            .map(|p| p.to_string())
            .map_err(|e| eyre!("failed to expand path: {}", e))
    }
}

impl Default for Settings {
    fn default() -> Self {
        // if this panics something is very wrong, as the default config
        // does not build or deserialize into the settings struct
        Self::builder()
            .expect("Could not build default")
            .build()
            .expect("Could not build config")
            .try_deserialize()
            .expect("Could not deserialize config")
    }
}

#[cfg(test)]
pub(crate) fn test_local_timeout() -> f64 {
    std::env::var("ATUIN_TEST_LOCAL_TIMEOUT")
        .ok()
        .and_then(|x| x.parse().ok())
        // this hardcoded value should be replaced by a simple way to get the
        // default local_timeout of Settings if possible
        .unwrap_or(2.0)
}

#[cfg(test)]
mod tests {
    use std::str::FromStr;

    use eyre::Result;

    use super::Timezone;

    #[test]
    fn can_parse_offset_timezone_spec() -> Result<()> {
        assert_eq!(Timezone::from_str("+02")?.0.as_hms(), (2, 0, 0));
        assert_eq!(Timezone::from_str("-04")?.0.as_hms(), (-4, 0, 0));
        assert_eq!(Timezone::from_str("+05:30")?.0.as_hms(), (5, 30, 0));
        assert_eq!(Timezone::from_str("-09:30")?.0.as_hms(), (-9, -30, 0));

        // single digit hours are allowed
        assert_eq!(Timezone::from_str("+2")?.0.as_hms(), (2, 0, 0));
        assert_eq!(Timezone::from_str("-4")?.0.as_hms(), (-4, 0, 0));
        assert_eq!(Timezone::from_str("+5:30")?.0.as_hms(), (5, 30, 0));
        assert_eq!(Timezone::from_str("-9:30")?.0.as_hms(), (-9, -30, 0));

        // fully qualified form
        assert_eq!(Timezone::from_str("+09:30:00")?.0.as_hms(), (9, 30, 0));
        assert_eq!(Timezone::from_str("-09:30:00")?.0.as_hms(), (-9, -30, 0));

        // these offsets don't really exist but are supported anyway
        assert_eq!(Timezone::from_str("+0:5")?.0.as_hms(), (0, 5, 0));
        assert_eq!(Timezone::from_str("-0:5")?.0.as_hms(), (0, -5, 0));
        assert_eq!(Timezone::from_str("+01:23:45")?.0.as_hms(), (1, 23, 45));
        assert_eq!(Timezone::from_str("-01:23:45")?.0.as_hms(), (-1, -23, -45));

        // require a leading sign for clarity
        assert!(Timezone::from_str("5").is_err());
        assert!(Timezone::from_str("10:30").is_err());

        Ok(())
    }

    #[test]
    fn builder_with_data_dir_uses_custom_paths() -> Result<()> {
        use std::path::PathBuf;

        let custom_dir = PathBuf::from("/custom/data/dir");
        let builder = super::Settings::builder_with_data_dir(&custom_dir)?;
        let config = builder.build()?;

        let db_path: String = config.get("db_path")?;
        let key_path: String = config.get("key_path")?;
        let record_store_path: String = config.get("record_store_path")?;
        let kv_db_path: String = config.get("kv.db_path")?;
        let scripts_db_path: String = config.get("scripts.db_path")?;
        let daemon_socket_path: String = config.get("daemon.socket_path")?;
        let daemon_pidfile_path: String = config.get("daemon.pidfile_path")?;

        assert_eq!(db_path, custom_dir.join("history.db").to_str().unwrap());
        assert_eq!(key_path, custom_dir.join("key").to_str().unwrap());
        assert_eq!(
            record_store_path,
            custom_dir.join("records.db").to_str().unwrap()
        );
        assert_eq!(kv_db_path, custom_dir.join("kv.db").to_str().unwrap());
        assert_eq!(
            scripts_db_path,
            custom_dir.join("scripts.db").to_str().unwrap()
        );
        assert_eq!(
            daemon_socket_path,
            turtle_common::utils::runtime_dir()
                .join("atuin.sock")
                .to_str()
                .unwrap()
        );
        assert_eq!(
            daemon_pidfile_path,
            custom_dir.join("atuin-daemon.pid").to_str().unwrap()
        );

        Ok(())
    }

    #[test]
    fn keymap_config_deserializes_simple_binding() {
        let json = r#"{"emacs": {"ctrl-c": "exit"}}"#;
        let config: super::KeymapConfig = serde_json::from_str(json).unwrap();
        assert_eq!(config.emacs.len(), 1);
        match &config.emacs["ctrl-c"] {
            super::KeyBindingConfig::Simple(s) => assert_eq!(s, "exit"),
            _ => panic!("expected Simple variant"),
        }
    }

    #[test]
    fn keymap_config_deserializes_conditional_binding() {
        let json = r#"{
            "emacs": {
                "left": [
                    {"when": "cursor-at-start", "action": "exit"},
                    {"action": "cursor-left"}
                ]
            }
        }"#;
        let config: super::KeymapConfig = serde_json::from_str(json).unwrap();
        match &config.emacs["left"] {
            super::KeyBindingConfig::Rules(rules) => {
                assert_eq!(rules.len(), 2);
                assert_eq!(rules[0].when.as_deref(), Some("cursor-at-start"));
                assert_eq!(rules[0].action, "exit");
                assert!(rules[1].when.is_none());
                assert_eq!(rules[1].action, "cursor-left");
            }
            _ => panic!("expected Rules variant"),
        }
    }

    #[test]
    fn keymap_config_deserializes_vim_normal() {
        let json = r#"{"vim-normal": {"j": "select-next", "k": "select-previous"}}"#;
        let config: super::KeymapConfig = serde_json::from_str(json).unwrap();
        assert_eq!(config.vim_normal.len(), 2);
        assert!(config.emacs.is_empty());
    }

    #[test]
    fn keymap_config_is_empty_when_default() {
        let config = super::KeymapConfig::default();
        assert!(config.is_empty());
    }

    #[test]
    fn keymap_config_mixed_modes() {
        let json = r#"{
            "emacs": {"ctrl-c": "exit"},
            "vim-normal": {"q": "exit"},
            "inspector": {"d": "delete"}
        }"#;
        let config: super::KeymapConfig = serde_json::from_str(json).unwrap();
        assert!(!config.is_empty());
        assert_eq!(config.emacs.len(), 1);
        assert_eq!(config.vim_normal.len(), 1);
        assert_eq!(config.inspector.len(), 1);
        assert!(config.vim_insert.is_empty());
        assert!(config.prefix.is_empty());
    }
}