Pass stdin as a generic BufRead, fix stdin tests

This commit is contained in:
sharkdp 2020-04-18 11:37:12 +02:00 committed by David Peter
parent d5a31dc2ec
commit 1b8ce60054
3 changed files with 17 additions and 8 deletions

View File

@ -271,7 +271,7 @@ mod tests {
let syntax = self.assets.get_syntax( let syntax = self.assets.get_syntax(
None, None,
input_file, input_file,
&mut input_file.get_reader(&io::stdin()).unwrap(), &mut input_file.get_reader(io::stdin().lock()).unwrap(),
&self.syntax_mapping, &self.syntax_mapping,
); );
@ -281,6 +281,17 @@ mod tests {
fn syntax_for_file(&self, file_name: &str) -> String { fn syntax_for_file(&self, file_name: &str) -> String {
self.syntax_for_file_with_content(file_name, "") self.syntax_for_file_with_content(file_name, "")
} }
fn syntax_for_stdin_with_content(&self, file_name: &str, content: &[u8]) -> String {
let input_file = InputFile::StdIn(Some(OsStr::new(file_name)));
let syntax = self.assets.get_syntax(
None,
input_file,
&mut input_file.get_reader(content).unwrap(),
&self.syntax_mapping,
);
syntax.name.clone()
}
} }
#[test] #[test]
@ -353,10 +364,10 @@ mod tests {
let test = SyntaxDetectionTest::new(); let test = SyntaxDetectionTest::new();
// from file extension // from file extension
assert_eq!(test.syntax_for_file_with_content("test.cpp", ""), "C++"); assert_eq!(test.syntax_for_stdin_with_content("test.cpp", b"a"), "C++");
// from first line (fallback) // from first line (fallback)
assert_eq!( assert_eq!(
test.syntax_for_file_with_content("my_script", "#!/bin/bash"), test.syntax_for_stdin_with_content("my_script", b"#!/bin/bash"),
"Bourne Again Shell (bash)" "Bourne Again Shell (bash)"
); );
} }

View File

@ -56,10 +56,8 @@ impl<'b> Controller<'b> {
let writer = output_type.handle()?; let writer = output_type.handle()?;
let mut no_errors: bool = true; let mut no_errors: bool = true;
let stdin = io::stdin();
for input_file in self.config.files.iter() { for input_file in self.config.files.iter() {
match input_file.get_reader(&stdin) { match input_file.get_reader(io::stdin().lock()) {
Err(error) => { Err(error) => {
handle_error(&error); handle_error(&error);
no_errors = false; no_errors = false;

View File

@ -86,9 +86,9 @@ pub enum InputFile<'a> {
} }
impl<'a> InputFile<'a> { impl<'a> InputFile<'a> {
pub(crate) fn get_reader(&self, stdin: &'a io::Stdin) -> Result<InputFileReader> { pub(crate) fn get_reader<R: BufRead + 'a>(&self, stdin: R) -> Result<InputFileReader> {
match self { match self {
InputFile::StdIn(_) => Ok(InputFileReader::new(stdin.lock())), InputFile::StdIn(_) => Ok(InputFileReader::new(stdin)),
InputFile::Ordinary(ofile) => { InputFile::Ordinary(ofile) => {
let file = File::open(ofile.path) let file = File::open(ofile.path)
.map_err(|e| format!("'{}': {}", ofile.path.to_string_lossy(), e))?; .map_err(|e| format!("'{}': {}", ofile.path.to_string_lossy(), e))?;