forked from tweag/topiary
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathio.rs
365 lines (309 loc) · 11.1 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
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
use std::{
ffi::OsString,
fmt::{self, Display},
fs::File,
io::{self, Read, Result, Seek, Write},
path::PathBuf,
};
use tempfile::tempfile;
use topiary_config::Configuration;
use topiary_core::{Language, TopiaryQuery};
use crate::{
cli::{AtLeastOneInput, ExactlyOneInput, FromStdin},
error::{CLIError, CLIResult, TopiaryError},
};
#[derive(Debug, Clone, Hash)]
pub enum QuerySource {
Path(PathBuf),
BuiltIn(String),
}
impl From<PathBuf> for QuerySource {
fn from(path: PathBuf) -> Self {
QuerySource::Path(path)
}
}
impl From<&PathBuf> for QuerySource {
fn from(path: &PathBuf) -> Self {
QuerySource::Path(path.clone())
}
}
impl From<&str> for QuerySource {
fn from(string: &str) -> Self {
QuerySource::BuiltIn(String::from(string))
}
}
impl Display for QuerySource {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
QuerySource::Path(p) => write!(f, "{}", p.to_string_lossy()),
QuerySource::BuiltIn(_) => write!(f, "built-in query"),
}
}
}
/// 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(String, Option<QuerySource>),
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.as_ref().map(|p| p.into())),
ExactlyOneInput {
file: Some(path), ..
} => InputFrom::Files(vec![path.to_owned()]),
_ => unreachable!("Clap guarantees input is always one of the above"),
}
}
}
impl From<&AtLeastOneInput> for InputFrom {
fn from(input: &AtLeastOneInput) -> Self {
match input {
AtLeastOneInput {
stdin: Some(FromStdin { language, query }),
..
} => InputFrom::Stdin(language.to_owned(), query.as_ref().map(|p| p.into())),
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 topiary_config::language::Language,
query: QuerySource,
}
impl InputFile<'_> {
/// Convert our `InputFile` into language definition values that Topiary can consume
pub async fn to_language(&self) -> CLIResult<Language> {
let grammar = self.language().grammar()?;
let contents = match &self.query {
QuerySource::Path(query) => tokio::fs::read_to_string(query).await?,
QuerySource::BuiltIn(contents) => contents.to_owned(),
};
let query = TopiaryQuery::new(&grammar, &contents)?;
Ok(Language {
name: self.language.name.clone(),
query,
grammar,
indent: self.language().config.indent.clone(),
})
}
/// Expose input source
pub fn source(&self) -> &InputSource {
&self.source
}
/// Expose language for input
pub fn language(&self) -> &topiary_config::language::Language {
self.language
}
/// Expose query path for input
pub fn query(&self) -> &QuerySource {
&self.query
}
}
impl Read for InputFile<'_> {
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
match &mut self.source {
InputSource::Stdin => io::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_name, query) => {
vec![(|| {
let language = config.get_language(&language_name)?;
let query_source: QuerySource = match query {
// The user specified a query file
Some(p) => p,
// The user did not specify a file, try the default locations
None => to_query_from_language(language)?,
};
Ok(InputFile {
source: InputSource::Stdin,
language,
query: query_source,
})
})()]
}
InputFrom::Files(files) => files
.into_iter()
.map(|path| {
let language = config.detect(&path)?;
let query: QuerySource = to_query_from_language(language)?;
Ok(InputFile {
source: InputSource::Disk(path, None),
language,
query,
})
})
.collect(),
};
Self(inputs)
}
}
fn to_query_from_language(language: &topiary_config::language::Language) -> CLIResult<QuerySource> {
let query: QuerySource = match language.find_query_file() {
Ok(p) => p.into(),
// For some reason, Topiary could not find any
// matching file in a default location. As a final attempt, try the
// builtin ones. Store the error, return that if we
// fail to find anything, because the builtin error might be unexpected.
Err(e) => {
log::warn!("No query files found in any of the expected locations. Falling back to compile-time included files.");
to_query(&language.name).map_err(|_| e)?
}
};
Ok(query)
}
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: File,
output: OsString,
},
}
impl OutputFile {
pub fn new(path: &str) -> CLIResult<Self> {
match path {
"-" => Ok(Self::Stdout),
file => Ok(Self::Disk {
staged: tempfile()?,
output: file.into(),
}),
}
}
// This function must be called to persist the output to disk
pub fn persist(self) -> CLIResult<()> {
if let Self::Disk { mut staged, output } = self {
// Rewind to the beginning of the staged output
staged.flush()?;
staged.rewind()?;
// Open the actual output for writing and copy the staged contents
let mut writer = File::create(&output)?;
let bytes = io::copy(&mut staged, &mut writer)?;
log::debug!("Wrote {bytes} bytes to {}", &output.to_string_lossy());
}
Ok(())
}
}
impl fmt::Display for OutputFile {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Stdout => write!(f, "standard output"),
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 => io::stdout().lock().write(buf),
Self::Disk { staged, .. } => staged.write(buf),
}
}
fn flush(&mut self) -> Result<()> {
match self {
Self::Stdout => io::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 TryFrom<&InputFile<'_>> 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()),
}
}
}
fn to_query<T>(name: T) -> CLIResult<QuerySource>
where
T: AsRef<str> + fmt::Display,
{
match name.as_ref() {
#[cfg(feature = "bash")]
"bash" => Ok(topiary_queries::bash().into()),
#[cfg(feature = "css")]
"css" => Ok(topiary_queries::css().into()),
#[cfg(feature = "json")]
"json" => Ok(topiary_queries::json().into()),
#[cfg(feature = "nickel")]
"nickel" => Ok(topiary_queries::nickel().into()),
#[cfg(feature = "ocaml")]
"ocaml" => Ok(topiary_queries::ocaml().into()),
#[cfg(feature = "ocaml_interface")]
"ocaml_interface" => Ok(topiary_queries::ocaml_interface().into()),
#[cfg(feature = "ocamllex")]
"ocamllex" => Ok(topiary_queries::ocamllex().into()),
#[cfg(feature = "openscad")]
"openscad" => Ok(topiary_queries::openscad().into()),
#[cfg(feature = "rust")]
"rust" => Ok(topiary_queries::rust().into()),
#[cfg(feature = "toml")]
"toml" => Ok(topiary_queries::toml().into()),
#[cfg(feature = "tree_sitter_query")]
"tree_sitter_query" => Ok(topiary_queries::tree_sitter_query().into()),
name => Err(TopiaryError::Bin(
format!("The specified language is unsupported: {}", name),
Some(CLIError::UnsupportedLanguage(name.to_string())),
)),
}
}