Add comparison script

This commit is contained in:
sharkdp 2020-08-03 13:34:21 +02:00 committed by David Peter
parent a70efae79b
commit 02a89d8ee8
4 changed files with 82 additions and 164 deletions

View file

@ -0,0 +1,65 @@
#!/usr/bin/env python3
import glob
import sys
import os.path as path
import difflib
import argparse
def compare_highlighted_versions(root_old, root_new):
print("Comparing the following directories:")
print(" -", root_old)
print(" -", root_new)
has_changes = False
for path_old in glob.glob(path.join(root_old, "*", "*")):
filename = path.basename(path_old)
dirname = path.basename(path.dirname(path_old))
path_new = path.join(root_new, dirname, filename)
print("\n========== {}/{}".format(dirname, filename))
with open(path_old) as file_old:
lines_old = file_old.readlines()
with open(path_new) as file_new:
lines_new = file_new.readlines()
diff = difflib.unified_diff(
lines_old, lines_new, fromfile=path_old, tofile=path_new
)
file_has_changes = False
for line in diff:
print(line, end="")
file_has_changes = True
if file_has_changes:
has_changes = True
else:
print("No changes")
print()
return has_changes
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="This script compares two directories that were created "
"by 'create_highlighted_versions.py'."
)
parser.add_argument(
"OLD", help="Path to the old (stored) version of the highlighted output",
)
parser.add_argument(
"NEW", help="Path to the new version of the highlighted output",
)
args = parser.parse_args()
if compare_highlighted_versions(args.OLD, args.NEW):
print("Error: files with changes have been found")
sys.exit(1)
else:
print("Directories are the same")

5
tests/syntax-tests/create_highlighted_versions.py vendored Normal file → Executable file
View file

