refactor: move binary detection to common module and enhance get logic
Co-authored-by: aider (openai/andrew/openrouter/qwen/qwen3-coder) <aider@aider.chat>
This commit is contained in:
@@ -1,6 +1,8 @@
|
||||
use anyhow::anyhow;
|
||||
use std::io::Read;
|
||||
|
||||
use crate::compression_engine::{CompressionType, get_compression_engine};
|
||||
use crate::common::is_binary;
|
||||
use clap::Command;
|
||||
use std::path::PathBuf;
|
||||
use std::str::FromStr;
|
||||
@@ -43,22 +45,49 @@ pub fn mode_get(
|
||||
let mut item_path = data_path.clone();
|
||||
item_path.push(item_id.to_string());
|
||||
|
||||
// Check if this is a binary item and we're outputting to a TTY
|
||||
if !args.options.force {
|
||||
// Determine if we should detect binary data
|
||||
let mut detect_binary = !args.options.force && is_stdout_tty();
|
||||
|
||||
// If we're detecting binary and there's binary metadata, check it
|
||||
if detect_binary {
|
||||
let item_meta = crate::db::get_item_meta(conn, &item)?;
|
||||
let binary_meta = item_meta.into_iter().find(|meta| meta.name == "binary");
|
||||
if let Some(binary_meta) = binary_meta {
|
||||
if binary_meta.value == "true" {
|
||||
if is_stdout_tty() {
|
||||
return Err(anyhow!("Refusing to output binary data to TTY, use --force to override"));
|
||||
}
|
||||
if binary_meta.value == "false" {
|
||||
// If metadata says it's not binary, don't detect
|
||||
detect_binary = false;
|
||||
} else if binary_meta.value == "true" {
|
||||
// If metadata says it's binary, error immediately
|
||||
return Err(anyhow!("Refusing to output binary data to TTY, use --force to override"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let compression_type = CompressionType::from_str(&item.compression)?;
|
||||
let compression_engine = get_compression_engine(compression_type)?;
|
||||
compression_engine.cat(item_path.clone())?;
|
||||
|
||||
// If we need to detect binary, read first 4KB and check
|
||||
if detect_binary {
|
||||
// Open the file through compression engine to read first 4KB
|
||||
let mut reader = compression_engine.open(item_path.clone())?;
|
||||
let mut buffer = [0u8; 4096];
|
||||
let bytes_read = reader.read(&mut buffer)?;
|
||||
|
||||
// Check if this data is binary
|
||||
if is_binary(&buffer[..bytes_read]) {
|
||||
return Err(anyhow!("Refusing to output binary data to TTY, use --force to override"));
|
||||
}
|
||||
|
||||
// If not binary, output the data we've read
|
||||
std::io::stdout().write_all(&buffer[..bytes_read])?;
|
||||
|
||||
// Continue reading and outputting the rest of the data
|
||||
let mut stdout = std::io::stdout();
|
||||
std::io::copy(&mut reader, &mut stdout)?;
|
||||
} else {
|
||||
// No binary detection needed, just output the data
|
||||
compression_engine.cat(item_path.clone())?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
} else {
|
||||
|
||||
Reference in New Issue
Block a user