1
#![cfg_attr(docsrs, feature(doc_cfg))]
2
#![doc = include_str!("../README.md")]
3
// @@ begin lint list maintained by maint/add_warning @@
4
#![allow(renamed_and_removed_lints)] // @@REMOVE_WHEN(ci_arti_stable)
5
#![allow(unknown_lints)] // @@REMOVE_WHEN(ci_arti_nightly)
6
#![warn(missing_docs)]
7
#![warn(noop_method_call)]
8
#![warn(unreachable_pub)]
9
#![warn(clippy::all)]
10
#![deny(clippy::await_holding_lock)]
11
#![deny(clippy::cargo_common_metadata)]
12
#![deny(clippy::cast_lossless)]
13
#![deny(clippy::checked_conversions)]
14
#![warn(clippy::cognitive_complexity)]
15
#![deny(clippy::debug_assert_with_mut_call)]
16
#![deny(clippy::exhaustive_enums)]
17
#![deny(clippy::exhaustive_structs)]
18
#![deny(clippy::expl_impl_clone_on_copy)]
19
#![deny(clippy::fallible_impl_from)]
20
#![deny(clippy::implicit_clone)]
21
#![deny(clippy::large_stack_arrays)]
22
#![warn(clippy::manual_ok_or)]
23
#![deny(clippy::missing_docs_in_private_items)]
24
#![warn(clippy::needless_borrow)]
25
#![warn(clippy::needless_pass_by_value)]
26
#![warn(clippy::option_option)]
27
#![deny(clippy::print_stderr)]
28
#![deny(clippy::print_stdout)]
29
#![warn(clippy::rc_buffer)]
30
#![deny(clippy::ref_option_ref)]
31
#![warn(clippy::semicolon_if_nothing_returned)]
32
#![warn(clippy::trait_duplication_in_bounds)]
33
#![deny(clippy::unchecked_time_subtraction)]
34
#![deny(clippy::unnecessary_wraps)]
35
#![warn(clippy::unseparated_literal_suffix)]
36
#![deny(clippy::unwrap_used)]
37
#![deny(clippy::mod_module_files)]
38
#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
39
#![allow(clippy::uninlined_format_args)]
40
#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
41
#![allow(clippy::result_large_err)] // temporary workaround for arti#587
42
#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
43
#![allow(clippy::needless_lifetimes)] // See arti#1765
44
#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
45
#![allow(clippy::collapsible_if)] // See arti#2342
46
#![deny(clippy::unused_async)]
47
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
48

            
49
use std::collections::HashMap;
50
use std::path::{Path, PathBuf};
51

            
52
use serde::{Deserialize, Serialize};
53
use std::borrow::Cow;
54
#[cfg(feature = "expand-paths")]
55
use {directories::BaseDirs, std::sync::LazyLock};
56

            
57
use tor_error::{ErrorKind, HasKind};
58

            
59
#[cfg(all(test, feature = "expand-paths"))]
60
use std::ffi::OsStr;
61

            
62
#[cfg(feature = "address")]
63
pub mod addr;
64

            
65
#[cfg(feature = "arti-client")]
66
mod arti_client_paths;
67

            
68
#[cfg(feature = "arti-client")]
69
pub use arti_client_paths::arti_client_base_resolver;
70

            
71
/// A path in a configuration file: tilde expansion is performed, along
72
/// with expansion of variables provided by a [`CfgPathResolver`].
73
///
74
/// The tilde expansion is performed using the home directory given by the
75
/// `directories` crate, which may be based on an environment variable. For more
76
/// information, see [`BaseDirs::home_dir`](directories::BaseDirs::home_dir).
77
///
78
/// Alternatively, a `CfgPath` can contain literal `PathBuf`, which will not be expanded.
79
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
80
#[serde(transparent)]
81
pub struct CfgPath(PathInner);
82

            
83
/// Inner implementation of CfgPath
84
///
85
/// `PathInner` exists to avoid making the variants part of the public Rust API
86
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
87
#[serde(untagged)]
88
enum PathInner {
89
    /// A path that should be used literally, with no expansion.
90
    Literal(LiteralPath),
91
    /// A path that should be expanded from a string using ShellExpand.
92
    Shell(String),
93
}
94

            
95
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
96
/// Inner implementation of PathInner:Literal
97
///
98
/// `LiteralPath` exists to arrange that `PathInner::Literal`'s (de)serialization
99
/// does not overlap with `PathInner::Shell`'s.
100
struct LiteralPath {
101
    /// The underlying `PathBuf`.
102
    literal: PathBuf,
103
}
104

            
105
/// An error that has occurred while expanding a path.
106
#[derive(thiserror::Error, Debug, Clone)]
107
#[non_exhaustive]
108
#[cfg_attr(test, derive(PartialEq))]
109
pub enum CfgPathError {
110
    /// The path contained a variable we didn't recognize.
111
    #[error("Unrecognized variable {0} in path")]
112
    UnknownVar(String),
113
    /// We couldn't construct a ProjectDirs object.
114
    #[error(
115
        "Couldn't determine XDG Project Directories, needed to resolve a path; probably, unable to determine HOME directory"
116
    )]
