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
use crate::{Encoding, Error, PathExt, Result};
use std::fmt;
use std::fs;
use std::io::{self, BufRead, BufReader, Cursor, Read};
use std::path::{Path, PathBuf};
use std::str::FromStr;
use url::Url;

/// A source for data that needs to be deserialized.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Source {
    /// Stdin source.
    Stdin,
    /// Local file or directory source.
    Path(PathBuf),
    /// Remote URL source.
    Url(Url),
}

impl Source {
    /// Returns `Some` if the source is a local path, `None` otherwise.
    pub fn as_path(&self) -> Option<&Path> {
        match self {
            Self::Path(path) => Some(path),
            _ => None,
        }
    }

    /// Returns `true` if the `Source` is a local path and the path exists on disk and is pointing
    /// at a directory.
    pub fn is_dir(&self) -> bool {
        self.as_path().map(|path| path.is_dir()).unwrap_or(false)
    }

    /// Tries to detect the encoding of the source. Returns `None` if the encoding cannot be
    /// detected.
    pub fn encoding(&self) -> Option<Encoding> {
        match self {
            Self::Stdin => None,
            Self::Path(path) => Encoding::from_path(path),
            Self::Url(url) => Encoding::from_path(url.as_str()),
        }
    }

    /// If source is a local path, this returns sources for all files matching the glob pattern.
    ///
    /// ## Errors
    ///
    /// Returns an error if the sink is not of variant `Sink::Path`, the pattern is invalid or if
    /// there is a `io::Error` while reading the file system.
    pub fn glob_files(&self, pattern: &str) -> Result<Vec<Source>> {
        match self.as_path() {
            Some(path) => Ok(path
                .glob_files(pattern)?
                .iter()
                .map(|path| Self::from(path.as_path()))
                .collect()),
            None => Err(Error::new("not a path source")),
        }
    }

    /// Returns a `SourceReader` to read from the source.
    ///
    /// ## Errors
    ///
    /// May return an error if the source is `Source::Path` and the file cannot be opened of if
    /// source is `Source::Url` and there is an error requesting the remote url.
    pub fn to_reader(&self) -> Result<SourceReader> {
        let reader: Box<dyn io::Read> = match self {
            Self::Stdin => Box::new(io::stdin()),
            Self::Path(path) => Box::new(fs::File::open(path)?),
            Self::Url(url) => Box::new(ureq::get(url.as_ref()).call()?.into_reader()),
        };

        SourceReader::new(reader, self.encoding())
    }
}

impl From<&str> for Source {
    fn from(s: &str) -> Self {
        if s == "-" {
            Self::Stdin
        } else {
            if let Ok(url) = Url::parse(s) {
                if url.scheme() != "file" {
                    return Self::Url(url);
                }
            }

            Self::Path(PathBuf::from(s))
        }
    }
}

impl From<&Path> for Source {
    fn from(path: &Path) -> Self {
        Self::Path(path.to_path_buf())
    }
}

impl FromStr for Source {
    type Err = std::convert::Infallible;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(From::from(s))
    }
}

impl fmt::Display for Source {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Stdin => write!(f, "<stdin>"),
            Self::Url(url) => url.fmt(f),
            Self::Path(path) => path
                .relative_to_cwd()
                .unwrap_or_else(|| path.clone())
                .display()
                .fmt(f),
        }
    }
}

/// A type that can read from a `Source`. It is able to detect the `Source`'s encoding by looking
/// at the first line of the input.
pub struct SourceReader {
    first_line: Cursor<Vec<u8>>,
    remainder: BufReader<Box<dyn Read>>,
    encoding: Option<Encoding>,
}

impl SourceReader {
    /// Creates a new `SourceReader` for an `io::Read` implementation and an optional encoding
    /// hint.
    ///
    /// Reads the first line from `reader` upon creation.
    ///
    /// ## Errors
    ///
    /// Returns an error if reading the first line from the reader fails.
    pub fn new(reader: Box<dyn Read>, encoding: Option<Encoding>) -> Result<SourceReader> {
        let mut remainder = BufReader::new(reader);
        let mut buf = Vec::new();

        remainder.read_until(b'\n', &mut buf)?;

        let first_line = Cursor::new(buf);

        Ok(SourceReader {
            first_line,
            remainder,
            encoding,
        })
    }

    /// Tries to detect the encoding of the source. If the source provides an encoding hint it is
    /// returned as is. Otherwise the `SourceReader` attempts to detect the encoding based on the
    /// contents of the first line of the input data.
    ///
    /// Returns `None` if the encoding cannot be detected.
    pub fn encoding(&self) -> Option<Encoding> {
        self.encoding.or_else(|| {
            std::str::from_utf8(self.first_line.get_ref())
                .ok()
                .and_then(Encoding::from_first_line)
        })
    }
}

impl Read for SourceReader {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        if self.first_line.position() < self.first_line.get_ref().len() as u64 {
            self.first_line.read(buf)
        } else {
            self.remainder.read(buf)
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use pretty_assertions::assert_eq;

    #[test]
    fn test_from_str() {
        assert_eq!(Source::from_str("-"), Ok(Source::Stdin));
        assert_eq!(
            Source::from_str("foo.json"),
            Ok(Source::Path(PathBuf::from("foo.json")))
        );
        assert_eq!(
            Source::from_str("http://localhost/foo.json"),
            Ok(Source::Url(
                Url::from_str("http://localhost/foo.json").unwrap()
            ))
        );
    }

    #[test]
    fn test_encoding() {
        assert_eq!(Source::from("-").encoding(), None);
        assert_eq!(Source::from("foo").encoding(), None);
        assert_eq!(Source::from("foo.json").encoding(), Some(Encoding::Json));
        assert_eq!(
            Source::from("http://localhost/bar.yaml").encoding(),
            Some(Encoding::Yaml)
        );
    }

    #[test]
    fn test_to_string() {
        assert_eq!(&Source::Stdin.to_string(), "<stdin>");
        assert_eq!(&Source::from("Cargo.toml").to_string(), "Cargo.toml");
        assert_eq!(
            &Source::from(std::fs::canonicalize("src/lib.rs").unwrap().as_path()).to_string(),
            "src/lib.rs"
        );
        assert_eq!(
            &Source::from("/non-existent/path").to_string(),
            "/non-existent/path"
        );
        assert_eq!(
            &Source::from("http://localhost/bar.yaml").to_string(),
            "http://localhost/bar.yaml",
        );
    }

    #[test]
    fn test_glob_files() {
        assert!(Source::from("src/")
            .glob_files("*.rs")
            .unwrap()
            .contains(&Source::from("src/lib.rs")));
        assert!(Source::from("-").glob_files("*.json").is_err());
        assert!(Source::from("http://localhost/")
            .glob_files("*.json")
            .is_err(),);
        assert!(matches!(
            Source::from("src/").glob_files("***"),
            Err(Error::GlobPatternError { .. })
        ));
    }

    #[test]
    fn test_source_reader() {
        let input = Cursor::new("---\nfoo: bar\n");
        let mut reader = SourceReader::new(Box::new(input), None).unwrap();

        assert_eq!(reader.encoding(), Some(Encoding::Yaml));

        let mut buf = String::new();
        reader.read_to_string(&mut buf).unwrap();

        assert_eq!(&buf, "---\nfoo: bar\n");
    }
}