Skip to content

Commit fd697ec

Browse files
superyngoclaude
andcommitted
feat: v0.4.2 - 移除管道偵測,簡化顏色控制邏輯
## 主要變更 ### 移除自動顏色控制功能 - 移除 `ColorMode` 枚舉(Auto/Always/Never) - 移除 `is_redirected_to_file()` 函數(TTY 和管道檢測) - 移除 `--color` 參數 - 簡化語法高亮控制:現在只透過 `--no-highlight` 參數控制 ### 行為變更 **之前 (v0.4.1)**: - `--color auto`(預設):終端和管道有顏色,文件重定向無顏色 - `--color always`:強制輸出顏色 - `--color never`:禁用顏色 **現在 (v0.4.2)**: - 預設:始終啟用語法高亮(包括管道和文件重定向) - `--no-highlight`:完全關閉語法高亮 ### 優點 - ✅ 更簡單直觀的使用體驗 - ✅ 移除複雜的 TTY 檢測邏輯(Unix fstat, Windows IsTerminal) - ✅ 減少程式碼複雜度 - ✅ 用戶可以自行決定何時需要語法高亮 ### 文檔更新 - 更新 README.md 移除 `--color` 參數說明 - 更新 help 信息 - 移除過時的範例和說明 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
1 parent a57fbad commit fd697ec

3 files changed

Lines changed: 7 additions & 99 deletions

File tree

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[package]
22
name = "cate"
3-
version = "0.4.1"
3+
version = "0.4.2"
44
edition = "2021"
55
authors = ["wen"]
66
description = "A lightweight CLI tool to display file contents with encoding support and syntax highlighting"

README.md

Lines changed: 2 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ A lightweight CLI tool to display file contents with encoding support and syntax
1111
- 📝 **Line Numbers**: Optional line number display
1212
- 🚀 **Lightweight & Fast**: Only 2.1 MB binary size with streaming architecture
1313
-**High Performance**: Instant output for large files with line-by-line processing
14-
- 🎨 **Smart Color Output**: Auto-detects TTY to avoid polluting redirected files
1514
- 🔧 **Debug Mode**: Detailed encoding detection information
1615
- 📋 **Stdin Support**: Read from pipes and redirects with language specification
1716
- 🎯 **Manual Language Selection**: Override auto-detection with `-l/--language` flag
@@ -141,7 +140,6 @@ Syntax Highlighting:
141140
--no-highlight Disable syntax highlighting
142141
--theme <THEME> Set color theme (default: base16-eighties.dark)
143142
-l, --language <LANG> Specify syntax language (e.g., rust, python, js)
144-
--color <WHEN> When to use colors: auto, always, never (default: auto)
145143
--list-themes List all available themes
146144
--list-syntaxes List all supported languages
147145
```
@@ -245,12 +243,6 @@ cat script | cate -l js # JavaScript by extension
245243
# Override file extension detection
246244
cate config.txt -l yaml # Treat .txt as YAML
247245

248-
# Color output control
249-
cate file.rs > output.txt # Auto-disables colors when redirected
250-
cate file.rs --color always > out.txt # Force colors in output
251-
cate file.rs --color always | less -R # Use with color-aware pager
252-
cate file.rs --color never # Disable colors completely
253-
254246
# Convert encoding and display with highlighting
255247
iconv -f gbk -t utf-8 input.py | cate -l python
256248

@@ -295,15 +287,14 @@ cargo test -- --nocapture
295287
- 💾 **Low memory usage**: Only buffers single lines, not entire files
296288
- 🎯 **Stateful highlighting**: Correctly handles multi-line syntax (comments, strings, etc.)
297289
- 🛡️ **Long line protection**: Automatically skips highlighting for lines >16KB
298-
- 🎨 **Smart TTY detection**: Auto-disables colors when output is redirected
299290

300291
### Performance Example
301292
```bash
302293
# 10,000 line file processes in ~0.3 seconds with instant first-line output
303294
cate large_file.rs
304295

