From 44d039a7c29fdd64e983c65912807c9a19eec552 Mon Sep 17 00:00:00 2001 From: Andrew Phillips Date: Mon, 8 Sep 2025 17:25:36 -0300 Subject: [PATCH] refactor: Move terminal width detection to common utility function Co-authored-by: aider (openai/andrew/openrouter/deepseek/deepseek-chat-v3.1) --- src/modes/common.rs | 28 ++++++++++++++++++++++++++++ src/modes/list.rs | 27 ++------------------------- 2 files changed, 30 insertions(+), 25 deletions(-) diff --git a/src/modes/common.rs b/src/modes/common.rs index c1d56d0..fd19722 100644 --- a/src/modes/common.rs +++ b/src/modes/common.rs @@ -8,8 +8,10 @@ use prettytable::format::TableFormat; use regex::Regex; use std::collections::HashMap; use std::env; +use std::io::{stdout, IsTerminal}; use std::str::FromStr; use strum::IntoEnumIterator; +use termsize; #[derive(Debug, Clone, strum::EnumString, strum::Display, PartialEq)] #[strum(ascii_case_insensitive)] pub enum OutputFormat { @@ -193,3 +195,29 @@ pub fn settings_output_format(settings: &config::Settings) -> OutputFormat { .and_then(|s| OutputFormat::from_str(s).ok()) .unwrap_or(OutputFormat::Table) } + +/// Get the terminal width, considering environment variables and actual terminal size +/// Returns 0 if output is not a terminal or width cannot be determined +pub fn get_terminal_width() -> usize { + use std::io::{stdout, IsTerminal}; + + // Check if output is a terminal + if !stdout().is_terminal() { + return 0; + } + + // Try to get width from COLUMNS environment variable first + if let Ok(columns_env) = env::var("COLUMNS") { + if let Ok(width) = columns_env.parse::() { + return width; + } + } + + // Fall back to querying the terminal size + if let Some(size) = termsize::get() { + return size.cols as usize; + } + + // Default to 80 if all else fails + 80 +} diff --git a/src/modes/list.rs b/src/modes/list.rs index 24c3c3d..5a5c6ba 100644 --- a/src/modes/list.rs +++ b/src/modes/list.rs @@ -57,31 +57,8 @@ pub fn mode_list( let is_terminal = stdout().is_terminal(); debug!("Output is terminal: {}", is_terminal); - // Get terminal width once, default to 80 if not available - // Only use max_len when output is a terminal - let term_width = if is_terminal { - if let Ok(columns_env) = env::var("COLUMNS") { - debug!("COLUMNS environment variable: {:?}", columns_env); - columns_env.parse::().unwrap_or(80) - } else { - // Try to get terminal size using termsize - match termsize::get() { - Some(size) => { - let width = size.cols as usize; - debug!("Terminal size detected: {} columns", width); - width - } - None => { - debug!("Failed to get terminal size, defaulting to 80"); - 80 - } - } - } - } else { - debug!("Not a terminal, max_len will be ignored"); - 0 // Use 0 to indicate no truncation - }; - + // Get terminal width using the common function + let term_width = crate::modes::common::get_terminal_width(); debug!("Terminal width: {}", term_width); let mut table = Table::new();