117
    NoProjectDirs,
118
    /// We couldn't construct a BaseDirs object.
119
    #[error("Can't construct base directories to resolve a path element")]
120
    NoBaseDirs,
121
    /// We couldn't find our current binary path.
122
    #[error("Can't find the path to the current binary")]
123
    NoProgramPath,
124
    /// We couldn't find the directory path containing the current binary.
125
    #[error("Can't find the directory of the current binary")]
126
    NoProgramDir,
127
    /// We couldn't convert a string to a valid path on the OS.
128
    //
129
    // NOTE: This is not currently generated. Shall we remove it?
130
    #[error("Invalid path string: {0:?}")]
131
    InvalidString(String),
132
    /// Variable interpolation (`$`) attempted, but not compiled in
133
    #[error(
134
        "Variable interpolation $ is not supported (tor-config/expand-paths feature disabled)); $ must still be doubled"
135
    )]
136
    VariableInterpolationNotSupported(String),
137
    /// Home dir interpolation (`~`) attempted, but not compiled in
138
    #[error("Home dir ~/ is not supported (tor-config/expand-paths feature disabled)")]
139
    HomeDirInterpolationNotSupported(String),
140
}
141

            
142
impl HasKind for CfgPathError {
143
    fn kind(&self) -> ErrorKind {
144
        use CfgPathError as E;
145
        use ErrorKind as EK;
146
        match self {
147
            E::UnknownVar(_) | E::InvalidString(_) => EK::InvalidConfig,
148
            E::NoProjectDirs | E::NoBaseDirs => EK::NoHomeDirectory,
149
            E::NoProgramPath | E::NoProgramDir => EK::InvalidConfig,
150
            E::VariableInterpolationNotSupported(_) | E::HomeDirInterpolationNotSupported(_) => {
151
                EK::FeatureDisabled
152
            }
153
        }
154
    }
155
}
156

            
157
/// A variable resolver for paths in a configuration file.
158
///
159
/// Typically there should be one resolver per application, and the application should share the
160
/// resolver throughout the application to have consistent path variable expansions. Typically the
161
/// application would create its own resolver with its application-specific variables, but note that
162
/// `TorClientConfig` is an exception which does not accept a resolver from the application and
163
/// instead generates its own. This is done for backwards compatibility reasons.
164
///
165
/// Once constructed, they are used during calls to [`CfgPath::path`] to expand variables in the
166
/// path.
167
#[derive(Clone, Debug, Default)]
168
pub struct CfgPathResolver {
169
    /// The variables and their values. The values can be an `Err` if the variable is expected but
170
    /// can't be expanded.
171
    vars: HashMap<String, Result<Cow<'static, Path>, CfgPathError>>,
172
}
173

            
174
impl CfgPathResolver {
175
    /// Get the value for a given variable name.
176
    #[cfg(feature = "expand-paths")]
177
5786
    fn get_var(&self, var: &str) -> Result<Cow<'static, Path>, CfgPathError> {
178
5786
        match self.vars.get(var) {
179
5735
            Some(val) => val.clone(),
180
51
            None => Err(CfgPathError::UnknownVar(var.to_owned())),
181
        }
182
5786
    }