305-
# Redirecting to file automatically disables color codes (no pollution)
306-
cate large_file.rs > output.txt
296+
# Use --no-highlight to disable syntax highlighting for faster plain text output
297+
cate large_file.txt --no-highlight
307298
```
308299

309300
## Why cate?
@@ -314,7 +305,6 @@ The name "cate" combines "cat" (the Unix command) with "encoding", making it eas
314305
-**Syntax highlighting** for 219 programming languages
315306
-**7 beautiful themes** with true color support
316307
-**Streaming architecture** for instant output on large files
317-
-**Smart color handling** - auto-disables when redirected to files
318308
- ✅ Automatic encoding detection and conversion
319309
- ✅ Support for non-UTF-8 files (GBK, Big5, Shift-JIS, etc.)
320310
- ✅ Manual language selection with `-l` flag

src/main.rs

Lines changed: 4 additions & 86 deletions
Original file line numberDiff line numberDiff line change
@@ -7,76 +7,6 @@ use pico_args::Arguments;
77
use std::io::Write;
88
use std::path::PathBuf;
99

10-
/// 顏色輸出模式
11-
#[derive(Debug, Clone, Copy, PartialEq)]
12-
enum ColorMode {
13-
Auto, // 自動檢測(TTY 時啟用)
14-
Always, // 總是輸出顏色
15-
Never, // 永不輸出顏色
16-
}
17-
18-
impl ColorMode {
19-
fn from_str(s: &str) -> Result<Self> {
20-
match s.to_lowercase().as_str() {
21-
"auto" => Ok(ColorMode::Auto),
22-
"always" => Ok(ColorMode::Always),
23-
"never" => Ok(ColorMode::Never),
24-
_ => Err(anyhow::anyhow!(
25-
"Invalid color mode: '{}'. Use 'auto', 'always', or 'never'",
26-
s
27-
)),
28-
}
29-
}
30-
31-
/// 根據模式和輸出目標決定是否啟用顏色
32-
/// auto 模式:終端和管道有顏色,文件重定向無顏色
33-
fn should_colorize(&self) -> bool {
34-
match self {
35-
ColorMode::Auto => !is_redirected_to_file(),
36-
ColorMode::Always => true,
37-
ColorMode::Never => false,
38-
}
39-
}
40-
}
41-
42-
/// 檢測 stdout 是否重定向到普通文件
43-
/// 返回 true 表示重定向到文件(應該禁用顏色)
44-
/// 返回 false 表示終端或管道(應該啟用顏色)
45-
fn is_redirected_to_file() -> bool {
46-
use std::io::IsTerminal;
47-
48-
// 如果是終端,肯定不是文件重定向
49-
if std::io::stdout().is_terminal() {
50-
return false;
51-
}
52-
53-
// 不是終端,需要進一步檢查是管道還是文件
54-
// 在 Unix 系統上,可以用 fstat 檢查
55-
#[cfg(unix)]
56-
{
57-
use std::os::unix::io::AsRawFd;
58-
let fd = std::io::stdout().as_raw_fd();
59-
60-
unsafe {
61-
let mut stat: libc::stat = std::mem::zeroed();
62-
if libc::fstat(fd, &mut stat) == 0 {
63-
// S_ISREG: 普通文件
64-
// S_ISFIFO: 管道(FIFO)
65-
// S_ISCHR: 字符設備(終端)
66-
return (stat.st_mode & libc::S_IFMT) == libc::S_IFREG;
67-
}
68-
}
69-
// Unix 檢查失敗,保守處理
70-
return false;
71-
}
72-
73-
// Windows:不是 TTY 就禁用顏色(無法區分管道和文件)
74-
#[cfg(not(unix))]
75-
{
76-
true
77-
}
78-
}
79-
8010
struct Args {
8111
files: Vec<PathBuf>,
8212
encoding: Option<String>,
@@ -87,7 +17,6 @@ struct Args {
8717
no_highlight: bool, // --no-highlight: 停用語法高亮
8818
theme: Option<String>, // --theme: 指定主題
8919
language: Option<String>, // -l, --language: 指定語法語言
90-
color_mode: ColorMode, // --color: 顏色輸出模式
9120
}
9221

9322
impl Args {
@@ -123,13 +52,6 @@ impl Args {
12352
std::process::exit(0);
12453
}
12554

126-
// 解析 color mode
127-
let color_mode = if let Some(color_str) = args.opt_value_from_str::<_, String>("--color")? {
128-
ColorMode::from_str(&color_str)?
129-
} else {
130-
ColorMode::Auto // 默認為 auto
131-
};
132-
13355
Ok(Args {
13456
encoding: args.opt_value_from_str(["-e", "--encoding"])?,
13557
show_line_numbers: args.contains(["-n", "--number"]),
@@ -139,7 +61,6 @@ impl Args {
13961
no_highlight: args.contains("--no-highlight"),
14062
theme: args.opt_value_from_str("--theme")?,
14163
language: args.opt_value_from_str(["-l", "--language"])?,
142-
color_mode,
14364

14465
files: args.finish().into_iter().map(PathBuf::from).collect(),
14566
})
@@ -173,8 +94,8 @@ fn main() -> Result<()> {
17394
eprintln!("[DEBUG] ---");
17495
}
17596

176-
// 決定是否啟用語法高亮(考慮 --no-highlight 和 TTY 檢測)
177-
let enable_highlighting = !args.no_highlight && args.color_mode.should_colorize();
97+
// 決定是否啟用語法高亮
98+
let enable_highlighting = !args.no_highlight;
17899

179100
// 使用 Cursor 將字符串轉為 BufRead
180101
let reader = std::io::Cursor::new(content);
@@ -209,8 +130,8 @@ fn main() -> Result<()> {
209130
eprintln!("[DEBUG] ---");
210131
}
211132

212-
// 決定是否啟用語法高亮(考慮 --no-highlight 和 TTY 檢測)
213-
let enable_highlighting = !args.no_highlight && args.color_mode.should_colorize();
133+
// 決定是否啟用語法高亮
134+
let enable_highlighting = !args.no_highlight;
214135

215136
// 使用 Cursor 將字符串轉為 BufRead
216137
let reader = std::io::Cursor::new(content);
@@ -255,7 +176,6 @@ fn print_help() {
255176
println!(" --no-highlight Disable syntax highlighting");
256177
println!(" --theme <THEME> Set color theme (default: base16-eighties.dark)");
257178
println!(" -l, --language <LANG> Specify syntax language (e.g., rust, python)");
258-
println!(" --color <WHEN> When to use colors: auto, always, never (default: auto)");
259179
println!(" --list-themes List all available themes");
260180
println!(" --list-syntaxes List all supported languages");
261181
println!();
@@ -266,8 +186,6 @@ fn print_help() {
266186
println!(" cate -e gbk chinese.txt # Specify GBK encoding");
267187
println!(" cat file.js | cate # Read from stdin");
268188
println!(" cat script | cate -l python # Specify language for stdin");
269-
println!(" cate file.rs > output.txt # Auto-disable colors when redirected");
270-
println!(" cate file.rs --color=always | less -R # Force colors for pager");
271189
println!();
272190
println!("SUPPORTED ENCODINGS:");
273191
encoder::list_encodings();

0 commit comments

Comments
 (0)