Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

build(infer): drop infer dependency and refactor code to a simpler heuristic #58

Merged
merged 2 commits into from
Nov 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ All notable changes to this project will be documented in this file.

### 🚜 Refactor

- *(picker)* Refactor picker logic and add tests for picker, cli and events
- *(picker)* Refactor picker logic and add tests to picker, cli, and events (#57)

### 📚 Documentation

Expand All @@ -20,6 +20,10 @@ All notable changes to this project will be documented in this file.

- Add readme version update to github actions (#55)

### Build

- *(infer)* Drop infer dependency and refactor code to a simpler heuristic

## [0.5.1] - 2024-11-20

### 📚 Documentation
Expand Down
28 changes: 0 additions & 28 deletions Cargo.lock

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

5 changes: 1 addition & 4 deletions crates/television-channels/src/channels/text.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,7 @@ use std::{
sync::{atomic::AtomicUsize, Arc},
};
use television_fuzzy::matcher::{config::Config, injector::Injector, Matcher};
use television_utils::files::{
is_not_text, walk_builder, DEFAULT_NUM_THREADS,
};
use television_utils::files::{walk_builder, DEFAULT_NUM_THREADS};
use television_utils::strings::{
preprocess_line, proportion_of_printable_ascii_characters,
PRINTABLE_ASCII_THRESHOLD,
Expand Down Expand Up @@ -298,7 +296,6 @@ fn try_inject_lines(
match reader.read(&mut buffer) {
Ok(bytes_read) => {
if (bytes_read == 0)
|| is_not_text(&buffer).unwrap_or(false)
|| proportion_of_printable_ascii_characters(&buffer)
< PRINTABLE_ASCII_THRESHOLD
{
Expand Down
1 change: 0 additions & 1 deletion crates/television-previewers/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,4 @@ tokio = "1.41.1"
termtree = "0.5.1"
devicons = "0.6.11"
color-eyre = "0.6.3"
infer = "0.16.0"

126 changes: 32 additions & 94 deletions crates/television-previewers/src/previewers/files.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ use color_eyre::Result;
//use ratatui_image::picker::Picker;
use parking_lot::Mutex;
use std::fs::File;
use std::io::{BufRead, BufReader, Read, Seek};
use std::path::{Path, PathBuf};
use std::io::{BufRead, BufReader, Seek};
use std::path::PathBuf;
use std::sync::Arc;

use syntect::{
Expand All @@ -16,12 +16,9 @@ use tracing::{debug, warn};
use super::cache::PreviewCache;
use crate::previewers::{meta, Preview, PreviewContent};
use television_channels::entry;
use television_utils::files::get_file_size;
use television_utils::files::FileType;
use television_utils::files::{get_file_size, is_known_text_extension};
use television_utils::strings::{
preprocess_line, proportion_of_printable_ascii_characters,
PRINTABLE_ASCII_THRESHOLD,
};
use television_utils::strings::preprocess_line;
use television_utils::syntax::{
self, load_highlighting_assets, HighlightingAssetsExt,
};
Expand Down Expand Up @@ -69,6 +66,10 @@ impl FilePreviewer {
}
}

/// The maximum file size that we will try to preview.
/// 4 MB
const MAX_FILE_SIZE: u64 = 4 * 1024 * 1024;

/// Get a preview for a file entry.
///
/// # Panics
Expand All @@ -93,53 +94,32 @@ impl FilePreviewer {

// try to determine file type
debug!("Computing preview for {:?}", entry.name);
match self.get_file_type(&path_buf) {
FileType::Text => {
match File::open(&path_buf) {
Ok(file) => {
// insert a loading preview into the cache
let preview = meta::loading(&entry.name);
self.cache_preview(
entry.name.clone(),
preview.clone(),
);

// compute the highlighted version in the background
let mut reader = BufReader::new(file);
reader.seek(std::io::SeekFrom::Start(0)).unwrap();
self.compute_highlighted_text_preview(entry, reader);
preview
}
Err(e) => {
warn!("Error opening file: {:?}", e);
let p = meta::not_supported(&entry.name);
self.cache_preview(entry.name.clone(), p.clone());
p
}
if let FileType::Text = FileType::from(&path_buf) {
debug!("File is text-based: {:?}", entry.name);
match File::open(&path_buf) {
Ok(file) => {
// insert a loading preview into the cache
let preview = meta::loading(&entry.name);
self.cache_preview(entry.name.clone(), preview.clone());

// compute the highlighted version in the background
let mut reader = BufReader::new(file);
reader.seek(std::io::SeekFrom::Start(0)).unwrap();
self.compute_highlighted_text_preview(entry, reader);
preview
}
Err(e) => {
warn!("Error opening file: {:?}", e);
let p = meta::not_supported(&entry.name);
self.cache_preview(entry.name.clone(), p.clone());
p
}
}
FileType::Image => {
debug!("Previewing image file: {:?}", entry.name);
// insert a loading preview into the cache
//let preview = loading(&entry.name);
let preview = meta::not_supported(&entry.name);
self.cache_preview(entry.name.clone(), preview.clone());
//// compute the image preview in the background
//self.compute_image_preview(entry).await;
preview
}
FileType::Other => {
debug!("Previewing other file: {:?}", entry.name);
let preview = meta::not_supported(&entry.name);
self.cache_preview(entry.name.clone(), preview.clone());
preview
}
FileType::Unknown => {
debug!("Unknown file type: {:?}", entry.name);
let preview = meta::not_supported(&entry.name);
self.cache_preview(entry.name.clone(), preview.clone());
preview
}
} else {
debug!("File isn't text-based: {:?}", entry.name);
let preview = meta::not_supported(&entry.name);
self.cache_preview(entry.name.clone(), preview.clone());
preview
}
}

Expand Down Expand Up @@ -218,48 +198,6 @@ impl FilePreviewer {
});
}

/// The maximum file size that we will try to preview.
/// 4 MB
const MAX_FILE_SIZE: u64 = 4 * 1024 * 1024;

fn get_file_type(&self, path: &Path) -> FileType {
debug!("Getting file type for {:?}", path);
let mut file_type = match infer::get_from_path(path) {
Ok(Some(t)) => {
let mime_type = t.mime_type();
if mime_type.contains("image") {
FileType::Image
} else if mime_type.contains("text") {
FileType::Text
} else {
FileType::Other
}
}
_ => FileType::Unknown,
};

// if the file type is unknown, try to determine it from the extension or the content
if matches!(file_type, FileType::Unknown) {
if is_known_text_extension(path) {
file_type = FileType::Text;
} else if let Ok(mut f) = File::open(path) {
let mut buffer = [0u8; 256];
if let Ok(bytes_read) = f.read(&mut buffer) {
if bytes_read > 0
&& proportion_of_printable_ascii_characters(
&buffer[..bytes_read],
) > PRINTABLE_ASCII_THRESHOLD
{
file_type = FileType::Text;
}
}
}
}
debug!("File type for {:?}: {:?}", path, file_type);

file_type
}

fn cache_preview(&mut self, key: String, preview: Arc<Preview>) {
self.cache.lock().insert(key, preview);
}
Expand Down
1 change: 0 additions & 1 deletion crates/television-utils/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ rust-version.workspace = true

[dependencies]
ignore = "0.4.23"
infer = "0.16.0"
lazy_static = "1.5.0"
tracing = "0.1.40"
color-eyre = "0.6.3"
Expand Down
57 changes: 36 additions & 21 deletions crates/television-utils/src/files.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
use std::fmt::Debug;
use std::fs::File;
use std::io::Read;
use std::path::Path;
use std::{collections::HashSet, path::PathBuf};

use ignore::{overrides::Override, types::TypesBuilder, WalkBuilder};
use infer::Infer;
use lazy_static::lazy_static;
use tracing::debug;
use tracing::{debug, warn};

use crate::strings::{
proportion_of_printable_ascii_characters, PRINTABLE_ASCII_THRESHOLD,
};
use crate::threads::default_num_threads;

lazy_static::lazy_static! {
Expand Down Expand Up @@ -51,34 +56,44 @@ pub fn get_file_size(path: &Path) -> Option<u64> {
#[derive(Debug)]
pub enum FileType {
Text,
Image,
Other,
Unknown,
}

pub fn is_not_text(bytes: &[u8]) -> Option<bool> {
let infer = Infer::new();
match infer.get(bytes) {
Some(t) => {
let mime_type = t.mime_type();
if mime_type.contains("image")
|| mime_type.contains("video")
|| mime_type.contains("audio")
|| mime_type.contains("archive")
|| mime_type.contains("book")
|| mime_type.contains("font")
{
Some(true)
} else {
None
impl<P> From<P> for FileType
where
P: AsRef<Path> + Debug,
{
fn from(path: P) -> Self {
debug!("Getting file type for {:?}", path);
let p = path.as_ref();
if is_known_text_extension(p) {
return FileType::Text;
}
if let Ok(mut f) = File::open(p) {
let mut buffer = [0u8; 256];
if let Ok(bytes_read) = f.read(&mut buffer) {
if bytes_read > 0
&& proportion_of_printable_ascii_characters(
&buffer[..bytes_read],
) > PRINTABLE_ASCII_THRESHOLD
{
return FileType::Text;
}
}
} else {
warn!("Error opening file: {:?}", path);
}
None => None,
FileType::Other
}
}

pub fn is_known_text_extension(path: &Path) -> bool {
path.extension()
pub fn is_known_text_extension<P>(path: P) -> bool
where
P: AsRef<Path>,
{
path.as_ref()
.extension()
.and_then(|ext| ext.to_str())
.is_some_and(|ext| KNOWN_TEXT_FILE_EXTENSIONS.contains(ext))
}
Expand Down