From fc0057617e06ad08b58ead8f8fa6b030916718d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=89=E5=92=B2=E9=9B=85=20=C2=B7=20Misaki=20Masa?= Date: Thu, 26 Oct 2023 01:33:07 +0800 Subject: [PATCH] fix: `jq` previews empty when the user sets `tab_size=8` (#320) --- yazi-core/src/external/jq.rs | 25 ++++++++++++++++--------- yazi-core/src/preview/provider.rs | 9 +++++---- 2 files changed, 21 insertions(+), 13 deletions(-) diff --git a/yazi-core/src/external/jq.rs b/yazi-core/src/external/jq.rs index 16fe788e..7286f803 100644 --- a/yazi-core/src/external/jq.rs +++ b/yazi-core/src/external/jq.rs @@ -1,16 +1,16 @@ use std::{path::Path, process::Stdio}; use anyhow::Result; -use tokio::{io::{AsyncBufReadExt, BufReader}, process::Command}; +use tokio::{io::{AsyncBufReadExt, AsyncReadExt, BufReader}, process::Command, select}; use yazi_config::PREVIEW; use yazi_shared::PeekError; pub async fn jq(path: &Path, skip: usize, limit: usize) -> Result { let mut child = Command::new("jq") - .args(["-C", "--indent", &PREVIEW.tab_size.to_string(), "."]) + .args(["-C", "--tab", "."]) .arg(path) .stdout(Stdio::piped()) - .stderr(Stdio::null()) + .stderr(Stdio::piped()) .kill_on_drop(true) .spawn()?; @@ -21,18 +21,25 @@ pub async fn jq(path: &Path, skip: usize, limit: usize) -> Result skip + limit { break; - } else if i <= skip { - continue; } - - lines.push_str(&line); - lines.push('\n'); + if i > skip { + lines.push_str(&line); + lines.push('\n'); + } } child.start_kill().ok(); + if lines.is_empty() { + let mut stderr = child.stderr.take().unwrap(); + select! { + Ok(_) = stderr.read_u8() => return Err("parse error".into()), + else => {} + } + } + if skip > 0 && i < skip + limit { Err(PeekError::Exceed(i.saturating_sub(limit))) } else { - Ok(lines) + Ok(lines.replace('\t', &" ".repeat(PREVIEW.tab_size as usize))) } } diff --git a/yazi-core/src/preview/provider.rs b/yazi-core/src/preview/provider.rs index 13d0ed32..441eb092 100644 --- a/yazi-core/src/preview/provider.rs +++ b/yazi-core/src/preview/provider.rs @@ -1,7 +1,6 @@ use std::{io::BufRead, path::Path, sync::atomic::{AtomicUsize, Ordering}}; use anyhow::anyhow; -use futures::TryFutureExt; use syntect::{easy::HighlightFile, util::as_24_bit_terminal_escaped}; use tokio::fs; use yazi_adaptor::ADAPTOR; @@ -70,9 +69,11 @@ impl Provider { } pub(super) async fn json(path: &Path, skip: usize) -> Result { - external::jq(path, skip, MANAGER.layout.preview_height()) - .or_else(|_| Provider::highlight(path, skip)) - .await + let result = external::jq(path, skip, MANAGER.layout.preview_height()).await; + if let Err(PeekError::Unexpected(_)) = result { + return Self::highlight(path, skip).await; + } + result } pub(super) async fn archive(path: &Path, skip: usize) -> Result {