on 206bf5b help sign in
bat/src/input.rs
345 lines 10 kB history raw
1use std::convert::TryFrom;
2use std::fs::File;
3use std::io::{self, BufRead, BufReader, Read};
4use std::path::{Path, PathBuf};
6use clircle::{Clircle, Identifier};
7use content_inspector::{self, ContentType};
9use crate::error::*;
11/// A description of an Input source.
12/// This tells bat how to refer to the input.
13#[derive(Clone)]
14pub struct InputDescription {
15 pub(crate) name: String,
17 /// The input title.
18 /// This replaces the name if provided.
19 title: Option<String>,
21 /// The input kind.
22 kind: Option<String>,
24 /// A summary description of the input.
25 /// Defaults to "{kind} '{name}'"
26 summary: Option<String>,
29impl InputDescription {
30 /// Creates a description for an input.
31 pub fn new(name: impl Into<String>) -> Self {
32 InputDescription {
33 name: name.into(),
34 title: None,
35 kind: None,
36 summary: None,
37 }
38 }
40 pub fn set_kind(&mut self, kind: Option<String>) {
41 self.kind = kind;
42 }
44 pub fn set_summary(&mut self, summary: Option<String>) {
45 self.summary = summary;
46 }
48 pub fn set_title(&mut self, title: Option<String>) {
49 self.title = title;
50 }
52 pub fn title(&self) -> &String {
53 match &self.title {
54 Some(title) => title,
55 None => &self.name,
56 }
57 }
59 pub fn kind(&self) -> Option<&String> {
60 self.kind.as_ref()
61 }
63 pub fn summary(&self) -> String {
64 self.summary.clone().unwrap_or_else(|| match &self.kind {
65 None => self.name.clone(),
66 Some(kind) => format!("{} '{}'", kind.to_lowercase(), self.name),
67 })
68 }
71pub(crate) enum InputKind<'a> {
72 OrdinaryFile(PathBuf),
73 StdIn,
74 CustomReader(Box<dyn Read + 'a>),
77impl<'a> InputKind<'a> {
78 pub fn description(&self) -> InputDescription {
79 match self {
80 InputKind::OrdinaryFile(ref path) => InputDescription::new(path.to_string_lossy()),
81 InputKind::StdIn => InputDescription::new("STDIN"),
82 InputKind::CustomReader(_) => InputDescription::new("READER"),
83 }
84 }
87#[derive(Clone, Default)]
88pub(crate) struct InputMetadata {
89 pub(crate) user_provided_name: Option<PathBuf>,
92pub struct Input<'a> {
93 pub(crate) kind: InputKind<'a>,
94 pub(crate) metadata: InputMetadata,
95 pub(crate) description: InputDescription,
98pub(crate) enum OpenedInputKind {
99 OrdinaryFile(PathBuf),
100 StdIn,
101 CustomReader,
104pub(crate) struct OpenedInput<'a> {
105 pub(crate) kind: OpenedInputKind,
106 pub(crate) metadata: InputMetadata,
107 pub(crate) reader: InputReader<'a>,
108 pub(crate) description: InputDescription,
111impl OpenedInput<'_> {
112 /// Get the path of the file:
113 /// If this was set by the metadata, that will take priority.
114 /// If it wasn't, it will use the real file path (if available).
115 pub(crate) fn path(&self) -> Option<&PathBuf> {
116 self.metadata
117 .user_provided_name
118 .as_ref()
119 .or_else(|| match self.kind {
120 OpenedInputKind::OrdinaryFile(ref path) => Some(path),
121 _ => None,
122 })
123 }
126impl<'a> Input<'a> {
127 pub fn ordinary_file(path: impl AsRef<Path>) -> Self {
128 Self::_ordinary_file(path.as_ref())
129 }
131 fn _ordinary_file(path: &Path) -> Self {
132 let kind = InputKind::OrdinaryFile(path.to_path_buf());
133 Input {
134 description: kind.description(),
135 metadata: InputMetadata::default(),
136 kind,
137 }
138 }
140 pub fn stdin() -> Self {
141 let kind = InputKind::StdIn;
142 Input {
143 description: kind.description(),
144 metadata: InputMetadata::default(),
145 kind,
146 }
147 }
149 pub fn from_reader(reader: Box<dyn Read + 'a>) -> Self {
150 let kind = InputKind::CustomReader(reader);
151 Input {
152 description: kind.description(),
153 metadata: InputMetadata::default(),
154 kind,
155 }
156 }
158 pub fn is_stdin(&self) -> bool {
159 matches!(self.kind, InputKind::StdIn)
160 }
162 pub fn with_name(self, provided_name: Option<impl AsRef<Path>>) -> Self {
163 self._with_name(provided_name.as_ref().map(|it| it.as_ref()))
164 }
166 fn _with_name(mut self, provided_name: Option<&Path>) -> Self {
167 if let Some(name) = provided_name {
168 self.description.name = name.to_string_lossy().to_string()
169 }
171 self.metadata.user_provided_name = provided_name.map(|n| n.to_owned());
172 self
173 }
175 pub fn description(&self) -> &InputDescription {
176 &self.description
177 }
179 pub fn description_mut(&mut self) -> &mut InputDescription {
180 &mut self.description
181 }
183 pub(crate) fn open<R: BufRead + 'a>(
184 self,
185 stdin: R,
186 stdout_identifier: Option<&Identifier>,
187 ) -> Result<OpenedInput<'a>> {
188 let description = self.description().clone();
189 match self.kind {
190 InputKind::StdIn => {
191 if let Some(stdout) = stdout_identifier {
192 let input_identifier = Identifier::try_from(clircle::Stdio::Stdin)
193 .map_err(|e| format!("Stdin: Error identifying file: {}", e))?;
194 if stdout.surely_conflicts_with(&input_identifier) {
195 return Err("IO circle detected. The input from stdin is also an output. Aborting to avoid infinite loop.".into());
196 }
197 }
199 Ok(OpenedInput {
200 kind: OpenedInputKind::StdIn,
201 description,
202 metadata: self.metadata,
203 reader: InputReader::new(stdin),
204 })
205 }
207 InputKind::OrdinaryFile(path) => Ok(OpenedInput {
208 kind: OpenedInputKind::OrdinaryFile(path.clone()),
209 description,
210 metadata: self.metadata,
211 reader: {
212 let mut file = File::open(&path)
213 .map_err(|e| format!("'{}': {}", path.to_string_lossy(), e))?;
214 if file.metadata()?.is_dir() {
215 return Err(format!("'{}' is a directory.", path.to_string_lossy()).into());
216 }
218 if let Some(stdout) = stdout_identifier {
219 let input_identifier = Identifier::try_from(file).map_err(|e| {
220 format!("{}: Error identifying file: {}", path.to_string_lossy(), e)
221 })?;
222 if stdout.surely_conflicts_with(&input_identifier) {
223 return Err(format!(
224 "IO circle detected. The input from '{}' is also an output. Aborting to avoid infinite loop.",
225 path.to_string_lossy()
226 )
227 .into());
228 }
229 file = input_identifier.into_inner().expect("The file was lost in the clircle::Identifier, this should not have happened...");
230 }
232 InputReader::new(BufReader::new(file))
233 },
234 }),
235 InputKind::CustomReader(reader) => Ok(OpenedInput {
236 description,
237 kind: OpenedInputKind::CustomReader,
238 metadata: self.metadata,
239 reader: InputReader::new(BufReader::new(reader)),
240 }),
241 }
242 }
245pub(crate) struct InputReader<'a> {
246 inner: Box<dyn BufRead + 'a>,
247 pub(crate) first_line: Vec<u8>,
248 pub(crate) content_type: Option<ContentType>,
251impl<'a> InputReader<'a> {
252 fn new<R: BufRead + 'a>(mut reader: R) -> InputReader<'a> {
253 let mut first_line = vec![];
254 reader.read_until(b'\n', &mut first_line).ok();
256 let content_type = if first_line.is_empty() {
257 None
258 } else {
259 Some(content_inspector::inspect(&first_line[..]))
260 };
262 if content_type == Some(ContentType::UTF_16LE) {
263 reader.read_until(0x00, &mut first_line).ok();
264 }
266 InputReader {
267 inner: Box::new(reader),
268 first_line,
269 content_type,
270 }
271 }
273 pub(crate) fn read_line(&mut self, buf: &mut Vec<u8>) -> io::Result<bool> {
274 if !self.first_line.is_empty() {
275 buf.append(&mut self.first_line);
276 return Ok(true);
277 }
279 let res = self.inner.read_until(b'\n', buf).map(|size| size > 0)?;
281 if self.content_type == Some(ContentType::UTF_16LE) {
282 let _ = self.inner.read_until(0x00, buf);
283 }
285 Ok(res)
286 }
289#[test]
290fn basic() {
291 let content = b"#!/bin/bash\necho hello";
292 let mut reader = InputReader::new(&content[..]);
294 assert_eq!(b"#!/bin/bash\n", &reader.first_line[..]);
296 let mut buffer = vec![];
298 let res = reader.read_line(&mut buffer);
299 assert!(res.is_ok());
300 assert!(res.unwrap());
301 assert_eq!(b"#!/bin/bash\n", &buffer[..]);
303 buffer.clear();
305 let res = reader.read_line(&mut buffer);
306 assert!(res.is_ok());
307 assert!(res.unwrap());
308 assert_eq!(b"echo hello", &buffer[..]);
310 buffer.clear();
312 let res = reader.read_line(&mut buffer);
313 assert!(res.is_ok());
314 assert!(!res.unwrap());
315 assert!(buffer.is_empty());
318#[test]
319fn utf16le() {
320 let content = b"\xFF\xFE\x73\x00\x0A\x00\x64\x00";
321 let mut reader = InputReader::new(&content[..]);
323 assert_eq!(b"\xFF\xFE\x73\x00\x0A\x00", &reader.first_line[..]);
325 let mut buffer = vec![];
327 let res = reader.read_line(&mut buffer);
328 assert!(res.is_ok());
329 assert!(res.unwrap());
330 assert_eq!(b"\xFF\xFE\x73\x00\x0A\x00", &buffer[..]);
332 buffer.clear();
334 let res = reader.read_line(&mut buffer);
335 assert!(res.is_ok());
336 assert!(res.unwrap());
337 assert_eq!(b"\x64\x00", &buffer[..]);
339 buffer.clear();
341 let res = reader.read_line(&mut buffer);
342 assert!(res.is_ok());
343 assert!(!res.unwrap());
344 assert!(buffer.is_empty());