183

            
184
    /// Set a variable `var` that will be replaced with `val` when a [`CfgPath`] is expanded.
185
    ///
186
    /// Setting an `Err` is useful when a variable is supported, but for whatever reason it can't be
187
    /// expanded, and you'd like to return a more-specific error. An example might be a `USER_HOME`
188
    /// variable for a user that doesn't have a `HOME` environment variable set.
189
    ///
190
    /// ```
191
    /// use std::path::Path;
192
    /// use tor_config_path::{CfgPath, CfgPathResolver};
193
    ///
194
    /// let mut path_resolver = CfgPathResolver::default();
195
    /// path_resolver.set_var("FOO", Ok(Path::new("/foo").to_owned().into()));
196
    ///
197
    /// let path = CfgPath::new("${FOO}/bar".into());
198
    ///
199
    /// #[cfg(feature = "expand-paths")]
200
    /// assert_eq!(path.path(&path_resolver).unwrap(), Path::new("/foo/bar"));
201
    /// #[cfg(not(feature = "expand-paths"))]
202
    /// assert!(path.path(&path_resolver).is_err());
203
    /// ```
204
57456
    pub fn set_var(
205
57456
        &mut self,
206
57456
        var: impl Into<String>,
207
57456
        val: Result<Cow<'static, Path>, CfgPathError>,
208
57456
    ) {
209
57456
        self.vars.insert(var.into(), val);
210
57456
    }
211

            
212
    /// Helper to create a `CfgPathResolver` from str `(name, value)` pairs.
213
    #[cfg(all(test, feature = "expand-paths"))]
214
24
    fn from_pairs<K, V>(vars: impl IntoIterator<Item = (K, V)>) -> CfgPathResolver
215
24
    where
216
24
        K: Into<String>,
217
24
        V: AsRef<OsStr>,
218
    {
219
24
        let mut path_resolver = CfgPathResolver::default();
220
24
        for (name, val) in vars.into_iter() {
221
24
            let val = Path::new(val.as_ref()).to_owned();
222
24
            path_resolver.set_var(name, Ok(val.into()));
223
24
        }
224
24
        path_resolver
225
24
    }
