on 7a9deca help sign in
bat/src/input.rs
306 lines 8.4 kB history raw
1use std::ffi::{OsStr, OsString};
2use std::fs::File;
3use std::io::{self, BufRead, BufReader, Read};
5use content_inspector::{self, ContentType};
7use crate::error::*;
9/// A description of an Input source.
10/// This tells bat how to refer to the input.
11#[derive(Clone)]
12pub struct InputDescription {
13 pub(crate) name: String,
15 /// The input title.
16 /// This replaces the name if provided.
17 title: Option<String>,
19 /// The input kind.
20 kind: Option<String>,
22 /// A summary description of the input.
23 /// Defaults to "{kind} '{name}'"
24 summary: Option<String>,
27impl InputDescription {
28 /// Creates a description for an input.
29 pub fn new(name: impl Into<String>) -> Self {
30 InputDescription {
31 name: name.into(),
32 title: None,
33 kind: None,
34 summary: None,
35 }
36 }
38 pub fn set_kind(&mut self, kind: Option<String>) -> () {
39 self.kind = kind;
40 }
42 pub fn set_summary(&mut self, summary: Option<String>) -> () {
43 self.summary = summary;
44 }
46 pub fn set_title(&mut self, title: Option<String>) -> () {
47 self.title = title;
48 }
50 pub fn title(&self) -> &String {
51 match self.title.as_ref() {
52 Some(ref title) => title,
53 None => &self.name,
54 }
55 }
57 pub fn kind(&self) -> Option<&String> {
58 self.kind.as_ref()
59 }
61 pub fn summary(&self) -> String {
62 self.summary.clone().unwrap_or_else(|| match &self.kind {
63 None => self.name.clone(),
64 Some(kind) => format!("{} '{}'", kind.to_lowercase(), self.name),
65 })
66 }
69pub(crate) enum InputKind<'a> {
70 OrdinaryFile(OsString),
71 StdIn,
72 CustomReader(Box<dyn Read + 'a>),
75impl<'a> InputKind<'a> {
76 pub fn description(&self) -> InputDescription {
77 match self {
78 InputKind::OrdinaryFile(ref path) => InputDescription::new(path.to_string_lossy()),
79 InputKind::StdIn => InputDescription::new("STDIN"),
80 InputKind::CustomReader(_) => InputDescription::new("READER"),
81 }
82 }
85#[derive(Clone, Default)]
86pub(crate) struct InputMetadata {
87 pub(crate) user_provided_name: Option<OsString>,
90pub struct Input<'a> {
91 pub(crate) kind: InputKind<'a>,
92 pub(crate) metadata: InputMetadata,
93 pub(crate) description: InputDescription,
96pub(crate) enum OpenedInputKind {
97 OrdinaryFile(OsString),
98 StdIn,
99 CustomReader,
102pub(crate) struct OpenedInput<'a> {
103 pub(crate) kind: OpenedInputKind,
104 pub(crate) metadata: InputMetadata,
105 pub(crate) reader: InputReader<'a>,
106 pub(crate) description: InputDescription,
109impl<'a> Input<'a> {
110 pub fn ordinary_file(path: &OsStr) -> Self {
111 let kind = InputKind::OrdinaryFile(path.to_os_string());
112 Input {
113 description: kind.description(),
114 metadata: InputMetadata::default(),
115 kind,
116 }
117 }
119 pub fn stdin() -> Self {
120 let kind = InputKind::StdIn;
121 Input {
122 description: kind.description(),
123 metadata: InputMetadata::default(),
124 kind,
125 }
126 }
128 pub fn stdin_as_file(name: Option<impl AsRef<OsStr>>) -> Self {
129 match name {
130 None => Input::stdin(),
131 Some(name) => {
132 let mut input = Input::stdin().with_name(Some(name.as_ref()));
133 input.description.kind = Some("File".to_owned());
134 input
135 }
136 }
137 }
139 pub fn from_reader(reader: Box<dyn Read + 'a>) -> Self {
140 let kind = InputKind::CustomReader(reader);
141 Input {
142 description: kind.description(),
143 metadata: InputMetadata::default(),
144 kind,
145 }
146 }
148 pub fn is_stdin(&self) -> bool {
149 if let InputKind::StdIn = self.kind {
150 true
151 } else {
152 false
153 }
154 }
156 pub fn with_name(mut self, provided_name: Option<&OsStr>) -> Self {
157 match provided_name {
158 Some(name) => self.description.name = name.to_string_lossy().to_string(),
159 None => {}
160 }
162 self.metadata.user_provided_name = provided_name.map(|n| n.to_owned());
163 self
164 }
166 pub fn description(&self) -> &InputDescription {
167 &self.description
168 }
170 pub fn description_mut(&mut self) -> &mut InputDescription {
171 &mut self.description
172 }
174 pub(crate) fn open<R: BufRead + 'a>(self, stdin: R) -> Result<OpenedInput<'a>> {
175 let description = self.description().clone();
176 match self.kind {
177 InputKind::StdIn => Ok(OpenedInput {
178 kind: OpenedInputKind::StdIn,
179 description,
180 metadata: self.metadata,
181 reader: InputReader::new(stdin),
182 }),
183 InputKind::OrdinaryFile(path) => Ok(OpenedInput {
184 kind: OpenedInputKind::OrdinaryFile(path.clone()),
185 description,
186 metadata: self.metadata,
187 reader: {
188 let file = File::open(&path)
189 .map_err(|e| format!("'{}': {}", path.to_string_lossy(), e))?;
190 if file.metadata()?.is_dir() {
191 return Err(format!("'{}' is a directory.", path.to_string_lossy()).into());
192 }
193 InputReader::new(BufReader::new(file))
194 },
195 }),
196 InputKind::CustomReader(reader) => Ok(OpenedInput {
197 description,
198 kind: OpenedInputKind::CustomReader,
199 metadata: self.metadata,
200 reader: InputReader::new(BufReader::new(reader)),
201 }),
202 }
203 }
206pub(crate) struct InputReader<'a> {
207 inner: Box<dyn BufRead + 'a>,
208 pub(crate) first_line: Vec<u8>,
209 pub(crate) content_type: Option<ContentType>,
212impl<'a> InputReader<'a> {
213 fn new<R: BufRead + 'a>(mut reader: R) -> InputReader<'a> {
214 let mut first_line = vec![];
215 reader.read_until(b'\n', &mut first_line).ok();
217 let content_type = if first_line.is_empty() {
218 None
219 } else {
220 Some(content_inspector::inspect(&first_line[..]))
221 };
223 if content_type == Some(ContentType::UTF_16LE) {
224 reader.read_until(0x00, &mut first_line).ok();
225 }
227 InputReader {
228 inner: Box::new(reader),
229 first_line,
230 content_type,
231 }
232 }
234 pub(crate) fn read_line(&mut self, buf: &mut Vec<u8>) -> io::Result<bool> {
235 if self.first_line.is_empty() {
236 let res = self.inner.read_until(b'\n', buf).map(|size| size > 0)?;
238 if self.content_type == Some(ContentType::UTF_16LE) {
239 self.inner.read_until(0x00, buf).ok();
240 }
242 Ok(res)
243 } else {
244 buf.append(&mut self.first_line);
245 Ok(true)
246 }
247 }
250#[test]
251fn basic() {
252 let content = b"#!/bin/bash\necho hello";
253 let mut reader = InputReader::new(&content[..]);
255 assert_eq!(b"#!/bin/bash\n", &reader.first_line[..]);
257 let mut buffer = vec![];
259 let res = reader.read_line(&mut buffer);
260 assert!(res.is_ok());
261 assert_eq!(true, res.unwrap());
262 assert_eq!(b"#!/bin/bash\n", &buffer[..]);
264 buffer.clear();
266 let res = reader.read_line(&mut buffer);
267 assert!(res.is_ok());
268 assert_eq!(true, res.unwrap());
269 assert_eq!(b"echo hello", &buffer[..]);
271 buffer.clear();
273 let res = reader.read_line(&mut buffer);
274 assert!(res.is_ok());
275 assert_eq!(false, res.unwrap());
276 assert!(buffer.is_empty());
279#[test]
280fn utf16le() {
281 let content = b"\xFF\xFE\x73\x00\x0A\x00\x64\x00";
282 let mut reader = InputReader::new(&content[..]);
284 assert_eq!(b"\xFF\xFE\x73\x00\x0A\x00", &reader.first_line[..]);
286 let mut buffer = vec![];
288 let res = reader.read_line(&mut buffer);
289 assert!(res.is_ok());
290 assert_eq!(true, res.unwrap());
291 assert_eq!(b"\xFF\xFE\x73\x00\x0A\x00", &buffer[..]);
293 buffer.clear();
295 let res = reader.read_line(&mut buffer);
296 assert!(res.is_ok());
297 assert_eq!(true, res.unwrap());
298 assert_eq!(b"\x64\x00", &buffer[..]);
300 buffer.clear();
302 let res = reader.read_line(&mut buffer);
303 assert!(res.is_ok());
304 assert_eq!(false, res.unwrap());
305 assert!(buffer.is_empty());