confy 2.0.0

Boilerplate-free configuration management
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
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
//! Zero-boilerplate configuration management
//!
//! ## Why?
//!
//! There are a lot of different requirements when
//! selecting, loading and writing a config,
//! depending on the operating system and other
//! environment factors.
//!
//! In many applications this burden is left to you,
//! the developer of an application, to figure out
//! where to place the configuration files.
//!
//! This is where `confy` comes in.
//!
//! ## Idea
//!
//! `confy` takes care of figuring out operating system
//! specific and environment paths before reading and
//! writing a configuration.
//!
//! It gives you easy access to a configuration file
//! which is mirrored into a Rust `struct` via [serde].
//! This way you only need to worry about the layout of
//! your configuration, not where and how to store it.
//!
//! [serde]: https://docs.rs/serde
//!
//! `confy` uses the [`Default`] trait in Rust to automatically
//! create a new configuration, if none is available to read
//! from yet.
//! This means that you can simply assume your application
//! to have a configuration, which will be created with
//! default values of your choosing, without requiring
//! any special logic to handle creation.
//!
//! [`Default`]: https://doc.rust-lang.org/std/default/trait.Default.html
//!
//! ```rust,no_run
//! use serde_derive::{Serialize, Deserialize};
//!
//! #[derive(Serialize, Deserialize)]
//! struct MyConfig {
//!     version: u8,
//!     api_key: String,
//! }
//!
//! /// `MyConfig` implements `Default`
//! impl ::std::default::Default for MyConfig {
//!     fn default() -> Self { Self { version: 0, api_key: "".into() } }
//! }
//!
//! fn main() -> Result<(), confy::ConfyError> {
//!     let cfg: MyConfig = confy::load("my-app-name", None)?;
//!     Ok(())
//! }
//! ```
//!
//! Serde is a required dependency, and can be added with either the `serde_derive` crate or `serde` crate with feature derive as shown below
//!```toml,no_run
//![dependencies]
//!serde = { version = "1.0.152", features = ["derive"] } # <- Only one serde version needed (serde or serde_derive)
//!serde_derive = "1.0.152" # <- Only one serde version needed (serde or serde_derive)
//!confy = "^0.6"
//!```
//! Updating the configuration is then done via the [`store`] function.
//!
//! [`store`]: fn.store.html
//!
//! ## Features
//!
//! Exactly **one** of the features has to be enabled from the following table.
//!
//! ### Tip
//! to add this crate to your project with the default, toml config do the following: `cargo add confy`, otherwise do something like: `cargo add confy --no-default-features --features yaml_conf`, for more info, see [cargo docs on features]
//!
//! [cargo docs on features]: https://docs.rust-lang.org/cargo/reference/resolver.html#features
//!
//! feature | file format | description
//! ------- | ----------- | -----------
//! **default**: `toml_conf` | [toml] | considered a reasonable default, uses the standard-compliant [`toml` crate]
//! `yaml_conf` | [yaml] | uses the [`serde_yaml` crate]
//! `ron_conf` | [ron] | Rusty Object Notation, uses the [`ron` crate]
//! `basic_toml_conf` | [toml] | alternative to the default `toml_conf`, instead of using the [`toml` crate], the [`basic_toml` crate] is used, in order to cut down on the number of dependencies, speed up compilation and shrink binary size. **_DISCLAIMER_**: this crate is **not** standard compliant, **nor** maintained, otherwise should work fine in most situations.
//!
//! [toml]: https://toml.io
//! [`toml` crate]: https://docs.rs/toml
//! [yaml]: https://yaml.org
//! [`serde_yaml` crate]: https://docs.rs/serde_yaml
//! [ron]: https://docs.rs/ron
//! [`ron` crate]: https://docs.rs/ron
//! [`basic_toml` crate]: https://docs.rs/basic_toml

mod utils;
use etcetera::app_strategy;
use utils::*;