@ -1,4 +1,4 @@
#!/usr/bin/env python #!/usr/bin/env python3
import subprocess import subprocess
import glob import glob
@ -37,8 +37,7 @@ def create_highlighted_versions(output_basepath):
with open(output_path, "wb") as output_file: with open(output_path, "wb") as output_file:
output_file.write(bat_output) output_file.write(bat_output)
relative_path = path.relpath(output_path, root) print("Created '{}'".format(output_path))
print("Created '{}'".format(relative_path))
except subprocess.CalledProcessError as err: except subprocess.CalledProcessError as err:
print( print(
"=== Error: Could not highlight source file '{}".format(source), "=== Error: Could not highlight source file '{}".format(source),

View file

@ -1,161 +0,0 @@
use std::io::{self, Write};
#[cfg(feature = "paging")]
use std::process::Child;
use crate::error::*;
#[cfg(feature = "paging")]
use crate::less::retrieve_less_version;
#[cfg(feature = "paging")]
use crate::paging::PagingMode;
#[derive(Debug)]
pub enum OutputType {
 #[cfg(feature = "paging")]
 Pager(Child),
 Stdout(io::Stdout),
}
impl OutputType {
 #[cfg(feature = "paging")]
 pub fn from_mode(mode: PagingMode, pager: Option<&str>) -> Result<Self> {
 use self::PagingMode::*;
 Ok(match mode {
 Always => OutputType::try_pager(false, pager)?,
 QuitIfOneScreen => OutputType::try_pager(true, pager)?,
 _ => OutputType::stdout(),
 })
 }
 /// Try to launch the pager. Fall back to stdout in case of errors.
 #[cfg(feature = "paging")]
 fn try_pager(quit_if_one_screen: bool, pager_from_config: Option<&str>) -> Result<Self> {
 use std::env;
 use std::ffi::OsString;
 use std::path::PathBuf;
 use std::process::{Command, Stdio};
 let mut replace_arguments_to_less = false;
 let pager_from_env = match (env::var("BAT_PAGER"), env::var("PAGER")) {
 (Ok(bat_pager), _) => Some(bat_pager),
 (_, Ok(pager)) => {
 // less needs to be called with the '-R' option in order to properly interpret the
 // ANSI color sequences printed by bat. If someone has set PAGER="less -F", we
 // therefore need to overwrite the arguments and add '-R'.
 //
 // We only do this for PAGER (as it is not specific to 'bat'), not for BAT_PAGER
 // or bats '--pager' command line option.
 replace_arguments_to_less = true;
 Some(pager)
 }
 _ => None,
 };
 let pager_from_config = pager_from_config.map(|p| p.to_string());
 if pager_from_config.is_some() {
 replace_arguments_to_less = false;
 }
 let pager = pager_from_config
 .or(pager_from_env)
 .unwrap_or_else(|| String::from("less"));
 let pagerflags =
 shell_words::split(&pager).chain_err(|| "Could not parse pager command.")?;
 match pagerflags.split_first() {
 Some((pager_name, args)) => {
 let mut pager_path = PathBuf::from(pager_name);
 if pager_path.file_stem() == Some(&OsString::from("bat")) {
 pager_path = PathBuf::from("less");
 }
 let is_less = pager_path.file_stem() == Some(&OsString::from("less"));
 let mut process = if is_less {
 let mut p = Command::new(&pager_path);
 if args.is_empty() || replace_arguments_to_less {
 p.arg("--RAW-CONTROL-CHARS");
 if quit_if_one_screen {
 p.arg("--quit-if-one-screen");
 }
 // Passing '--no-init' fixes a bug with '--quit-if-one-screen' in older
 // versions of 'less'. Unfortunately, it also breaks mouse-wheel support.
 //
 // See: http://www.greenwoodsoftware.com/less/news.530.html
 //
 // For newer versions (530 or 558 on Windows), we omit '--no-init' as it
 // is not needed anymore.
 match retrieve_less_version() {
 None => {
 p.arg("--no-init");
 }
 Some(version)
 if (version < 530 || (cfg!(windows) && version < 558)) =>
 {
 p.arg("--no-init");
 }
 _ => {}
 }
 } else {
 p.args(args);
 }
 p.env("LESSCHARSET", "UTF-8");
 p
 } else {
 let mut p = Command::new(&pager_path);
 p.args(args);
 p
 };
 Ok(process
 .stdin(Stdio::piped())
 .spawn()
 .map(OutputType::Pager)
 .unwrap_or_else(|_| OutputType::stdout()))
 }
 None => Ok(OutputType::stdout()),
 }
 }
 pub(crate) fn stdout() -> Self {
 OutputType::Stdout(io::stdout())
 }
 #[cfg(feature = "paging")]
 pub(crate) fn is_pager(&self) -> bool {
 if let OutputType::Pager(_) = self {
 true
 } else {
 false
 }
 }
 #[cfg(not(feature = "paging"))]
 pub(crate) fn is_pager(&self) -> bool {
 false
 }
 pub fn handle(&mut self) -> Result<&mut dyn Write> {
 Ok(match *self {
 #[cfg(feature = "paging")]
 OutputType::Pager(ref mut command) => command
 .stdin
 .as_mut()
 .chain_err(|| "Could not open stdin for pager")?,
 OutputType::Stdout(ref mut handle) => handle,
 })
 }
}
#[cfg(feature = "paging")]
impl Drop for OutputType {
 fn drop(&mut self) {
 if let OutputType::Pager(ref mut command) = *self {
 let _ = command.wait();
 }
 }
}

15
tests/syntax-tests/regression_test.sh vendored Normal file
View file

@ -0,0 +1,15 @@
#!/bin/bash
set -eou pipefail
script_directory="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
output_directory=$(mktemp -d --suffix=.bat-syntax-regression-test)
"$script_directory"/create_highlighted_versions.py --output="$output_directory"
echo
"$script_directory"/compare_highlighted_versions.py \
"$script_directory/highlighted" \
"$output_directory"