on fa72f86 help sign in
bat/src/input.rs
304 lines 8.4 kB history raw
1use std::convert::TryFrom;
2use std::ffi::{OsStr, OsString};
3use std::fs::File;
4use std::io::{self, BufRead, BufReader, Read};
5use std::path::Path;
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.as_ref() {
54 Some(ref 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(OsString),
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<OsString>,
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(OsString),
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<'a> Input<'a> {
112 pub fn ordinary_file(path: &OsStr) -> Self {
113 let kind = InputKind::OrdinaryFile(path.to_os_string());
114 Input {
115 description: kind.description(),
116 metadata: InputMetadata::default(),
117 kind,
118 }
119 }
121 pub fn stdin() -> Self {
122 let kind = InputKind::StdIn;
123 Input {
124 description: kind.description(),
125 metadata: InputMetadata::default(),
126 kind,
127 }
128 }
130 pub fn from_reader(reader: Box<dyn Read + 'a>) -> Self {
131 let kind = InputKind::CustomReader(reader);
132 Input {
133 description: kind.description(),
134 metadata: InputMetadata::default(),
135 kind,
136 }
137 }
139 pub fn is_stdin(&self) -> bool {
140 matches!(self.kind, InputKind::StdIn)
141 }
143 pub fn with_name(mut self, provided_name: Option<&OsStr>) -> Self {
144 if let Some(name) = provided_name {
145 self.description.name = name.to_string_lossy().to_string()
146 }
148 self.metadata.user_provided_name = provided_name.map(|n| n.to_owned());
149 self
150 }
152 pub fn description(&self) -> &InputDescription {
153 &self.description
154 }
156 pub fn description_mut(&mut self) -> &mut InputDescription {
157 &mut self.description
158 }
160 pub(crate) fn open<R: BufRead + 'a>(self, stdin: R) -> Result<OpenedInput<'a>> {
161 let description = self.description().clone();
162 match self.kind {
163 InputKind::StdIn => Ok(OpenedInput {
164 kind: OpenedInputKind::StdIn,
165 description,
166 metadata: self.metadata,
167 reader: InputReader::new(stdin),
168 }),
169 InputKind::OrdinaryFile(path) => Ok(OpenedInput {
170 kind: OpenedInputKind::OrdinaryFile(path.clone()),
171 description,
172 metadata: self.metadata,
173 reader: {
174 let file = File::open(&path)
175 .map_err(|e| format!("'{}': {}", path.to_string_lossy(), e))?;
176 if file.metadata()?.is_dir() {
177 return Err(format!("'{}' is a directory.", path.to_string_lossy()).into());
178 }
179 InputReader::new(BufReader::new(file))
180 },
181 }),
182 InputKind::CustomReader(reader) => Ok(OpenedInput {
183 description,
184 kind: OpenedInputKind::CustomReader,
185 metadata: self.metadata,
186 reader: InputReader::new(BufReader::new(reader)),
187 }),
188 }
189 }
192impl TryFrom<&'_ Input<'_>> for clircle::Identifier {
193 type Error = ();
195 fn try_from(input: &Input) -> std::result::Result<clircle::Identifier, ()> {
196 match input.kind {
197 InputKind::OrdinaryFile(ref path) => Self::try_from(Path::new(path)).map_err(|_| ()),
198 InputKind::StdIn => Self::try_from(clircle::Stdio::Stdin).map_err(|_| ()),
199 InputKind::CustomReader(_) => Err(()),
200 }
201 }
204pub(crate) struct InputReader<'a> {
205 inner: Box<dyn BufRead + 'a>,
206 pub(crate) first_line: Vec<u8>,
207 pub(crate) content_type: Option<ContentType>,
210impl<'a> InputReader<'a> {
211 fn new<R: BufRead + 'a>(mut reader: R) -> InputReader<'a> {
212 let mut first_line = vec![];
213 reader.read_until(b'\n', &mut first_line).ok();
215 let content_type = if first_line.is_empty() {
216 None
217 } else {
218 Some(content_inspector::inspect(&first_line[..]))
219 };
221 if content_type == Some(ContentType::UTF_16LE) {
222 reader.read_until(0x00, &mut first_line).ok();
223 }
225 InputReader {
226 inner: Box::new(reader),
227 first_line,
228 content_type,
229 }
230 }
232 pub(crate) fn read_line(&mut self, buf: &mut Vec<u8>) -> io::Result<bool> {
233 if self.first_line.is_empty() {
234 let res = self.inner.read_until(b'\n', buf).map(|size| size > 0)?;
236 if self.content_type == Some(ContentType::UTF_16LE) {
237 self.inner.read_until(0x00, buf).ok();
238 }
240 Ok(res)
241 } else {
242 buf.append(&mut self.first_line);
243 Ok(true)
244 }
245 }
248#[test]
249fn basic() {
250 let content = b"#!/bin/bash\necho hello";
251 let mut reader = InputReader::new(&content[..]);
253 assert_eq!(b"#!/bin/bash\n", &reader.first_line[..]);
255 let mut buffer = vec![];
257 let res = reader.read_line(&mut buffer);
258 assert!(res.is_ok());
259 assert_eq!(true, res.unwrap());
260 assert_eq!(b"#!/bin/bash\n", &buffer[..]);
262 buffer.clear();
264 let res = reader.read_line(&mut buffer);
265 assert!(res.is_ok());
266 assert_eq!(true, res.unwrap());
267 assert_eq!(b"echo hello", &buffer[..]);
269 buffer.clear();
271 let res = reader.read_line(&mut buffer);
272 assert!(res.is_ok());
273 assert_eq!(false, res.unwrap());
274 assert!(buffer.is_empty());
277#[test]
278fn utf16le() {
279 let content = b"\xFF\xFE\x73\x00\x0A\x00\x64\x00";
280 let mut reader = InputReader::new(&content[..]);
282 assert_eq!(b"\xFF\xFE\x73\x00\x0A\x00", &reader.first_line[..]);
284 let mut buffer = vec![];
286 let res = reader.read_line(&mut buffer);
287 assert!(res.is_ok());
288 assert_eq!(true, res.unwrap());
289 assert_eq!(b"\xFF\xFE\x73\x00\x0A\x00", &buffer[..]);
291 buffer.clear();
293 let res = reader.read_line(&mut buffer);
294 assert!(res.is_ok());
295 assert_eq!(true, res.unwrap());
296 assert_eq!(b"\x64\x00", &buffer[..]);
298 buffer.clear();
300 let res = reader.read_line(&mut buffer);
301 assert!(res.is_ok());
302 assert_eq!(false, res.unwrap());
303 assert!(buffer.is_empty());