generated from tweag/project
-
Notifications
You must be signed in to change notification settings - Fork 30
/
io.rs
272 lines (233 loc) · 8.13 KB
/
io.rs
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
use std::{
ffi::OsString,
fmt,
fs::File,
io::{stdin, stdout, ErrorKind, Read, Result, Write},
path::{Path, PathBuf},
};
use tempfile::NamedTempFile;
use topiary::{Configuration, Language, SupportedLanguage, TopiaryQuery};
use crate::{
cli::{AtLeastOneInput, ExactlyOneInput, FromStdin},
error::{CLIResult, TopiaryError},
language::LanguageDefinition,
};
type QueryPath = PathBuf;
/// Unified interface for input sources. We either have input from:
/// * Standard input, in which case we need to specify the language and, optionally, query override
/// * A sequence of files
///
/// These are captured by the CLI parser, with `cli::AtLeastOneInput` and `cli::ExactlyOneInput`.
/// We use this struct to normalise the interface for downstream (using `From` implementations).
pub enum InputFrom {
Stdin(SupportedLanguage, Option<QueryPath>),
Files(Vec<PathBuf>),
}
impl From<&ExactlyOneInput> for InputFrom {
fn from(input: &ExactlyOneInput) -> Self {
match input {
ExactlyOneInput {
stdin: Some(FromStdin { language, query }),
..
} => InputFrom::Stdin(language.to_owned(), query.to_owned()),
ExactlyOneInput {
file: Some(path), ..
} => InputFrom::Files(vec![path.to_owned()]),
// We're guaranteed (by clap) to have at least one of the above
_ => unreachable!(),
}
}
}
impl From<&AtLeastOneInput> for InputFrom {
fn from(input: &AtLeastOneInput) -> Self {
match input {
AtLeastOneInput {
stdin: Some(FromStdin { language, query }),
..
} => InputFrom::Stdin(language.to_owned(), query.to_owned()),
AtLeastOneInput { files, .. } => InputFrom::Files(files.to_owned()),
}
}
}
/// Each `InputFile` needs to locate its source (standard input or disk), such that its `io::Read`
/// implementation can do the right thing.
#[derive(Debug)]
pub enum InputSource {
Stdin,
Disk(PathBuf, Option<File>),
}
impl fmt::Display for InputSource {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Stdin => write!(f, "standard input"),
Self::Disk(path, _) => write!(f, "{}", path.to_string_lossy()),
}
}
}
/// An `InputFile` is the unit of input for Topiary, encapsulating everything needed for downstream
/// processing. It implements `io::Read`, so it can be passed directly to the Topiary API.
#[derive(Debug)]
pub struct InputFile<'cfg> {
source: InputSource,
language: &'cfg Language,
query: QueryPath,
}
impl<'cfg> InputFile<'cfg> {
/// Convert our `InputFile` into language definition values that Topiary can consume
pub async fn to_language_definition(&self) -> CLIResult<LanguageDefinition> {
let grammar = self.language.grammar().await?;
let query = {
let contents = tokio::fs::read_to_string(&self.query).await?;
TopiaryQuery::new(&grammar, &contents)?
};
Ok(LanguageDefinition {
query,
language: self.language.clone(),
grammar,
})
}
/// Expose input source
pub fn source(&self) -> &InputSource {
&self.source
}
/// Expose language for input
pub fn language(&self) -> &Language {
self.language
}
/// Expose query path for input
pub fn query(&self) -> &PathBuf {
&self.query
}
}
impl<'cfg> Read for InputFile<'cfg> {
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
match &mut self.source {
InputSource::Stdin => stdin().lock().read(buf),
InputSource::Disk(path, fd) => {
if fd.is_none() {
*fd = Some(File::open(path)?);
}
fd.as_mut().unwrap().read(buf)
}
}
}
}
/// `Inputs` is an iterator of fully qualified `InputFile`s, each wrapped in `CLIResult`, which is
/// populated by its constructor from any type that implements `Into<InputFrom>`
pub struct Inputs<'cfg>(Vec<CLIResult<InputFile<'cfg>>>);
impl<'cfg, 'i> Inputs<'cfg> {
pub fn new<T>(config: &'cfg Configuration, inputs: &'i T) -> Self
where
&'i T: Into<InputFrom>,
{
let inputs = match inputs.into() {
InputFrom::Stdin(language, query) => {
vec![(|| {
let language = language.to_language(config);
let query = query.unwrap_or(language.query_file()?);
Ok(InputFile {
source: InputSource::Stdin,
language,
query,
})
})()]
}
InputFrom::Files(files) => files
.into_iter()
.map(|path| {
let language = Language::detect(&path, config)?;
let query = language.query_file()?;
Ok(InputFile {
source: InputSource::Disk(path, None),
language,
query,
})
})
.collect(),
};
Self(inputs)
}
}
impl<'cfg> Iterator for Inputs<'cfg> {
type Item = CLIResult<InputFile<'cfg>>;
fn next(&mut self) -> Option<Self::Item> {
self.0.pop()
}
}
/// An `OutputFile` is the unit of output for Topiary, differentiating between standard output and
/// disk (which uses temporary files to perform atomic updates in place). It implements
/// `io::Write`, so it can be passed directly to the Topiary API.
///
/// NOTE When writing to disk, the `persist` function must be called to perform the in place write.
#[derive(Debug)]
pub enum OutputFile {
Stdout,
Disk {
// NOTE We stage to a file, rather than writing
// to memory (e.g., Vec<u8>), to ensure atomicity
staged: NamedTempFile,
output: OsString,
},
}
impl OutputFile {
pub fn new(path: &str) -> CLIResult<Self> {
match path {
"-" => Ok(Self::Stdout),
file => {
// `canonicalize` if the given path exists, otherwise fallback to what was given
let path = Path::new(file).canonicalize().or_else(|e| match e.kind() {
ErrorKind::NotFound => Ok(file.into()),
_ => Err(e),
})?;
// The call to `parent` will only return `None` if `path` is the root directory,
// but that doesn't make sense as an output file, so unwrapping is safe
let parent = path.parent().unwrap();
Ok(Self::Disk {
staged: NamedTempFile::new_in(parent)?,
output: file.into(),
})
}
}
}
// This function must be called to persist the output to disk
pub fn persist(self) -> CLIResult<()> {
if let Self::Disk { staged, output } = self {
staged.persist(output)?;
}
Ok(())
}
}
impl fmt::Display for OutputFile {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Stdout => write!(f, "standard ouput"),
Self::Disk { output, .. } => write!(f, "{}", output.to_string_lossy()),
}
}
}
impl Write for OutputFile {
fn write(&mut self, buf: &[u8]) -> Result<usize> {
match self {
Self::Stdout => stdout().lock().write(buf),
Self::Disk { staged, .. } => staged.write(buf),
}
}
fn flush(&mut self) -> Result<()> {
match self {
Self::Stdout => stdout().lock().flush(),
Self::Disk { staged, .. } => staged.flush(),
}
}
}
// Convenience conversion:
// * stdin maps to stdout
// * Files map to themselves (i.e., for in-place updates)
impl<'cfg> TryFrom<&InputFile<'cfg>> for OutputFile {
type Error = TopiaryError;
fn try_from(input: &InputFile) -> CLIResult<Self> {
match &input.source {
InputSource::Stdin => Ok(Self::Stdout),
InputSource::Disk(path, _) => Self::new(path.to_string_lossy().as_ref()),
}
}
}