Skip to content

Commit

Permalink
feat(runtime): filter out binary files
Browse files Browse the repository at this point in the history
  • Loading branch information
loichyan committed Jul 11, 2024
1 parent 335cbef commit d1f29e4
Show file tree
Hide file tree
Showing 6 changed files with 51 additions and 11 deletions.
10 changes: 10 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ edition = "2021"
[dependencies]
clap = { version = ">=4.0, <4.5", features = ["derive"] }
codespan-reporting = "0.11.1"
content_inspector = "0.2.4"
extend = "1.2"
indexmap = "2.2"
inquire = "0.7.5"
Expand Down
25 changes: 19 additions & 6 deletions src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
use std::path::PathBuf;
use std::str::FromStr;
use std::{fmt, io};
use std::{fmt, fs, io};

use clap::{Parser, Subcommand, ValueEnum};
use shadow_rs::formatcp;
Expand Down Expand Up @@ -91,6 +91,9 @@ pub enum Command {
/// Recursively traverse all directories.
#[arg(short, long)]
recursive: bool,
/// Do not skip binary files.
#[arg(long)]
include_binary: bool,
/// Path(s) of files to check.
#[arg(value_name = V_PATH)]
source: Vec<IoPath>,
Expand All @@ -109,6 +112,9 @@ pub enum Command {
/// Recursively traverse all directories.
#[arg(short, long)]
recursive: bool,
/// Do not skip binary files.
#[arg(long)]
include_binary: bool,
/// Path tuple(s) of files to read from and write to.
///
/// Each tuple is an input path followed by an optional output path,
Expand Down Expand Up @@ -178,17 +184,24 @@ impl fmt::Display for IoPath {
}

impl IoPath {
pub fn read_to_string(&self) -> io::Result<String> {
pub fn read_all(&self) -> io::Result<Vec<u8>> {
let mut buf = Vec::new();
match self {
IoPath::Stdio => io::read_to_string(io::stdin()),
IoPath::Path(path) => std::fs::read_to_string(path),
}
IoPath::Stdio => _ = io::Read::read_to_end(&mut io::stdin(), &mut buf)?,
IoPath::Path(path) => _ = io::Read::read_to_end(&mut fs::File::open(path)?, &mut buf)?,
};
Ok(buf)
}

pub fn read_to_string(&self) -> io::Result<String> {
self.read_all()
.map(|s| String::from_utf8_lossy(&s).as_ref().to_owned())
}

pub fn write_str(&self, content: &str) -> io::Result<()> {
match self {
IoPath::Stdio => io::Write::write_all(&mut io::stdout(), content.as_bytes()),
IoPath::Path(path) => std::fs::write(path, content),
IoPath::Path(path) => fs::write(path, content),
}
}
}
Expand Down
4 changes: 4 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,11 +107,13 @@ fn main_impl() -> error::Result<()> {
format,
source,
recursive,
include_binary,
} => {
let rt = rt.build();
let mut context = CheckerContext {
format,
writer: Box::new(std::io::stdout()),
include_binary,
..Default::default()
};
for source in walk(source.into_iter().map(|p| Source(p, None)), recursive) {
Expand All @@ -128,6 +130,7 @@ fn main_impl() -> error::Result<()> {
write,
select_first,
recursive,
include_binary,
source,
} => {
if yes {
Expand All @@ -137,6 +140,7 @@ fn main_impl() -> error::Result<()> {
let mut context = CheckerContext {
write,
select_first,
include_binary,
..Default::default()
};
let mut buffer = String::new();
Expand Down
16 changes: 14 additions & 2 deletions src/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use miette::{Diagnostic, ReportHandler};
use once_cell::unsync::{Lazy, OnceCell};
use serde::Serialize;
use thisctx::IntoError;
use tracing::info;
use tracing::{info, warn};

use crate::autocomplete::Autocompleter;
use crate::cli::{IoPath, OutputFormat, UserInput};
Expand Down Expand Up @@ -119,7 +119,17 @@ impl Runtime {
mut output: Option<&mut String>,
) -> error::Result<bool> {
info!("Check input file from '{}'", input);
let content = input.read_to_string()?;
let bytes = input.read_all()?;
if !context.include_binary
&& matches!(
content_inspector::inspect(&bytes),
content_inspector::ContentType::BINARY
)
{
warn!("Skip binary file '{}'", input);
return Ok(false);
}
let content = String::from_utf8_lossy(&bytes);
let mut updated = false;
for (start, mut ch) in content.char_indices() {
if let Some(icon) = self
Expand Down Expand Up @@ -344,6 +354,7 @@ pub struct CheckerContext {
pub format: OutputFormat,
pub write: bool,
pub select_first: bool,
pub include_binary: bool,
}

impl Default for CheckerContext {
Expand All @@ -355,6 +366,7 @@ impl Default for CheckerContext {
format: OutputFormat::default(),
write: false,
select_first: false,
include_binary: false,
}
}
}
Expand Down
6 changes: 3 additions & 3 deletions tests/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
#![cfg(unix)]

use core::fmt;
use std::env;
use std::path::Path;
use std::process::{Command, Output};
use std::{env, fs};

use assert_cmd::assert::Assert;
use assert_cmd::prelude::*;
Expand Down Expand Up @@ -74,11 +74,11 @@ fn cmp_or_override(file: &str) -> impl '_ + Predicate<[u8]> {
let path = Path::new("tests").join(file);
if matches!(env::var("NERDFIX_TEST").as_deref(), Ok("overwrite")) {
BoxedPredicate::new(predicate::function(move |expected: &[u8]| {
std::fs::write(&path, expected).unwrap();
fs::write(&path, expected).unwrap();
true
}))
} else {
let expected = std::fs::read_to_string(path).unwrap();
let expected = fs::read_to_string(path).unwrap();
BoxedPredicate::new(predicate::str::diff(expected).from_utf8())
}
}
Expand Down

0 comments on commit d1f29e4

Please sign in to comment.