Define a separate files.rs for reading and content checking

ida_star
Wilfred Hughes 2021-08-27 22:08:32 +07:00
parent ce2d6dee54
commit aff0131ecb
2 changed files with 37 additions and 34 deletions

@ -0,0 +1,34 @@
use std::fs;
pub fn read_or_die(path: &str) -> Vec<u8> {
match fs::read(path) {
Ok(src) => src,
Err(e) => {
match e.kind() {
std::io::ErrorKind::NotFound => {
eprintln!("No such file: {}", path);
}
std::io::ErrorKind::PermissionDenied => {
eprintln!("Permission denied when reading file: {}", path);
}
_ => {
eprintln!("Could not read file: {} (error {:?})", path, e.kind());
}
};
std::process::exit(1);
}
}
}
/// Do these bytes look like a binary (non-textual) format?
pub fn is_probably_binary(bytes: &[u8]) -> bool {
// If more than 20 of the first 1,000 characters are not valid
// UTF-8, we assume it's binary.
let num_replaced = String::from_utf8_lossy(bytes)
.to_string()
.chars()
.take(1000)
.filter(|c| *c == std::char::REPLACEMENT_CHARACTER)
.count();
num_replaced > 20
}

@ -1,4 +1,5 @@
mod dijkstra;
mod files;
mod inline;
mod intervals;
mod line_parser;
@ -11,49 +12,17 @@ mod syntax;
mod tree_sitter_parser;
use atty::Stream;
use clap::{App, AppSettings, Arg};
use std::env;
use std::ffi::OsStr;
use std::path::Path;
use std::{env, fs};
use typed_arena::Arena;
use crate::dijkstra::mark_syntax;
use crate::files::{is_probably_binary, read_or_die};
use crate::lines::{join_overlapping, visible_groups, MaxLine};
use crate::syntax::{change_positions, init_info, matching_lines};
use crate::tree_sitter_parser as tsp;
fn read_or_die(path: &str) -> Vec<u8> {
match fs::read(path) {
Ok(src) => src,
Err(e) => {
match e.kind() {
std::io::ErrorKind::NotFound => {
eprintln!("No such file: {}", path);
}
std::io::ErrorKind::PermissionDenied => {
eprintln!("Permission denied when reading file: {}", path);
}
_ => {
eprintln!("Could not read file: {} (error {:?})", path, e.kind());
}
};
std::process::exit(1);
}
}
}
/// Do these bytes look like a binary (non-textual) format?
fn is_probably_binary(bytes: &[u8]) -> bool {
// If more than 20 of the first 1,000 characters are not valid
// UTF-8, we assume it's binary.
let num_replaced = String::from_utf8_lossy(bytes)
.to_string()
.chars()
.take(1000)
.filter(|c| *c == std::char::REPLACEMENT_CHARACTER)
.count();
num_replaced > 20
}
const VERSION: &str = env!("CARGO_PKG_VERSION");
fn configure_color() {