From 93ef6da6298f3a98127ed572659b6c24a3f5295e Mon Sep 17 00:00:00 2001 From: sigoden Date: Thu, 6 Jun 2024 06:08:41 +0800 Subject: refactor: global IS_STDOUT_TERMINAL (#571) --- src/config/mod.rs | 9 ++++----- src/function.rs | 5 ++--- src/main.rs | 14 ++++++-------- src/render/mod.rs | 6 ++---- src/utils/mod.rs | 2 ++ 5 files changed, 16 insertions(+), 20 deletions(-) diff --git a/src/config/mod.rs b/src/config/mod.rs index 0240a80..fbee667 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -15,12 +15,11 @@ use crate::rag::{Rag, TEMP_RAG_NAME}; use crate::render::{MarkdownRender, RenderOptions}; use crate::utils::{ format_option_value, fuzzy_match, get_env_name, light_theme_from_colorfgbg, now, render_prompt, - set_text, AbortSignal, + set_text, AbortSignal, IS_STDOUT_TERMINAL, }; use anyhow::{anyhow, bail, Context, Result}; use inquire::{Confirm, Select}; -use is_terminal::IsTerminal; use parking_lot::RwLock; use serde::Deserialize; use serde_json::json; @@ -28,7 +27,7 @@ use std::collections::{HashMap, HashSet}; use std::{ env, fs::{create_dir_all, read_dir, read_to_string, remove_file, File, OpenOptions}, - io::{stdout, Write}, + io::Write, path::{Path, PathBuf}, process::exit, sync::Arc, @@ -156,7 +155,7 @@ impl Config { let config_path = Self::config_file()?; let platform = env::var(get_env_name("platform")).ok(); - if working_mode != WorkingMode::Command && platform.is_none() && !config_path.exists() { + if *IS_STDOUT_TERMINAL && platform.is_none() && !config_path.exists() { create_config_file(&config_path)?; } let mut config = if platform.is_some() { @@ -915,7 +914,7 @@ impl Config { } else { None }; - let wrap = if stdout().is_terminal() { + let wrap = if *IS_STDOUT_TERMINAL { self.wrap.clone() } else { None diff --git a/src/function.rs b/src/function.rs index a42b943..9cb098a 100644 --- a/src/function.rs +++ b/src/function.rs @@ -2,6 +2,7 @@ use crate::{ config::GlobalConfig, utils::{ dimmed_text, get_env_bool, indent_text, run_command, run_command_with_output, warning_text, + IS_STDOUT_TERMINAL, }, }; @@ -9,14 +10,12 @@ use anyhow::{anyhow, bail, Context, Result}; use fancy_regex::Regex; use indexmap::{IndexMap, IndexSet}; use inquire::{validator::Validation, Text}; -use is_terminal::IsTerminal; use lazy_static::lazy_static; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use std::{ collections::{HashMap, HashSet}, fs, - io::stdout, path::Path, sync::mpsc::channel, }; @@ -232,7 +231,7 @@ impl ToolCall { let name = polyfill_cmd_name(&name, &config.read().function.bin_dir); let output = if self.is_execute() { - if stdout().is_terminal() { + if *IS_STDOUT_TERMINAL { println!("{prompt}"); let answer = Text::new("[1] Run, [2] Run & Retrieve, [3] Skip:") .with_default("1") diff --git a/src/main.rs b/src/main.rs index 3222285..e021f9e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -24,7 +24,7 @@ use crate::render::{render_error, MarkdownRender}; use crate::repl::Repl; use crate::utils::{ create_abort_signal, detect_shell, extract_block, run_command, run_spinner, Shell, - CODE_BLOCK_RE, + CODE_BLOCK_RE, IS_STDOUT_TERMINAL, }; use anyhow::{bail, Result}; @@ -33,7 +33,7 @@ use clap::Parser; use inquire::{Select, Text}; use is_terminal::IsTerminal; use parking_lot::RwLock; -use std::io::{stderr, stdin, stdout, Read}; +use std::io::{stderr, stdin, Read}; use std::process; use std::sync::Arc; @@ -146,8 +146,7 @@ async fn start_directive( code_mode: bool, ) -> Result<()> { let client = input.create_client()?; - let is_terminal_stdout = stdout().is_terminal(); - let extract_code = !is_terminal_stdout && code_mode; + let extract_code = !*IS_STDOUT_TERMINAL && code_mode; let (output, tool_call_results) = if no_stream || extract_code { let ChatCompletionsOutput { text, tool_calls, .. @@ -160,7 +159,7 @@ async fn start_directive( } else { text.clone() }; - if is_terminal_stdout { + if *IS_STDOUT_TERMINAL { let render_options = config.read().get_render_options()?; let mut markdown_render = MarkdownRender::init(render_options)?; println!("{}", markdown_render.render(&text).trim()); @@ -198,8 +197,7 @@ async fn start_interactive(config: &GlobalConfig) -> Result<()> { #[async_recursion::async_recursion] async fn shell_execute(config: &GlobalConfig, shell: &Shell, mut input: Input) -> Result<()> { let client = input.create_client()?; - let is_terminal_stdout = stdout().is_terminal(); - let ret = if is_terminal_stdout { + let ret = if *IS_STDOUT_TERMINAL { let (stop_spinner_tx, _) = run_spinner("Generating").await; let ret = client.chat_completions(input.clone()).await; let _ = stop_spinner_tx.send(()); @@ -219,7 +217,7 @@ async fn shell_execute(config: &GlobalConfig, shell: &Shell, mut input: Input) - println!("{}", markdown_render.render(&eval_str).trim()); return Ok(()); } - if is_terminal_stdout { + if *IS_STDOUT_TERMINAL { loop { let answer = Select::new( eval_str.trim(), diff --git a/src/render/mod.rs b/src/render/mod.rs index 054a830..9fa6787 100644 --- a/src/render/mod.rs +++ b/src/render/mod.rs @@ -4,12 +4,10 @@ mod stream; pub use self::markdown::{MarkdownRender, RenderOptions}; use self::stream::{markdown_stream, raw_stream}; -use crate::utils::{error_text, AbortSignal}; +use crate::utils::{error_text, AbortSignal, IS_STDOUT_TERMINAL}; use crate::{client::SseEvent, config::GlobalConfig}; use anyhow::Result; -use is_terminal::IsTerminal; -use std::io::stdout; use tokio::sync::mpsc::UnboundedReceiver; pub async fn render_stream( @@ -17,7 +15,7 @@ pub async fn render_stream( config: &GlobalConfig, abort: AbortSignal, ) -> Result<()> { - if stdout().is_terminal() { + if *IS_STDOUT_TERMINAL { let render_options = config.read().get_render_options()?; let mut render = MarkdownRender::init(render_options)?; markdown_stream(rx, &mut render, &abort).await diff --git a/src/utils/mod.rs b/src/utils/mod.rs index 95c6725..cd00cc5 100644 --- a/src/utils/mod.rs +++ b/src/utils/mod.rs @@ -15,11 +15,13 @@ pub use self::render_prompt::render_prompt; pub use self::spinner::run_spinner; use fancy_regex::Regex; +use is_terminal::IsTerminal; use lazy_static::lazy_static; use std::env; lazy_static! { pub static ref CODE_BLOCK_RE: Regex = Regex::new(r"(?ms)```\w*(.*)```").unwrap(); + pub static ref IS_STDOUT_TERMINAL: bool = std::io::stdout().is_terminal(); } pub fn now() -> String { -- cgit v1.2.3