use etcetera::{
    AppStrategy, AppStrategyArgs, app_strategy::choose_app_strategy,
    app_strategy::choose_native_strategy,
};
use lazy_static::lazy_static;
use serde::{Serialize, de::DeserializeOwned};
use std::fs::{self, File, OpenOptions, Permissions};
use std::io::{ErrorKind::NotFound, Write};
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use thiserror::Error;

#[cfg(feature = "toml_conf")]
use toml::{
    de::Error as TomlDeErr, from_str as toml_from_str, ser::Error as TomlSerErr,
    to_string_pretty as toml_to_string_pretty,
};

#[cfg(feature = "basic_toml_conf")]
use basic_toml::{
    Error as TomlDeErr, Error as TomlSerErr, from_str as toml_from_str,
    to_string as toml_to_string_pretty,
};

#[cfg(not(any(
    feature = "toml_conf",
    feature = "basic_toml_conf",
    feature = "yaml_conf",
    feature = "ron_conf"
)))]
compile_error!(
    "Exactly one config language feature must be enabled to use \
confy. Please enable one of either the `toml_conf`, `yaml_conf`, \
, `ron_conf` or `toml_basic_conf` features."
);

#[cfg(any(
    all(feature = "toml_conf", feature = "basic_toml_conf"),
    all(
        any(feature = "toml_conf", feature = "basic_toml_conf"),
        feature = "yaml_conf"
    ),
    all(
        any(feature = "toml_conf", feature = "basic_toml_conf"),
        feature = "ron_conf"
    ),
    all(feature = "ron_conf", feature = "yaml_conf"),
))]
compile_error!(
    "Exactly one config language feature must be enabled to compile \
confy.  Please disable one of either the `toml_conf`, `basic_toml_conf`, `yaml_conf`, or `ron_conf` features. \
NOTE: `toml_conf` is a default feature, so disabling it might mean switching off \
default features for confy in your Cargo.toml"
);

#[cfg(any(feature = "toml_conf", feature = "basic_toml_conf"))]
const EXTENSION: &str = "toml";

#[cfg(feature = "yaml_conf")]
const EXTENSION: &str = "yml";

#[cfg(feature = "ron_conf")]
const EXTENSION: &str = "ron";

lazy_static! {
    static ref STRATEGY: Mutex<ConfigStrategy> = Mutex::new(ConfigStrategy::App);
}

