    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

    use std::env;
    use std::error::Error;
    use std::fs;
    use std::io;
    use std::path::PathBuf;

    use crate::file::{
        format::ALL_EXTENSIONS, source::FileSourceResult, FileSource, FileStoredFormat, Format,
    };

    /// Describes a file sourced from a file
    #[derive(Clone, Debug)]
    pub struct FileSourceFile {
        /// Path of configuration file
        name: PathBuf,
    }

    impl FileSourceFile {
        pub fn new(name: PathBuf) -> Self {
            Self { name }
        }

        fn find_file<F>(
            &self,
            format_hint: Option<F>,
        ) -> Result<(PathBuf, Box<dyn Format>), Box<dyn Error + Send + Sync>>
        where
            F: FileStoredFormat + Format + 'static,
        {
            let filename = if self.name.is_absolute() {
                self.name.clone()
            } else {
                env::current_dir()?.as_path().join(&self.name)
            };

            // First check for an _exact_ match
            if filename.is_file() {
                return if let Some(format) = format_hint {
                    Ok((filename, Box::new(format)))
                } else {
                    for (format, extensions) in ALL_EXTENSIONS.iter() {
                        if extensions.contains(
                            &filename
                                .extension()
                                .unwrap_or_default()
                                .to_string_lossy()
                                .as_ref(),
                        ) {
                            return Ok((filename, Box::new(*format)));
                        }
                    }

                    Err(Box::new(io::Error::new(
                        io::ErrorKind::NotFound,
                        format!(
                            "configuration file \"{}\" is not of a registered file format",
                            filename.to_string_lossy()
                        ),
                    )))
                };
            }
            // Adding a dummy extension will make sure we will not override secondary extensions, i.e. "file.local"
            // This will make the following set_extension function calls to append the extension.
            let mut filename = add_dummy_extension(filename);

            match format_hint {
                Some(format) => {
                    for ext in format.file_extensions() {
                        filename.set_extension(ext);

                        if filename.is_file() {
                            return Ok((filename, Box::new(format)));
                        }
                    }
                }

                None => {
                    for format in ALL_EXTENSIONS.keys() {
                        for ext in format.extensions() {
                            filename.set_extension(ext);

                            if filename.is_file() {
                                return Ok((filename, Box::new(*format)));
                            }
                        }
                    }
                }
            }

            Err(Box::new(io::Error::new(
                io::ErrorKind::NotFound,
                format!(
                    "configuration file \"{}\" not found",
                    self.name.to_string_lossy()
                ),
            )))
        }
    }

    impl<F> FileSource<F> for FileSourceFile
    where
        F: Format + FileStoredFormat + 'static,
    {
        fn resolve(
            &self,
            format_hint: Option<F>,
        ) -> Result<FileSourceResult, Box<dyn Error + Send + Sync>> {
            // Find file
            let (filename, format) = self.find_file(format_hint)?;

            // Attempt to use a relative path for the URI
            let uri = env::current_dir()
                .ok()
                .and_then(|base| pathdiff::diff_paths(&filename, base))
                .unwrap_or_else(|| filename.clone());

            // Read contents from file
            let text = fs::read_to_string(filename)?;

            Ok(FileSourceResult {
                uri: Some(uri.to_string_lossy().into_owned()),
                content: text,
                format,
            })
        }
    }

    fn add_dummy_extension(mut filename: PathBuf) -> PathBuf {
        match filename.extension() {
            Some(extension) => {
                let mut ext = extension.to_os_string();
                ext.push(".");
                ext.push("dummy");
                filename.set_extension(ext);
            }
            None => {
                filename.set_extension("dummy");
            }
        }
        filename
    }