226
}
227

            
228
impl CfgPath {
229
    /// Create a new configuration path
230
21061
    pub fn new(s: String) -> Self {
231
21061
        CfgPath(PathInner::Shell(s))
232
21061
    }
233

            
234
    /// Construct a new `CfgPath` designating a literal not-to-be-expanded `PathBuf`
235
1245
    pub fn new_literal<P: Into<PathBuf>>(path: P) -> Self {
236
1245
        CfgPath(PathInner::Literal(LiteralPath {
237
1245
            literal: path.into(),
238
1245
        }))
239
1245
    }
240

            
241
    /// Return the path on disk designated by this `CfgPath`.
242
    ///
243
    /// Variables may or may not be resolved using `path_resolver`, depending on whether the
244
    /// `expand-paths` feature is enabled or not.
245
10349
    pub fn path(&self, path_resolver: &CfgPathResolver) -> Result<PathBuf, CfgPathError> {
246
10349
        match &self.0 {
247
8226
            PathInner::Shell(s) => expand(s, path_resolver),
248
2123
            PathInner::Literal(LiteralPath { literal }) => Ok(literal.clone()),
249
        }
250
10349
    }
251

            
252
    /// If the `CfgPath` is a string that should be expanded, return the (unexpanded) string,
253
    ///
254
    /// Before use, this string would have be to expanded.  So if you want a path to actually use,
255
    /// call `path` instead.
256
    ///
257
    /// Returns `None` if the `CfgPath` is a literal `PathBuf` not intended for expansion.
258
12
    pub fn as_unexpanded_str(&self) -> Option<&str> {
259
12
        match &self.0 {
260
6
            PathInner::Shell(s) => Some(s),
261
6
            PathInner::Literal(_) => None,
262
        }
263
12
    }
264

            
265
    /// If the `CfgPath` designates a literal not-to-be-expanded `Path`, return a reference to it
266
    ///
267
    /// Returns `None` if the `CfgPath` is a string which should be expanded, which is the
268
    /// usual case.
269
12
    pub fn as_literal_path(&self) -> Option<&Path> {
270
12
        match &self.0 {
271
6
            PathInner::Shell(_) => None,
272
6
            PathInner::Literal(LiteralPath { literal }) => Some(literal),
273
        }
274
12
    }
275
}
276

            
277
impl std::fmt::Display for CfgPath {
278
249
    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
279
249
        match &self.0 {
280
2
            PathInner::Literal(LiteralPath { literal }) => write!(fmt, "{:?} [exactly]", literal),
281
247
            PathInner::Shell(s) => s.fmt(fmt),
282
        }
283
249
    }
284
}
285

            
286
/// Return the user's home directory used when expanding paths.
287
// This is public so that applications which want to support for example a `USER_HOME` variable can
288
// use the same home directory expansion that we use in this crate for `~` expansion.
289
#[cfg(feature = "expand-paths")]
290
9640
pub fn home() -> Result<&'static Path, CfgPathError> {
291
    /// Lazy lock holding the home directory.
292
    static HOME_DIR: LazyLock<Option<PathBuf>> =
293
2837
        LazyLock::new(|| Some(BaseDirs::new()?.home_dir().to_owned()));
294
9640
    HOME_DIR
295
9640
        .as_ref()
296
9640
        .map(PathBuf::as_path)
297
9640
        .ok_or(CfgPathError::NoBaseDirs)
