Swadhin Biswas fix: resolve all 25 clippy warnings · 3/4/2026
60ab211
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
//! Utility functions for FetchX
use std::process::Command;
/// Run a command and return its stdout trimmed, or empty string on failure.
pub fn run_cmd(cmd: &str, args: &[&str]) -> String {
Command::new(cmd)
.args(args)
.output()
.ok()
.and_then(|o| {
if o.status.success() {
String::from_utf8(o.stdout).ok()
} else {
None
}
})
.map(|s| s.trim().to_string())
.unwrap_or_default()
}
/// Run a command and return its stdout even on non-zero exit.
#[allow(dead_code)]
pub fn run_cmd_lossy(cmd: &str, args: &[&str]) -> String {
Command::new(cmd)
.args(args)
.output()
.ok()
.and_then(|o| String::from_utf8(o.stdout).ok())
.map(|s| s.trim().to_string())
.unwrap_or_default()
}
/// Read a file to string, trimmed. Returns empty string on failure.
pub fn read_file(path: &str) -> String {
std::fs::read_to_string(path)
.map(|s| s.trim().to_string())
.unwrap_or_default()
}
/// Read first line of a file, trimmed.
pub fn read_first_line(path: &str) -> String {
std::fs::read_to_string(path)
.ok()
.and_then(|s| s.lines().next().map(|l| l.trim().to_string()))
.unwrap_or_default()
}
/// Check if a command exists on the system.
pub fn command_exists(cmd: &str) -> bool {
Command::new("which")
.arg(cmd)
.output()
.map(|o| o.status.success())
.unwrap_or(false)
}
/// Get environment variable or empty string.
pub fn env_or(key: &str) -> String {
std::env::var(key).unwrap_or_default()
}
/// Strip ANSI escape sequences from a string for width calculation.
/// Handles CSI (\x1b[...), OSC (\x1b]...), APC (\x1b_...) and simple \x1b<char> sequences.
pub fn strip_ansi(s: &str) -> String {
let mut result = String::with_capacity(s.len());
let mut chars = s.chars().peekable();
while let Some(ch) = chars.next() {
if ch == '\x1b' {
match chars.peek() {
Some(&'[') => {
// CSI sequence: \x1b[ ... <letter>
chars.next();
while let Some(&c) = chars.peek() {
chars.next();
if c.is_ascii_alphabetic() {
break;
}
}
}
Some(&']') | Some(&'_') | Some(&'^') => {
// OSC / APC / PM: terminated by ST (\x1b\\ or BEL)
chars.next();
while let Some(c) = chars.next() {
if c == '\x07' {
break; // BEL terminator
}
if c == '\x1b' && chars.peek() == Some(&'\\') {
chars.next(); // consume '\\'
break;
}
}
}
Some(&c) if c.is_ascii_alphabetic() || c == '(' || c == ')' => {
// Simple two-char escape like \x1bM, \x1b(B etc.
chars.next();
if c == '(' || c == ')' {
chars.next(); // consume charset designator
}
}
_ => {} // Lone ESC, skip it
}
} else {
result.push(ch);
}
}
result
}
/// Calculate the visible width of a string (strip ANSI, use unicode-width).
pub fn visible_width(s: &str) -> usize {
use unicode_width::UnicodeWidthStr;
let stripped = strip_ansi(s);
UnicodeWidthStr::width(stripped.as_str())
}
/// Pad a string to a given visible width with spaces on the right.
pub fn pad_right(s: &str, target_width: usize) -> String {
let current = visible_width(s);
if current >= target_width {
s.to_string()
} else {
format!("{}{}", s, " ".repeat(target_width - current))
}
}
/// Truncate a string (which may contain ANSI escapes) so its visible width
/// does not exceed `max_width`. Preserves ANSI sequences but cuts visible chars.
pub fn truncate_to_width(s: &str, max_width: usize) -> String {
use unicode_width::UnicodeWidthChar;
let mut result = String::with_capacity(s.len());
let mut vis_w: usize = 0;
let mut chars = s.chars().peekable();
while let Some(ch) = chars.next() {
if ch == '\x1b' {
// Pass through the entire escape sequence
result.push(ch);
match chars.peek() {
Some(&'[') => {
result.push(chars.next().unwrap());
while let Some(&c) = chars.peek() {
result.push(chars.next().unwrap());
if c.is_ascii_alphabetic() {
break;
}
}
}
Some(&']') | Some(&'_') | Some(&'^') => {
result.push(chars.next().unwrap());
while let Some(c) = chars.next() {
result.push(c);
if c == '\x07' {
break;
}
if c == '\x1b' && chars.peek() == Some(&'\\') {
result.push(chars.next().unwrap());
break;
}
}
}
Some(&c) if c.is_ascii_alphabetic() || c == '(' || c == ')' => {
result.push(chars.next().unwrap());
if c == '(' || c == ')' {
if let Some(n) = chars.next() {
result.push(n);
}
}
}
_ => {}
}
} else {
let cw = UnicodeWidthChar::width(ch).unwrap_or(0);
if vis_w + cw > max_width {
break;
}
vis_w += cw;
result.push(ch);
}
}
result
}
/// Get the home directory.
pub fn home_dir() -> String {
std::env::var("HOME")
.or_else(|_| std::env::var("USERPROFILE"))
.unwrap_or_else(|_| "/root".to_string())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_strip_ansi_no_escapes() {
assert_eq!(strip_ansi("hello world"), "hello world");
}
#[test]
fn test_strip_ansi_csi() {
assert_eq!(strip_ansi("\x1b[31mred\x1b[0m"), "red");
assert_eq!(strip_ansi("\x1b[1;34mbold blue\x1b[0m"), "bold blue");
}
#[test]
fn test_strip_ansi_osc() {
assert_eq!(strip_ansi("\x1b]0;title\x07text"), "text");
}
#[test]
fn test_strip_ansi_complex() {
let s = "\x1b[36m\x1b[1mCPU\x1b[0m\x1b[0m: \x1b[0mi5-13600K";
assert_eq!(strip_ansi(s), "CPU: i5-13600K");
}
#[test]
fn test_visible_width_plain() {
assert_eq!(visible_width("hello"), 5);
assert_eq!(visible_width(""), 0);
}
#[test]
fn test_visible_width_with_ansi() {
assert_eq!(visible_width("\x1b[31mhello\x1b[0m"), 5);
}
#[test]
fn test_visible_width_unicode() {
// CJK characters are typically double-width
assert_eq!(visible_width("日本"), 4);
}
#[test]
fn test_pad_right() {
let padded = pad_right("hi", 10);
assert_eq!(visible_width(&padded), 10);
assert!(padded.starts_with("hi"));
}
#[test]
fn test_pad_right_already_wide() {
let padded = pad_right("hello world", 5);
assert_eq!(padded, "hello world");
}
#[test]
fn test_truncate_to_width_plain() {
let truncated = truncate_to_width("hello world", 5);
assert_eq!(truncated, "hello");
}
#[test]
fn test_truncate_to_width_with_ansi() {
let s = "\x1b[31mhello world\x1b[0m";
let truncated = truncate_to_width(s, 5);
// Should contain "hello" visible chars + ANSI prefix
assert_eq!(visible_width(&truncated), 5);
assert!(truncated.contains("hello"));
}
#[test]
fn test_truncate_to_width_no_cut() {
let s = "hi";
let truncated = truncate_to_width(s, 10);
assert_eq!(truncated, "hi");
}
#[test]
fn test_env_or() {
std::env::set_var("FETCHX_TEST_VAR", "test_value");
assert_eq!(env_or("FETCHX_TEST_VAR"), "test_value");
assert_eq!(env_or("FETCHX_NONEXISTENT_VAR_12345"), "");
std::env::remove_var("FETCHX_TEST_VAR");
}
#[test]
fn test_run_cmd() {
let result = run_cmd("echo", &["hello"]);
assert_eq!(result, "hello");
}
#[test]
fn test_run_cmd_failure() {
let result = run_cmd("nonexistent_command_12345", &[]);
assert_eq!(result, "");
}
#[test]
fn test_command_exists() {
assert!(command_exists("echo"));
assert!(!command_exists("nonexistent_command_12345"));
}
}