diff options
| author | 魏曹先生 <1992414357@qq.com> | 2025-11-20 17:44:49 +0800 |
|---|---|---|
| committer | 魏曹先生 <1992414357@qq.com> | 2025-11-20 17:44:49 +0800 |
| commit | 34abfcdc8e148c047ebb2e06539036e514df7046 (patch) | |
| tree | 3761aeb4b435029efdbbb66cb486b03195deff9a /src/utils | |
| parent | 733739294fac9aa1c99c6a1cbb8cb08c0c00ef5b (diff) | |
add: utility functions for table and pager
- Add insert_item method to SimpleTable for flexible row insertion
- Add show_in_pager function for system pager support
Diffstat (limited to 'src/utils')
| -rw-r--r-- | src/utils/display.rs | 24 | ||||
| -rw-r--r-- | src/utils/input.rs | 32 |
2 files changed, 56 insertions, 0 deletions
diff --git a/src/utils/display.rs b/src/utils/display.rs index 09efe97..cab7477 100644 --- a/src/utils/display.rs +++ b/src/utils/display.rs @@ -55,6 +55,30 @@ impl SimpleTable { self.line.push(processed_items); } + /// Insert a new row of items at the specified index + pub fn insert_item(&mut self, index: usize, items: Vec<impl Into<String>>) { + let items: Vec<String> = items.into_iter().map(|v| v.into()).collect(); + + let mut processed_items = Vec::with_capacity(self.items.len()); + + for i in 0..self.items.len() { + if i < items.len() { + processed_items.push(items[i].clone()); + } else { + processed_items.push(String::new()); + } + } + + for (i, d) in processed_items.iter().enumerate() { + let d_len = display_width(d); + if d_len > self.length[i] { + self.length[i] = d_len; + } + } + + self.line.insert(index, processed_items); + } + /// Get the current maximum column widths fn get_column_widths(&self) -> &[usize] { &self.length diff --git a/src/utils/input.rs b/src/utils/input.rs index a728c77..219fe1b 100644 --- a/src/utils/input.rs +++ b/src/utils/input.rs @@ -103,3 +103,35 @@ pub async fn input_with_editor( Ok(processed_content) } + +/// Show text using the system pager (less) +/// Opens the system pager (less) with the given text content written to the specified file +/// If less is not found, directly outputs the content to stdout +pub async fn show_in_pager( + content: impl AsRef<str>, + cache_file: impl AsRef<std::path::Path>, +) -> Result<(), std::io::Error> { + let content_str = content.as_ref(); + let cache_path = cache_file.as_ref(); + + // Write content to cache file + fs::write(cache_path, content_str).await?; + + // Try to use less first + let status = Command::new("less").arg(cache_path).status().await; + + match status { + Ok(status) if status.success() => Ok(()), + _ => { + // If less failed, output directly to stdout + use tokio::io::{self, AsyncWriteExt}; + let mut stdout = io::stdout(); + stdout + .write_all(content_str.as_bytes()) + .await + .expect("Failed to write content"); + stdout.flush().await.expect("Failed to flush stdout"); + Ok(()) + } + } +} |