298
9640
}
299

            
300
/// Helper: expand a directory given as a string.
301
#[cfg(feature = "expand-paths")]
302
8226
fn expand(s: &str, path_resolver: &CfgPathResolver) -> Result<PathBuf, CfgPathError> {
303
8226
    let path = shellexpand::path::full_with_context(
304
8226
        s,
305
2
        || home().ok(),
306
5786
        |x| path_resolver.get_var(x).map(Some),
307
    );
308
8226
    Ok(path.map_err(|e| e.cause)?.into_owned())
309
8226
}
310

            
311
/// Helper: convert a string to a path without expansion.
312
#[cfg(not(feature = "expand-paths"))]
313
fn expand(input: &str, _: &CfgPathResolver) -> Result<PathBuf, CfgPathError> {
314
    // We must still de-duplicate `$` and reject `~/`,, so that the behaviour is a superset
315
    if input.starts_with('~') {
316
        return Err(CfgPathError::HomeDirInterpolationNotSupported(input.into()));
317
    }
318

            
319
    let mut out = String::with_capacity(input.len());
320
    let mut s = input;
321
    while let Some((lhs, rhs)) = s.split_once('$') {
322
        if let Some(rhs) = rhs.strip_prefix('$') {
323
            // deduplicate the $
324
            out += lhs;
325
            out += "$";
326
            s = rhs;
327
        } else {
328
            return Err(CfgPathError::VariableInterpolationNotSupported(
329
                input.into(),
330
            ));
331
        }
332
    }
333
    out += s;
334
    Ok(out.into())
335
}
336

            
337
#[cfg(all(test, feature = "expand-paths"))]
338
mod test {
339
    #![allow(clippy::unwrap_used)]
340
    use super::*;
341

            
342
    #[test]
343
    fn expand_no_op() {
344
        let r = CfgPathResolver::from_pairs([("FOO", "foo")]);
345

            
346
        let p = CfgPath::new("Hello/world".to_string());
347
        assert_eq!(p.to_string(), "Hello/world".to_string());
348
        assert_eq!(p.path(&r).unwrap().to_str(), Some("Hello/world"));
349

            
350
        let p = CfgPath::new("/usr/local/foo".to_string());
351
        assert_eq!(p.to_string(), "/usr/local/foo".to_string());
352
        assert_eq!(p.path(&r).unwrap().to_str(), Some("/usr/local/foo"));
353
    }
354

            
355
    #[cfg(not(target_family = "windows"))]
356
    #[test]
357
    fn expand_home() {
358
        let r = CfgPathResolver::from_pairs([("USER_HOME", home().unwrap())]);
359

            
360
        let p = CfgPath::new("~/.arti/config".to_string());
361
        assert_eq!(p.to_string(), "~/.arti/config".to_string());
362

            
363
        let expected = dirs::home_dir().unwrap().join(".arti/config");
364
        assert_eq!(p.path(&r).unwrap().to_str(), expected.to_str());
365

            
366
        let p = CfgPath::new("${USER_HOME}/.arti/config".to_string());
367
        assert_eq!(p.to_string(), "${USER_HOME}/.arti/config".to_string());
368
        assert_eq!(p.path(&r).unwrap().to_str(), expected.to_str());
369
    }
370

            
371
    #[cfg(target_family = "windows")]
372
    #[test]
373
    fn expand_home() {
374
        let r = CfgPathResolver::from_pairs([("USER_HOME", home().unwrap())]);
375

            
376
        let p = CfgPath::new("~\\.arti\\config".to_string());
377
        assert_eq!(p.to_string(), "~\\.arti\\config".to_string());
378

            
379
        let expected = dirs::home_dir().unwrap().join(".arti\\config");
380
        assert_eq!(p.path(&r).unwrap().to_str(), expected.to_str());
381

            
382
        let p = CfgPath::new("${USER_HOME}\\.arti\\config".to_string());
383
        assert_eq!(p.to_string(), "${USER_HOME}\\.arti\\config".to_string());
384
        assert_eq!(p.path(&r).unwrap().to_str(), expected.to_str());
385
    }
386

            
387
    #[test]
388
    fn expand_bogus() {
389
        let r = CfgPathResolver::from_pairs([("FOO", "foo")]);
390

            
391
        let p = CfgPath::new("${ARTI_WOMBAT}/example".to_string());
392
        assert_eq!(p.to_string(), "${ARTI_WOMBAT}/example".to_string());
393

            
394
        assert!(matches!(p.path(&r), Err(CfgPathError::UnknownVar(_))));
395
        assert_eq!(
396
            &p.path(&r).unwrap_err().to_string(),
397
            "Unrecognized variable ARTI_WOMBAT in path"
398
        );
399
    }
400

            
401
    #[test]
402
    fn literal() {
403
        let r = CfgPathResolver::from_pairs([("ARTI_CACHE", "foo")]);
404

            
405
        let p = CfgPath::new_literal(PathBuf::from("${ARTI_CACHE}/literally"));
406
        // This doesn't get expanded, since we're using a literal path.
407
        assert_eq!(
408
            p.path(&r).unwrap().to_str().unwrap(),
409
            "${ARTI_CACHE}/literally"
410
        );
411
        assert_eq!(p.to_string(), "\"${ARTI_CACHE}/literally\" [exactly]");
412
    }
413

            
414
    #[test]
415
    #[cfg(feature = "expand-paths")]
416
    fn program_dir() {
417
        let current_exe = std::env::current_exe().unwrap();
418
        let r = CfgPathResolver::from_pairs([("PROGRAM_DIR", current_exe.parent().unwrap())]);
419

            
420
        let p = CfgPath::new("${PROGRAM_DIR}/foo".to_string());
421

            
422
        let mut this_binary = current_exe;
423
        this_binary.pop();
424
        this_binary.push("foo");
425
        let expanded = p.path(&r).unwrap();
426
        assert_eq!(expanded, this_binary);
427
    }
428

            
429
    #[test]
430
    #[cfg(not(feature = "expand-paths"))]
431
    fn rejections() {
432
        let r = CfgPathResolver::from_pairs([("PROGRAM_DIR", std::env::current_exe().unwrap())]);
433

            
434
        let chk_err = |s: &str, mke: &dyn Fn(String) -> CfgPathError| {
435
            let p = CfgPath::new(s.to_string());
436
            assert_eq!(p.path(&r).unwrap_err(), mke(s.to_string()));
437
        };
438

            
439
        let chk_ok = |s: &str, exp| {
440
            let p = CfgPath::new(s.to_string());
441
            assert_eq!(p.path(&r), Ok(PathBuf::from(exp)));
442
        };
443

            
444
        chk_err(
445
            "some/${PROGRAM_DIR}/foo",
446
            &CfgPathError::VariableInterpolationNotSupported,
447
        );
448
        chk_err("~some", &CfgPathError::HomeDirInterpolationNotSupported);
449

            
450
        chk_ok("some$$foo$$bar", "some$foo$bar");
451
        chk_ok("no dollars", "no dollars");
452
    }
453
}
454

            
455
#[cfg(test)]
456
mod test_serde {
457
    // @@ begin test lint list maintained by maint/add_warning @@
458
    #![allow(clippy::bool_assert_comparison)]
459
    #![allow(clippy::clone_on_copy)]
460
    #![allow(clippy::dbg_macro)]
461
    #![allow(clippy::mixed_attributes_style)]
462
    #![allow(clippy::print_stderr)]
463
    #![allow(clippy::print_stdout)]
464
    #![allow(clippy::single_char_pattern)]
465
    #![allow(clippy::unwrap_used)]
466
    #![allow(clippy::unchecked_time_subtraction)]
467
    #![allow(clippy::useless_vec)]
468
    #![allow(clippy::needless_pass_by_value)]
469
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
470

            
471
    use super::*;
472

            
473
    use std::ffi::OsString;
474
    use std::fmt::Debug;
475

            
476
    use derive_builder::Builder;
477
    use tor_config::load::TopLevel;
478
    use tor_config::{ConfigBuildError, impl_standard_builder};
479

            
480
    #[derive(Serialize, Deserialize, Builder, Eq, PartialEq, Debug)]
481
    #[builder(derive(Serialize, Deserialize, Debug))]
482
    #[builder(build_fn(error = "ConfigBuildError"))]
483
    struct TestConfigFile {
484
        p: CfgPath,
485
    }
486

            
487
    impl_standard_builder! { TestConfigFile: !Default }
488

            
489
    impl TopLevel for TestConfigFile {
490
        type Builder = TestConfigFileBuilder;
491
    }
492

            
493
    fn deser_json(json: &str) -> CfgPath {
494
        dbg!(json);
495
        let TestConfigFile { p } = serde_json::from_str(json).expect("deser json failed");
496
        p
497
    }
498
    fn deser_toml(toml: &str) -> CfgPath {
499
        dbg!(toml);
500
        let TestConfigFile { p } = toml::from_str(toml).expect("deser toml failed");
501
        p
502
    }
503
    fn deser_toml_cfg(toml: &str) -> CfgPath {
504
        dbg!(toml);
505
        let mut sources = tor_config::ConfigurationSources::new_empty();
506
        sources.push_source(
507
            tor_config::ConfigurationSource::from_verbatim(toml.to_string()),
508
            tor_config::sources::MustRead::MustRead,
509
        );
510
        let cfg = sources.load().unwrap();
511

            
512
        dbg!(&cfg);
513
        let TestConfigFile { p } = tor_config::load::resolve(cfg).expect("cfg resolution failed");
514
        p
515
    }
516

            
517
    #[test]
518
    fn test_parse() {
519
        fn desers(toml: &str, json: &str) -> Vec<CfgPath> {
520
            vec![deser_toml(toml), deser_toml_cfg(toml), deser_json(json)]
521
        }
522

            
523
        for cp in desers(r#"p = "string""#, r#"{ "p": "string" }"#) {
524
            assert_eq!(cp.as_unexpanded_str(), Some("string"));
525
            assert_eq!(cp.as_literal_path(), None);
526
        }
527

            
528
        for cp in desers(
529
            r#"p = { literal = "lit" }"#,
530
            r#"{ "p": {"literal": "lit"} }"#,
531
        ) {
532
            assert_eq!(cp.as_unexpanded_str(), None);
533
            assert_eq!(cp.as_literal_path(), Some(&*PathBuf::from("lit")));
534
        }
535
    }
536

            
537
    fn non_string_path() -> PathBuf {
538
        #[cfg(target_family = "unix")]
539
        {
540
            use std::os::unix::ffi::OsStringExt;
541
            return PathBuf::from(OsString::from_vec(vec![0x80_u8]));
542
        }
543

            
544
        #[cfg(target_family = "windows")]
545
        {
546
            use std::os::windows::ffi::OsStringExt;
547
            return PathBuf::from(OsString::from_wide(&[0xD800_u16]));
548
        }
549

            
550
        #[allow(unreachable_code)]
551
        // Cannot test non-Stringy Paths on this platform
552
        PathBuf::default()
553
    }
554

            
555
    fn test_roundtrip_cases<SER, S, DESER, E, F>(ser: SER, deser: DESER)
556
    where
557
        SER: Fn(&TestConfigFile) -> Result<S, E>,
558
        DESER: Fn(&S) -> Result<TestConfigFile, F>,
559
        S: Debug,
560
        E: Debug,
561
        F: Debug,
562
    {
563
        let case = |easy, p| {
564
            let input = TestConfigFile { p };
565
            let s = match ser(&input) {
566
                Ok(s) => s,
567
                Err(e) if easy => panic!("ser failed {:?} e={:?}", &input, &e),
568
                Err(_) => return,
569
            };
570
            dbg!(&input, &s);
571
            let output = deser(&s).expect("deser failed");
572
            assert_eq!(&input, &output, "s={:?}", &s);
573
        };
574

            
575
        case(true, CfgPath::new("string".into()));
576
        case(true, CfgPath::new_literal(PathBuf::from("nice path")));
577
        case(true, CfgPath::new_literal(PathBuf::from("path with ✓")));
578

            
579
        // Non-UTF-8 paths are really hard to serialize.  We allow the serializsaton
580
        // to fail, and if it does, we skip the rest of the round trip test.
581
        // But, if they did serialise, we want to make sure that we can deserialize.
582
        // Hence this test case.
583
        case(false, CfgPath::new_literal(non_string_path()));
584
    }
585

            
586
    #[test]
587
    fn roundtrip_json() {
588
        test_roundtrip_cases(
589
            |input| serde_json::to_string(&input),
590
            |json| serde_json::from_str(json),
591
        );
592
    }
593

            
594
    #[test]
595
    fn roundtrip_toml() {
596
        test_roundtrip_cases(|input| toml::to_string(&input), |toml| toml::from_str(toml));
597
    }
598

            
599
    #[test]
600
    fn roundtrip_mpack() {
601
        test_roundtrip_cases(
602
            |input| rmp_serde::to_vec(&input),
603
            |mpack| rmp_serde::from_slice(mpack),
604
        );
605
    }
606
}