1use std::ffi::{OsStr, OsString};
3use std::io::{self, BufRead, BufReader, Read};
5use content_inspector::{self, ContentType};
9/// A description of an Input source.
10/// This tells bat how to refer to the input.
12pub struct InputDescription {
13 pub(crate) name: String,
16 /// This replaces the name if provided.
17 title: 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 {
38 pub fn set_kind(&mut self, kind: Option<String>) {
42 pub fn set_summary(&mut self, summary: Option<String>) {
43 self.summary = summary;
46 pub fn set_title(&mut self, title: Option<String>) {
50 pub fn title(&self) -> &String {
51 match self.title.as_ref() {
52 Some(ref title) => title,
57 pub fn kind(&self) -> Option<&String> {
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),
69pub(crate) enum InputKind<'a> {
70 OrdinaryFile(OsString),
72 CustomReader(Box<dyn Read + 'a>),
75impl<'a> InputKind<'a> {
76 pub fn description(&self) -> InputDescription {
78 InputKind::OrdinaryFile(ref path) => InputDescription::new(path.to_string_lossy()),
79 InputKind::StdIn => InputDescription::new("STDIN"),
80 InputKind::CustomReader(_) => InputDescription::new("READER"),
85#[derive(Clone, Default)]
86pub(crate) struct InputMetadata {
87 pub(crate) user_provided_name: Option<OsString>,
91 pub(crate) kind: InputKind<'a>,
92 pub(crate) metadata: InputMetadata,
93 pub(crate) description: InputDescription,
96pub(crate) enum OpenedInputKind {
97 OrdinaryFile(OsString),
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,
110 pub fn ordinary_file(path: &OsStr) -> Self {
111 let kind = InputKind::OrdinaryFile(path.to_os_string());
113 description: kind.description(),
114 metadata: InputMetadata::default(),
119 pub fn stdin() -> Self {
120 let kind = InputKind::StdIn;
122 description: kind.description(),
123 metadata: InputMetadata::default(),
128 pub fn from_reader(reader: Box<dyn Read + 'a>) -> Self {
129 let kind = InputKind::CustomReader(reader);
131 description: kind.description(),
132 metadata: InputMetadata::default(),
137 pub fn is_stdin(&self) -> bool {
138 if let InputKind::StdIn = self.kind {
145 pub fn with_name(mut self, provided_name: Option<&OsStr>) -> Self {
146 match provided_name {
147 Some(name) => self.description.name = name.to_string_lossy().to_string(),
151 self.metadata.user_provided_name = provided_name.map(|n| n.to_owned());
155 pub fn description(&self) -> &InputDescription {
159 pub fn description_mut(&mut self) -> &mut InputDescription {
160 &mut self.description
163 pub(crate) fn open<R: BufRead + 'a>(self, stdin: R) -> Result<OpenedInput<'a>> {
164 let description = self.description().clone();
166 InputKind::StdIn => Ok(OpenedInput {
167 kind: OpenedInputKind::StdIn,
169 metadata: self.metadata,
170 reader: InputReader::new(stdin),
172 InputKind::OrdinaryFile(path) => Ok(OpenedInput {
173 kind: OpenedInputKind::OrdinaryFile(path.clone()),
175 metadata: self.metadata,
177 let file = File::open(&path)
178 .map_err(|e| format!("'{}': {}", path.to_string_lossy(), e))?;
179 if file.metadata()?.is_dir() {
180 return Err(format!("'{}' is a directory.", path.to_string_lossy()).into());
182 InputReader::new(BufReader::new(file))
185 InputKind::CustomReader(reader) => Ok(OpenedInput {
187 kind: OpenedInputKind::CustomReader,
188 metadata: self.metadata,
189 reader: InputReader::new(BufReader::new(reader)),
195pub(crate) struct InputReader<'a> {
196 inner: Box<dyn BufRead + 'a>,
197 pub(crate) first_line: Vec<u8>,
198 pub(crate) content_type: Option<ContentType>,
201impl<'a> InputReader<'a> {
202 fn new<R: BufRead + 'a>(mut reader: R) -> InputReader<'a> {
203 let mut first_line = vec![];
204 reader.read_until(b'\n', &mut first_line).ok();
206 let content_type = if first_line.is_empty() {
209 Some(content_inspector::inspect(&first_line[..]))
212 if content_type == Some(ContentType::UTF_16LE) {
213 reader.read_until(0x00, &mut first_line).ok();
217 inner: Box::new(reader),
223 pub(crate) fn read_line(&mut self, buf: &mut Vec<u8>) -> io::Result<bool> {
224 if self.first_line.is_empty() {
225 let res = self.inner.read_until(b'\n', buf).map(|size| size > 0)?;
227 if self.content_type == Some(ContentType::UTF_16LE) {
228 self.inner.read_until(0x00, buf).ok();
233 buf.append(&mut self.first_line);
241 let content = b"#!/bin/bash\necho hello";
242 let mut reader = InputReader::new(&content[..]);
244 assert_eq!(b"#!/bin/bash\n", &reader.first_line[..]);
246 let mut buffer = vec![];
248 let res = reader.read_line(&mut buffer);
249 assert!(res.is_ok());
250 assert_eq!(true, res.unwrap());
251 assert_eq!(b"#!/bin/bash\n", &buffer[..]);
255 let res = reader.read_line(&mut buffer);
256 assert!(res.is_ok());
257 assert_eq!(true, res.unwrap());
258 assert_eq!(b"echo hello", &buffer[..]);
262 let res = reader.read_line(&mut buffer);
263 assert!(res.is_ok());
264 assert_eq!(false, res.unwrap());
265 assert!(buffer.is_empty());
270 let content = b"\xFF\xFE\x73\x00\x0A\x00\x64\x00";
271 let mut reader = InputReader::new(&content[..]);
273 assert_eq!(b"\xFF\xFE\x73\x00\x0A\x00", &reader.first_line[..]);
275 let mut buffer = vec![];
277 let res = reader.read_line(&mut buffer);
278 assert!(res.is_ok());
279 assert_eq!(true, res.unwrap());
280 assert_eq!(b"\xFF\xFE\x73\x00\x0A\x00", &buffer[..]);
284 let res = reader.read_line(&mut buffer);
285 assert!(res.is_ok());
286 assert_eq!(true, res.unwrap());
287 assert_eq!(b"\x64\x00", &buffer[..]);
291 let res = reader.read_line(&mut buffer);
292 assert!(res.is_ok());
293 assert_eq!(false, res.unwrap());
294 assert!(buffer.is_empty());
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list