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
use std::convert::TryFrom;
use std::fs;
use std::fs::File;
use std::io::{self, BufRead, BufReader, Read};
use std::path::{Path, PathBuf};
use clircle::{Clircle, Identifier};
use content_inspector::{self, ContentType};
use crate::error::*;
#[derive(Clone)]
pub struct InputDescription {
pub(crate) name: String,
title: Option<String>,
kind: Option<String>,
summary: Option<String>,
}
impl InputDescription {
pub fn new(name: impl Into<String>) -> Self {
InputDescription {
name: name.into(),
title: None,
kind: None,
summary: None,
}
}
pub fn set_kind(&mut self, kind: Option<String>) {
self.kind = kind;
}
pub fn set_summary(&mut self, summary: Option<String>) {
self.summary = summary;
}
pub fn set_title(&mut self, title: Option<String>) {
self.title = title;
}
pub fn title(&self) -> &String {
match &self.title {
Some(title) => title,
None => &self.name,
}
}
pub fn kind(&self) -> Option<&String> {
self.kind.as_ref()
}
pub fn summary(&self) -> String {
self.summary.clone().unwrap_or_else(|| match &self.kind {
None => self.name.clone(),
Some(kind) => format!("{} '{}'", kind.to_lowercase(), self.name),
})
}
}
pub(crate) enum InputKind<'a> {
OrdinaryFile(PathBuf),
StdIn,
CustomReader(Box<dyn Read + 'a>),
}
impl<'a> InputKind<'a> {
pub fn description(&self) -> InputDescription {
match self {
InputKind::OrdinaryFile(ref path) => InputDescription::new(path.to_string_lossy()),
InputKind::StdIn => InputDescription::new("STDIN"),
InputKind::CustomReader(_) => InputDescription::new("READER"),
}
}
}
#[derive(Clone, Default)]
pub(crate) struct InputMetadata {
pub(crate) user_provided_name: Option<PathBuf>,
pub(crate) size: Option<u64>,
}
pub struct Input<'a> {
pub(crate) kind: InputKind<'a>,
pub(crate) metadata: InputMetadata,
pub(crate) description: InputDescription,
}
pub(crate) enum OpenedInputKind {
OrdinaryFile(PathBuf),
StdIn,
CustomReader,
}
pub(crate) struct OpenedInput<'a> {
pub(crate) kind: OpenedInputKind,
pub(crate) metadata: InputMetadata,
pub(crate) reader: InputReader<'a>,
pub(crate) description: InputDescription,
}
impl OpenedInput<'_> {
pub(crate) fn path(&self) -> Option<&PathBuf> {
self.metadata
.user_provided_name
.as_ref()
.or(match self.kind {
OpenedInputKind::OrdinaryFile(ref path) => Some(path),
_ => None,
})
}
}
impl<'a> Input<'a> {
pub fn ordinary_file(path: impl AsRef<Path>) -> Self {
Self::_ordinary_file(path.as_ref())
}
fn _ordinary_file(path: &Path) -> Self {
let kind = InputKind::OrdinaryFile(path.to_path_buf());
let metadata = InputMetadata {
size: fs::metadata(path).map(|m| m.len()).ok(),
..InputMetadata::default()
};
Input {
description: kind.description(),
metadata,
kind,
}
}
pub fn stdin() -> Self {
let kind = InputKind::StdIn;
Input {
description: kind.description(),
metadata: InputMetadata::default(),
kind,
}
}
pub fn from_reader(reader: Box<dyn Read + 'a>) -> Self {
let kind = InputKind::CustomReader(reader);
Input {
description: kind.description(),
metadata: InputMetadata::default(),
kind,
}
}
pub fn is_stdin(&self) -> bool {
matches!(self.kind, InputKind::StdIn)
}
pub fn with_name(self, provided_name: Option<impl AsRef<Path>>) -> Self {
self._with_name(provided_name.as_ref().map(|it| it.as_ref()))
}
fn _with_name(mut self, provided_name: Option<&Path>) -> Self {
if let Some(name) = provided_name {
self.description.name = name.to_string_lossy().to_string()
}
self.metadata.user_provided_name = provided_name.map(|n| n.to_owned());
self
}
pub fn description(&self) -> &InputDescription {
&self.description
}
pub fn description_mut(&mut self) -> &mut InputDescription {
&mut self.description
}
pub(crate) fn open<R: BufRead + 'a>(
self,
stdin: R,
stdout_identifier: Option<&Identifier>,
) -> Result<OpenedInput<'a>> {
let description = self.description().clone();
match self.kind {
InputKind::StdIn => {
if let Some(stdout) = stdout_identifier {
let input_identifier = Identifier::try_from(clircle::Stdio::Stdin)
.map_err(|e| format!("Stdin: Error identifying file: {}", e))?;
if stdout.surely_conflicts_with(&input_identifier) {
return Err("IO circle detected. The input from stdin is also an output. Aborting to avoid infinite loop.".into());
}
}
Ok(OpenedInput {
kind: OpenedInputKind::StdIn,
description,
metadata: self.metadata,
reader: InputReader::new(stdin),
})
}
InputKind::OrdinaryFile(path) => Ok(OpenedInput {
kind: OpenedInputKind::OrdinaryFile(path.clone()),
description,
metadata: self.metadata,
reader: {
let mut file = File::open(&path)
.map_err(|e| format!("'{}': {}", path.to_string_lossy(), e))?;
if file.metadata()?.is_dir() {
return Err(format!("'{}' is a directory.", path.to_string_lossy()).into());
}
if let Some(stdout) = stdout_identifier {
let input_identifier = Identifier::try_from(file).map_err(|e| {
format!("{}: Error identifying file: {}", path.to_string_lossy(), e)
})?;
if stdout.surely_conflicts_with(&input_identifier) {
return Err(format!(
"IO circle detected. The input from '{}' is also an output. Aborting to avoid infinite loop.",
path.to_string_lossy()
)
.into());
}
file = input_identifier.into_inner().expect("The file was lost in the clircle::Identifier, this should not have happened...");
}
InputReader::new(BufReader::new(file))
},
}),
InputKind::CustomReader(reader) => Ok(OpenedInput {
description,
kind: OpenedInputKind::CustomReader,
metadata: self.metadata,
reader: InputReader::new(BufReader::new(reader)),
}),
}
}
}
pub(crate) struct InputReader<'a> {
inner: Box<dyn BufRead + 'a>,
pub(crate) first_line: Vec<u8>,
pub(crate) content_type: Option<ContentType>,
}
impl<'a> InputReader<'a> {
fn new<R: BufRead + 'a>(mut reader: R) -> InputReader<'a> {
let mut first_line = vec![];
reader.read_until(b'\n', &mut first_line).ok();
let content_type = if first_line.is_empty() {
None
} else {
Some(content_inspector::inspect(&first_line[..]))
};
if content_type == Some(ContentType::UTF_16LE) {
reader.read_until(0x00, &mut first_line).ok();
}
InputReader {
inner: Box::new(reader),
first_line,
content_type,
}
}
pub(crate) fn read_line(&mut self, buf: &mut Vec<u8>) -> io::Result<bool> {
if !self.first_line.is_empty() {
buf.append(&mut self.first_line);
return Ok(true);
}
let res = self.inner.read_until(b'\n', buf).map(|size| size > 0)?;
if self.content_type == Some(ContentType::UTF_16LE) {
let _ = self.inner.read_until(0x00, buf);
}
Ok(res)
}
}
#[test]
fn basic() {
let content = b"#!/bin/bash\necho hello";
let mut reader = InputReader::new(&content[..]);
assert_eq!(b"#!/bin/bash\n", &reader.first_line[..]);
let mut buffer = vec![];
let res = reader.read_line(&mut buffer);
assert!(res.is_ok());
assert!(res.unwrap());
assert_eq!(b"#!/bin/bash\n", &buffer[..]);
buffer.clear();
let res = reader.read_line(&mut buffer);
assert!(res.is_ok());
assert!(res.unwrap());
assert_eq!(b"echo hello", &buffer[..]);
buffer.clear();
let res = reader.read_line(&mut buffer);
assert!(res.is_ok());
assert!(!res.unwrap());
assert!(buffer.is_empty());
}
#[test]
fn utf16le() {
let content = b"\xFF\xFE\x73\x00\x0A\x00\x64\x00";
let mut reader = InputReader::new(&content[..]);
assert_eq!(b"\xFF\xFE\x73\x00\x0A\x00", &reader.first_line[..]);
let mut buffer = vec![];
let res = reader.read_line(&mut buffer);
assert!(res.is_ok());
assert!(res.unwrap());
assert_eq!(b"\xFF\xFE\x73\x00\x0A\x00", &buffer[..]);
buffer.clear();
let res = reader.read_line(&mut buffer);
assert!(res.is_ok());
assert!(res.unwrap());
assert_eq!(b"\x64\x00", &buffer[..]);
buffer.clear();
let res = reader.read_line(&mut buffer);
assert!(res.is_ok());
assert!(!res.unwrap());
assert!(buffer.is_empty());
}