feat: improve the performance of highlighting big JSON file (#23)

This commit is contained in:
三咲雅 · Misaki Masa 2023-08-05 17:29:40 +08:00 committed by GitHub
parent 011154abcb
commit c5c9b2e598
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 23 additions and 10 deletions

View File

@ -1,19 +1,32 @@
use std::path::Path;
use std::{path::Path, process::Stdio};
use anyhow::{bail, Result};
use config::PREVIEW;
use tokio::process::Command;
use tokio::{io::{AsyncBufReadExt, BufReader}, process::Command};
pub async fn jq(path: &Path) -> Result<String> {
let output = Command::new("jq")
pub async fn jq(path: &Path, mut lines: usize) -> Result<String> {
let mut child = Command::new("jq")
.args(["-C", "--indent", &PREVIEW.tab_size.to_string(), "."])
.arg(path)
.stdout(Stdio::piped())
.stderr(Stdio::null())
.kill_on_drop(true)
.output()
.await?;
.spawn()?;
if !output.status.success() {
bail!("failed to get json: {}", String::from_utf8_lossy(&output.stderr));
let mut it = BufReader::new(child.stdout.take().unwrap()).lines();
let mut output = String::new();
while let Ok(Some(line)) = it.next_line().await {
if lines < 1 {
break;
}
output.push_str(&line);
output.push('\n');
lines -= 1;
}
Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
if output.is_empty() {
bail!("failed to get head of jq");
}
Ok(output)
}

View File

@ -134,7 +134,7 @@ impl Preview {
pub async fn json(path: &Path) -> Result<String> {
Ok(
external::jq(path)
external::jq(path, Self::rect().height as usize)
.await?
.lines()
.take(Self::rect().height as usize)