on v0.17.1 help sign in
bat/src/input.rs
294 lines 8.0 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 from_reader(reader: Box<dyn Read + 'a>) -> Self {
129 let kind = InputKind::CustomReader(reader);
130 Input {
131 description: kind.description(),
132 metadata: InputMetadata::default(),
133 kind,
134 }
135 }
137 pub fn is_stdin(&self) -> bool {
138 if let InputKind::StdIn = self.kind {
139 true
140 } else {
141 false
142 }
143 }
145 pub fn with_name(mut self, provided_name: Option<&OsStr>) -> Self {
146 if let Some(name) = provided_name {
147 self.description.name = name.to_string_lossy().to_string()
148 }
150 self.metadata.user_provided_name = provided_name.map(|n| n.to_owned());
151 self
152 }
154 pub fn description(&self) -> &InputDescription {
155 &self.description
156 }
158 pub fn description_mut(&mut self) -> &mut InputDescription {
159 &mut self.description
160 }
162 pub(crate) fn open<R: BufRead + 'a>(self, stdin: R) -> Result<OpenedInput<'a>> {
163 let description = self.description().clone();
164 match self.kind {
165 InputKind::StdIn => Ok(OpenedInput {
166 kind: OpenedInputKind::StdIn,
167 description,
168 metadata: self.metadata,
169 reader: InputReader::new(stdin),
170 }),
171 InputKind::OrdinaryFile(path) => Ok(OpenedInput {
172 kind: OpenedInputKind::OrdinaryFile(path.clone()),
173 description,
174 metadata: self.metadata,
175 reader: {
176 let file = File::open(&path)
177 .map_err(|e| format!("'{}': {}", path.to_string_lossy(), e))?;
178 if file.metadata()?.is_dir() {
179 return Err(format!("'{}' is a directory.", path.to_string_lossy()).into());
180 }
181 InputReader::new(BufReader::new(file))
182 },
183 }),
184 InputKind::CustomReader(reader) => Ok(OpenedInput {
185 description,
186 kind: OpenedInputKind::CustomReader,
187 metadata: self.metadata,
188 reader: InputReader::new(BufReader::new(reader)),
189 }),
190 }
191 }
194pub(crate) struct InputReader<'a> {
195 inner: Box<dyn BufRead + 'a>,
196 pub(crate) first_line: Vec<u8>,
197 pub(crate) content_type: Option<ContentType>,
200impl<'a> InputReader<'a> {
201 fn new<R: BufRead + 'a>(mut reader: R) -> InputReader<'a> {
202 let mut first_line = vec![];
203 reader.read_until(b'\n', &mut first_line).ok();
205 let content_type = if first_line.is_empty() {
206 None
207 } else {
208 Some(content_inspector::inspect(&first_line[..]))
209 };
211 if content_type == Some(ContentType::UTF_16LE) {
212 reader.read_until(0x00, &mut first_line).ok();
213 }
215 InputReader {
216 inner: Box::new(reader),
217 first_line,
218 content_type,
219 }
220 }
222 pub(crate) fn read_line(&mut self, buf: &mut Vec<u8>) -> io::Result<bool> {
223 if self.first_line.is_empty() {
224 let res = self.inner.read_until(b'\n', buf).map(|size| size > 0)?;
226 if self.content_type == Some(ContentType::UTF_16LE) {
227 self.inner.read_until(0x00, buf).ok();
228 }
230 Ok(res)
231 } else {
232 buf.append(&mut self.first_line);
233 Ok(true)
234 }
235 }
238#[test]
239fn basic() {
240 let content = b"#!/bin/bash\necho hello";
241 let mut reader = InputReader::new(&content[..]);
243 assert_eq!(b"#!/bin/bash\n", &reader.first_line[..]);
245 let mut buffer = vec![];
247 let res = reader.read_line(&mut buffer);
248 assert!(res.is_ok());
249 assert_eq!(true, res.unwrap());
250 assert_eq!(b"#!/bin/bash\n", &buffer[..]);
252 buffer.clear();
254 let res = reader.read_line(&mut buffer);
255 assert!(res.is_ok());
256 assert_eq!(true, res.unwrap());
257 assert_eq!(b"echo hello", &buffer[..]);
259 buffer.clear();
261 let res = reader.read_line(&mut buffer);
262 assert!(res.is_ok());
263 assert_eq!(false, res.unwrap());
264 assert!(buffer.is_empty());
267#[test]
268fn utf16le() {
269 let content = b"\xFF\xFE\x73\x00\x0A\x00\x64\x00";
270 let mut reader = InputReader::new(&content[..]);
272 assert_eq!(b"\xFF\xFE\x73\x00\x0A\x00", &reader.first_line[..]);
274 let mut buffer = vec![];
276 let res = reader.read_line(&mut buffer);
277 assert!(res.is_ok());
278 assert_eq!(true, res.unwrap());
279 assert_eq!(b"\xFF\xFE\x73\x00\x0A\x00", &buffer[..]);
281 buffer.clear();
283 let res = reader.read_line(&mut buffer);
284 assert!(res.is_ok());
285 assert_eq!(true, res.unwrap());
286 assert_eq!(b"\x64\x00", &buffer[..]);
288 buffer.clear();
290 let res = reader.read_line(&mut buffer);
291 assert!(res.is_ok());
292 assert_eq!(false, res.unwrap());
293 assert!(buffer.is_empty());