/// The errors the confy crate can encounter.
#[derive(Debug, Error)]
pub enum ConfyError {
    #[cfg(any(feature = "toml_conf", feature = "basic_toml_conf"))]
    #[error("Bad TOML data")]
    BadTomlData(#[source] TomlDeErr),

    #[cfg(feature = "yaml_conf")]
    #[error("Bad YAML data")]
    BadYamlData(#[source] serde_yaml::Error),

    #[cfg(feature = "ron_conf")]
    #[error("Bad RON data")]
    BadRonData(#[source] ron::error::SpannedError),

    #[error("Failed to create directory")]
    DirectoryCreationFailed(#[source] std::io::Error),

    #[error("Failed to load configuration file")]
    GeneralLoadError(#[source] std::io::Error),

    #[error("Bad configuration directory: {0}")]
    BadConfigDirectory(String),

    #[cfg(any(feature = "toml_conf", feature = "basic_toml_conf"))]
    #[error("Failed to serialize configuration data into TOML")]
    SerializeTomlError(#[source] TomlSerErr),

    #[cfg(feature = "yaml_conf")]
    #[error("Failed to serialize configuration data into YAML")]
    SerializeYamlError(#[source] serde_yaml::Error),

    #[cfg(feature = "ron_conf")]
    #[error("Failed to serialize configuration data into RON")]
    SerializeRonError(#[source] ron::error::Error),

    #[error("Failed to write configuration file")]
    WriteConfigurationFileError(#[source] std::io::Error),

    #[error("Failed to read configuration file")]
    ReadConfigurationFileError(#[source] std::io::Error),

    #[error("Failed to open configuration file")]
    OpenConfigurationFileError(#[source] std::io::Error),

    #[error("Failed to set configuration file permissions")]
    SetPermissionsFileError(#[source] std::io::Error),
}

/// Determine what strategy `confy` should use
/// these are based off of [the etcetera crate's strategies](https://docs.rs/etcetera/latest/etcetera/#strategies).
///
/// To change use [`change_config_strategy`] function before calling any load or save functions.
pub enum ConfigStrategy {
    /// The `App` Strategy is the default strategy
    /// this is the traditional XDG strategy and will place the config file in the XDG directories.
    /// See [Etcetera App Strategy](https://docs.rs/etcetera/latest/etcetera/#appstrategy) for more information.
    App,
    /// The `Native` Strategy is mainly used for GUI applications and places the config directory based on the
    /// host systems determination. See [Etcetera Native Strategy](https://docs.rs/etcetera/latest/etcetera/#native-strategy) for more information.
    Native,
}

/// Changes the strategy to use which places the config file using XDG or the native OS's configuration.
///
/// The default is the App Strategy see [`ConfigStrategy`] for more details on the strategy's affect.
///
/// ```rust,no_run
/// # use confy::{ConfyError, ConfigStrategy, change_config_strategy};
/// # use serde_derive::{Serialize, Deserialize};
/// # fn main() -> Result<(), ConfyError> {
/// #[derive(Default, Serialize, Deserialize)]
/// struct MyConfig {}
/// // use the native file paths to store the config
/// change_config_strategy(ConfigStrategy::Native);
///
/// let cfg: MyConfig = confy::load("my-app-name", None)?;
/// # Ok(())
/// # }
/// ```
pub fn change_config_strategy(changer: ConfigStrategy) {
    *STRATEGY
        .lock()
        .expect("Error getting lock on Config Strategy") = changer;
}

enum InternalStrategy {
    App(app_strategy::Xdg),
    NativeMac(app_strategy::Apple),
    NativeUnix(app_strategy::Unix),
    NativeWindows(app_strategy::Windows),
}

// we only every access the config dir function
impl AppStrategy for InternalStrategy {
    fn home_dir(&self) -> &Path {
        unimplemented!()
    }

    fn config_dir(&self) -> PathBuf {
        match self {
            InternalStrategy::App(xdg) => xdg.config_dir(),
            InternalStrategy::NativeMac(mac) => mac.config_dir(),
            InternalStrategy::NativeUnix(unix) => unix.config_dir(),
            InternalStrategy::NativeWindows(windows) => windows.config_dir(),
        }
    }

    fn data_dir(&self) -> PathBuf {
        unimplemented!()
    }

    fn cache_dir(&self) -> PathBuf {
        unimplemented!()
    }

    fn state_dir(&self) -> Option<PathBuf> {
        unimplemented!()
    }

    fn runtime_dir(&self) -> Option<PathBuf> {
        unimplemented!()
    }
}

impl From<app_strategy::Xdg> for InternalStrategy {
    fn from(value: app_strategy::Xdg) -> Self {
        InternalStrategy::App(value)
    }
}

impl From<app_strategy::Apple> for InternalStrategy {
    fn from(value: app_strategy::Apple) -> Self {
        InternalStrategy::NativeMac(value)
    }
}

impl From<app_strategy::Unix> for InternalStrategy {
    fn from(value: app_strategy::Unix) -> Self {
        InternalStrategy::NativeUnix(value)
    }
}

impl From<app_strategy::Windows> for InternalStrategy {
    fn from(value: app_strategy::Windows) -> Self {
        InternalStrategy::NativeWindows(value)
    }
}

/// Load an application configuration from disk
///
/// A new configuration file is created with default values if none
/// exists.
///
/// Errors that are returned from this function are I/O related,
/// for example if the writing of the new configuration fails
/// or `confy` encounters an operating system or environment
/// that it does not support.
///
/// **Note:** The type of configuration needs to be declared in some way
/// that is inferable by the compiler. Also note that your
/// configuration needs to implement `Default`.
///
/// ```rust,no_run
/// # use confy::ConfyError;
/// # use serde_derive::{Serialize, Deserialize};
/// # fn main() -> Result<(), ConfyError> {
/// #[derive(Default, Serialize, Deserialize)]
/// struct MyConfig {}
///
/// let cfg: MyConfig = confy::load("my-app-name", None)?;
/// # Ok(())
/// # }
/// ```
pub fn load<'a, T: Serialize + DeserializeOwned + Default>(
    app_name: &str,
    config_name: impl Into<Option<&'a str>>,
) -> Result<T, ConfyError> {
    get_configuration_file_path(app_name, config_name).and_then(load_path)
}

/// Load an application configuration from a specified path.
///
/// A new configuration file is created with default values if none
/// exists.
///
/// This is an alternate version of [`load`] that allows the specification of
/// an arbitrary path instead of a system one.  For more information on errors
/// and behavior, see [`load`]'s documentation.
///
/// [`load`]: fn.load.html
pub fn load_path<T: Serialize + DeserializeOwned + Default>(
    path: impl AsRef<Path>,
) -> Result<T, ConfyError> {
    match File::open(&path) {
        Ok(mut cfg) => {
            let cfg_string = cfg
                .get_string()
                .map_err(ConfyError::ReadConfigurationFileError)?;

            #[cfg(any(feature = "toml_conf", feature = "basic_toml_conf"))]
            {
                let cfg_data = toml_from_str(&cfg_string);
                cfg_data.map_err(ConfyError::BadTomlData)
            }
            #[cfg(feature = "yaml_conf")]
            {
                let cfg_data = serde_yaml::from_str(&cfg_string);
                cfg_data.map_err(ConfyError::BadYamlData)
            }
            #[cfg(feature = "ron_conf")]
            {
                let cfg_data = ron::from_str(&cfg_string);
                cfg_data.map_err(ConfyError::BadRonData)
            }
        }
        Err(ref e) if e.kind() == NotFound => {
            if let Some(parent) = path.as_ref().parent() {
                fs::create_dir_all(parent).map_err(ConfyError::DirectoryCreationFailed)?;
            }
            let cfg = T::default();
            store_path(path, &cfg)?;
            Ok(cfg)
        }
        Err(e) => Err(ConfyError::GeneralLoadError(e)),
    }
}

/// Load an application configuration from a specified path.
///
/// A new configuration file is created with `op`'s result if none
/// exists or file content is incorrect.
///
/// This is an alternate version of [`load`] that allows the specification of
/// an arbitrary path instead of a system one.  For more information on errors
/// and behavior, see [`load`]'s documentation.
///
/// [`load`]: fn.load.html
pub fn load_or_else<T, F>(path: impl AsRef<Path>, op: F) -> Result<T, ConfyError>
where
    T: DeserializeOwned + Serialize,
    F: FnOnce() -> T,
{
    let path_ref = path.as_ref();
    let load_value = || {
        let cfg = op();
        if let Some(parent) = path.as_ref().parent() {
            fs::create_dir_all(parent).map_err(ConfyError::DirectoryCreationFailed)?;
        }
        store_path(path_ref, &cfg)?;
        Ok(cfg)
    };

    match File::open(path_ref) {
        Ok(mut cfg) => {
            let mut load_from_file = || {
                let cfg_string = cfg
                    .get_string()
                    .map_err(ConfyError::ReadConfigurationFileError)?;

                #[cfg(any(feature = "toml_conf", feature = "basic_toml_conf"))]
                {
                    let cfg_data = toml_from_str(&cfg_string);
                    cfg_data.map_err(ConfyError::BadTomlData)
                }
                #[cfg(feature = "yaml_conf")]
                {
                    let cfg_data = serde_yaml::from_str(&cfg_string);
                    cfg_data.map_err(ConfyError::BadYamlData)
                }
                #[cfg(feature = "ron_conf")]
                {
                    let cfg_data = ron::from_str(&cfg_string);
                    cfg_data.map_err(ConfyError::BadRonData)
                }
            };
            load_from_file().or_else(|_| load_value())
        }
        Err(ref e) if e.kind() == NotFound => load_value(),
        Err(e) => Err(ConfyError::GeneralLoadError(e)),
    }
}

/// Save changes made to a configuration object
///
/// This function will update a configuration,
/// with the provided values, and create a new one,
/// if none exists.
///
/// You can also use this function to create a new configuration
/// with different initial values than which are provided
/// by your `Default` trait implementation, or if your
/// configuration structure _can't_ implement `Default`.
///
/// ```rust,no_run
/// # use serde_derive::{Serialize, Deserialize};
/// # use confy::ConfyError;
/// # fn main() -> Result<(), ConfyError> {
/// #[derive(Serialize, Deserialize)]
/// struct MyConf {}
///
/// let my_cfg = MyConf {};
/// confy::store("my-app-name", None, my_cfg)?;
/// # Ok(())
/// # }
/// ```
///
/// Errors returned are I/O errors related to not being
/// able to write the configuration file or if `confy`
/// encounters an operating system or environment it does
/// not support.
pub fn store<'a, T: Serialize>(
    app_name: &str,
    config_name: impl Into<Option<&'a str>>,
    cfg: T,
) -> Result<(), ConfyError> {
    let path = get_configuration_file_path(app_name, config_name)?;
    store_path(path, cfg)
}

/// Save changes made to a configuration object at a specified path
///
/// This is an alternate version of [`store`] that allows the specification of
/// file permissions that must be set. For more information on errors and
/// behavior, see [`store`]'s documentation.
///
/// [`store`]: fn.store.html
pub fn store_perms<'a, T: Serialize>(
    app_name: &str,
    config_name: impl Into<Option<&'a str>>,
    cfg: T,
    perms: Permissions,
) -> Result<(), ConfyError> {
    let path = get_configuration_file_path(app_name, config_name)?;
    store_path_perms(path, cfg, perms)
}

/// Save changes made to a configuration object at a specified path
///
/// This is an alternate version of [`store`] that allows the specification of
/// an arbitrary path instead of a system one.  For more information on errors
/// and behavior, see [`store`]'s documentation.
///
/// [`store`]: fn.store.html
pub fn store_path<T: Serialize>(path: impl AsRef<Path>, cfg: T) -> Result<(), ConfyError> {
    do_store(path.as_ref(), cfg, None)
}

/// Save changes made to a configuration object at a specified path
///
/// This is an alternate version of [`store_path`] that allows the
/// specification of file permissions that must be set. For more information on
/// errors and behavior, see [`store`]'s documentation.
///
/// [`store_path`]: fn.store_path.html
pub fn store_path_perms<T: Serialize>(
    path: impl AsRef<Path>,
    cfg: T,
    perms: Permissions,
) -> Result<(), ConfyError> {
    do_store(path.as_ref(), cfg, Some(perms))
}

fn do_store<T: Serialize>(
    path: &Path,
    cfg: T,
    perms: Option<Permissions>,
) -> Result<(), ConfyError> {
    let config_dir = path
        .parent()
        .ok_or_else(|| ConfyError::BadConfigDirectory(format!("{path:?} is a root or prefix")))?;
    fs::create_dir_all(config_dir).map_err(ConfyError::DirectoryCreationFailed)?;

    let s;
    #[cfg(any(feature = "toml_conf", feature = "basic_toml_conf"))]
    {
        s = toml_to_string_pretty(&cfg).map_err(ConfyError::SerializeTomlError)?;
    }
    #[cfg(feature = "yaml_conf")]
    {
        s = serde_yaml::to_string(&cfg).map_err(ConfyError::SerializeYamlError)?;
    }
    #[cfg(feature = "ron_conf")]
    {
        let pretty_cfg = ron::ser::PrettyConfig::default();
        s = ron::ser::to_string_pretty(&cfg, pretty_cfg).map_err(ConfyError::SerializeRonError)?;
    }

    let mut f = OpenOptions::new()
        .write(true)
        .create(true)
        .truncate(true)
        .open(path)
        .map_err(ConfyError::OpenConfigurationFileError)?;

    if let Some(p) = perms {
        f.set_permissions(p)
            .map_err(ConfyError::SetPermissionsFileError)?;
    }

    f.write_all(s.as_bytes())
        .map_err(ConfyError::WriteConfigurationFileError)?;
    Ok(())
}

/// Get the configuration file path used by [`load`] and [`store`]
///
/// This is useful if you want to show where the configuration file is to your user.
///
/// [`load`]: fn.load.html
/// [`store`]: fn.store.html
pub fn get_configuration_file_path<'a>(
    app_name: &str,
    config_name: impl Into<Option<&'a str>>,
) -> Result<PathBuf, ConfyError> {
    let config_name = config_name.into().unwrap_or("default-config");
    let project: InternalStrategy = match *STRATEGY
        .lock()
        .expect("Error getting lock on config strategy")
    {
        ConfigStrategy::App => choose_app_strategy(AppStrategyArgs {
            top_level_domain: "rs".to_string(),
            author: "".to_string(),
            app_name: app_name.to_string(),
        })
        .map_err(|e| {
            ConfyError::BadConfigDirectory(format!("could not determine home directory path: {e}"))
        })?
        .into(),
        ConfigStrategy::Native => choose_native_strategy(AppStrategyArgs {
            top_level_domain: "rs".to_string(),
            author: "".to_string(),
            app_name: app_name.to_string(),
        })
        .map_err(|e| {
            ConfyError::BadConfigDirectory(format!("could not determine home directory path: {e}"))
        })?
        .into(),
    };

    let mut path = project.config_dir();

    path.push(format!("{config_name}.{EXTENSION}"));

    Ok(path)
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde::Serializer;
    use serde_derive::{Deserialize, Serialize};

    #[cfg(unix)]
    use std::os::unix::fs::PermissionsExt;

    #[derive(PartialEq, Default, Debug, Serialize, Deserialize)]
    struct ExampleConfig {
        name: String,
        count: usize,
    }

    /// Run a test function with a temporary config path as fixture.
    fn with_config_path(test_fn: fn(&Path)) {
        let config_dir = tempfile::tempdir().expect("creating test fixture failed");
        // config_path should roughly correspond to the result of `get_configuration_file_path("example-app", "example-config")`
        let config_path = config_dir
            .path()
            .join("example-app")
            .join("example-config")
            .with_extension(EXTENSION);
        test_fn(&config_path);
        config_dir.close().expect("removing test fixture failed");
    }

    /// [`load_path`] loads [`ExampleConfig`].
    #[test]
    fn load_path_works() {
        with_config_path(|path| {
            let config: ExampleConfig = load_path(path).expect("load_path failed");
            assert_eq!(config, ExampleConfig::default());
        })
    }

    /// [`load_or_else`] loads [`ExampleConfig`].
    #[test]
    fn load_or_else_works() {
        with_config_path(|path| {
            let the_value = || ExampleConfig {
                name: "a".to_string(),
                count: 5,
            };

            let config: ExampleConfig = load_or_else(path, the_value).expect("load_or_else failed");
            assert_eq!(config, the_value());
        });

        with_config_path(|path| {
            fs::create_dir_all(path.parent().unwrap()).unwrap();
            let mut file = File::create(path).expect("creating file failed");
            file.write("some normal text".as_bytes())
                .expect("write to file failed");
            drop(file);

            let the_value = || ExampleConfig {
                name: "a".to_string(),
                count: 5,
            };

            let config: ExampleConfig = load_or_else(path, the_value).expect("load_or_else failed");
            assert_eq!(config, the_value());
        })
    }

    /// [`store_path`] stores [`ExampleConfig`].
    #[test]
    fn test_store_path() {
        with_config_path(|path| {
            let config: ExampleConfig = ExampleConfig {
                name: "Test".to_string(),
                count: 42,
            };
            store_path(path, &config).expect("store_path failed");
            let loaded = load_path(path).expect("load_path failed");
            assert_eq!(config, loaded);
        })
    }

    #[test]
    fn test_store_path_native() {
        // change the strategy first then the app will always use it
        change_config_strategy(ConfigStrategy::Native);

        with_config_path(|path| {
            let config: ExampleConfig = ExampleConfig {
                name: "Test".to_string(),
                count: 42,
            };

            let file_path = get_configuration_file_path("example-app", "example-config").unwrap();

            if cfg!(target_os = "macos") {
                assert_eq!(
                    file_path,
                    Path::new(&format!(
                        "{}/Library/Preferences/rs.example-app/example-config.toml",
                        std::env::home_dir().unwrap().display()
                    )),
                );
            } else if cfg!(target_os = "linux") {
                assert_eq!(
                    file_path,
                    Path::new(&format!(
                        "{}/.config/example-app/example-config.toml",
                        std::env::home_dir().unwrap().display()
                    ))
                );
            } else {
                //windows
                assert_eq!(
                    file_path,
                    Path::new(&format!(
                        "{}\\AppData\\Roaming\\example-app\\config\\example-config.toml",
                        std::env::home_dir().unwrap().display()
                    )),
                );
            }

            // Make sure it is still the same config file
            store_path(path, &config).expect("store_path failed");
            let loaded = load_path(path).expect("load_path failed");
            assert_eq!(config, loaded);
        })
    }

    #[test]
    fn test_store_path_change() {
        // change the strategy first to native
        change_config_strategy(ConfigStrategy::Native);

        with_config_path(|path| {
            let config: ExampleConfig = ExampleConfig {
                name: "Test".to_string(),
                count: 42,
            };

            let file_path = get_configuration_file_path("example-app", "example-config").unwrap();

            if cfg!(target_os = "macos") {
                assert_eq!(
                    file_path,
                    Path::new(&format!(
                        "{}/Library/Preferences/rs.example-app/example-config.toml",
                        std::env::home_dir().unwrap().display()
                    )),
                );
            } else if cfg!(target_os = "linux") {
                assert_eq!(
                    file_path,
                    Path::new(&format!(
                        "{}/.config/example-app/example-config.toml",
                        std::env::home_dir().unwrap().display()
                    ))
                );
            } else {
                //windows
                assert_eq!(
                    file_path,
                    Path::new(&format!(
                        "{}\\AppData\\Roaming\\example-app\\config\\example-config.toml",
                        std::env::home_dir().unwrap().display()
                    )),
                );
            }

            //change the strategy back to Application style
            change_config_strategy(ConfigStrategy::App);

            let file_path = get_configuration_file_path("example-app", "example-config").unwrap();

            if cfg!(target_os = "macos") {
                assert_eq!(
                    file_path,
                    Path::new(&format!(
                        "{}/.config/example-app/example-config.toml",
                        std::env::home_dir().unwrap().display()
                    )),
                );
            } else if cfg!(target_os = "linux") {
                assert_eq!(
                    file_path,
                    Path::new(&format!(
                        "{}/.config/example-app/example-config.toml",
                        std::env::home_dir().unwrap().display()
                    ))
                );
            } else {
                //windows
                assert_eq!(
                    file_path,
                    Path::new(&format!(
                        "{}\\AppData\\Roaming\\example-app\\config\\example-config.toml",
                        std::env::home_dir().unwrap().display()
                    )),
                );
            }

            // Make sure it is still the same config file
            store_path(path, &config).expect("store_path failed");
            let loaded = load_path(path).expect("load_path failed");
            assert_eq!(config, loaded);
        })
    }

    /// [`store_path_perms`] stores [`ExampleConfig`], with only read permission for owner (UNIX).
    #[test]
    #[cfg(unix)]
    fn test_store_path_perms() {
        with_config_path(|path| {
            let config: ExampleConfig = ExampleConfig {
                name: "Secret".to_string(),
                count: 16549,
            };
            store_path_perms(path, &config, Permissions::from_mode(0o600))
                .expect("store_path_perms failed");
            let loaded = load_path(path).expect("load_path failed");
            assert_eq!(config, loaded);
        })
    }

    /// [`store_path_perms`] stores [`ExampleConfig`], as read-only.
    #[test]
    fn test_store_path_perms_readonly() {
        with_config_path(|path| {
            let config: ExampleConfig = ExampleConfig {
                name: "Soon read-only".to_string(),
                count: 27115,
            };
            store_path(path, &config).expect("store_path failed");

            let metadata = fs::metadata(path).expect("reading metadata failed");
            let mut permissions = metadata.permissions();
            permissions.set_readonly(true);

            store_path_perms(path, &config, permissions).expect("store_path_perms failed");

            assert!(
                fs::metadata(path)
                    .expect("reading metadata failed")
                    .permissions()
                    .readonly()
            );
        })
    }

    /// [`store_path`] fails when given a root path.
    #[test]
    fn test_store_path_root_error() {
        let err = store_path(PathBuf::from("/"), &ExampleConfig::default())
            .expect_err("store_path should fail");
        assert_eq!(
            err.to_string(),
            r#"Bad configuration directory: "/" is a root or prefix"#,
        )
    }

    struct CannotSerialize;

    impl Serialize for CannotSerialize {
        fn serialize<S>(&self, _serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            use serde::ser::Error;
            Err(S::Error::custom("cannot serialize CannotSerialize"))
        }
    }

    /// Verify that if you call store_path() with an object that fails to serialize,
    /// the file on disk will not be overwritten or truncated.
    #[test]
    fn test_store_path_atomic() -> Result<(), ConfyError> {
        let tmp = tempfile::NamedTempFile::new().expect("Failed to create NamedTempFile");
        let path = tmp.path();
        let message = "Hello world!";

        // Write to file.
        {
            let mut f = OpenOptions::new()
                .write(true)
                .create(true)
                .truncate(true)
                .open(path)
                .map_err(ConfyError::OpenConfigurationFileError)?;

            f.write_all(message.as_bytes())
                .map_err(ConfyError::WriteConfigurationFileError)?;

            f.flush().map_err(ConfyError::WriteConfigurationFileError)?;
        }

        // Call store_path() to overwrite file with an object that fails to serialize.
        let store_result = store_path(path, CannotSerialize);
        assert!(matches!(store_result, Err(_)));

        // Ensure file was not overwritten.
        let buf = {
            let mut f = OpenOptions::new()
                .read(true)
                .open(path)
                .map_err(ConfyError::OpenConfigurationFileError)?;

            let mut buf = String::new();

            use std::io::Read;
            f.read_to_string(&mut buf)
                .map_err(ConfyError::ReadConfigurationFileError)?;
            buf
        };

        assert_eq!(buf, message);
        Ok(())
    }

    // Verify that [`load_path`] can deserialize into structs with differing names
    // as long as they have the same fields
    #[test]
    fn test_change_struct_name() -> Result<(), ConfyError> {
        with_config_path(|path| {
            #[derive(PartialEq, Default, Debug, Serialize, Deserialize)]
            struct AnotherExampleConfig {
                name: String,
                count: usize,
            }

            store_path(path, &ExampleConfig::default()).expect("store_path failed");
            let _: AnotherExampleConfig = load_path(path).expect("load_path failed");
        });

        Ok(())
    }
}