feat: 新增现代化命令替代功能 v0.2.0

🎯 主要功能:
- 智能检测系统中已安装的现代化命令行工具
- 支持 44 种默认命令映射 (ls→eza, cat→bat, find→fd 等)
- 灵活的环境变量配置系统
- AI 提示词集成,优先推荐现代化工具
- 完整的配置状态显示

⚙️ 配置方式:
- 环境变量: AI_SHELL_MODERN_COMMANDS="ls:eza,cat:bat"
- .env 文件配置支持
- 动态配置检测和合并

🔧 技术实现:
- 新增 get_modern_commands() 配置管理
- 新增 get_available_modern_commands() 系统检测
- 新增 generate_modern_commands_prompt() 提示词生成
- 更新 AI agent 系统提示词
- 完善配置显示和测试脚本

📊 支持的现代化工具:
文件操作: eza, bat, fd, tree
文本处理: rg, sd, choose, delta
系统监控: procs, htop, ncdu, duf
网络工具: gping, httpie, aria2c
编辑器: nvim, micro
其他: zoxide, trash, ouch, pnpm
This commit is contained in:
2025-07-12 22:32:09 +08:00
parent 51cc93d408
commit c4d1510ce9
9 changed files with 660 additions and 24 deletions

View File

@ -9,3 +9,7 @@ AI_SHELL_MODEL=your_model_name
# 可选配置
# AI_SHELL_TIMEOUT=30
# AI_SHELL_MAX_RETRIES=3
# 现代化命令替代配置(可选)
# 格式: "旧命令:新命令,旧命令2:新命令2"
# AI_SHELL_MODERN_COMMANDS="ls:eza,cat:bat,find:fd,grep:rg,du:ncdu"

165
README重构完成总结.md Normal file
View File

@ -0,0 +1,165 @@
# README 重构完成总结
## 🎯 重构目标
将分散在多个文件中的项目说明整合到一个完整、结构化的中文 README.md 中,提升用户体验和项目可维护性。
## ✅ 已完成的工作
### 1. 文档整合
**删除的分散文档**
-`配置管理说明.md`
-`配置修复总结.md`
-`配置总结.md`
-`升级指南.md`
-`使用示例.md`
-`项目配置说明.md`
-`项目完成总结.md`
-`修改完成总结.md`
-`Git工作流程.md`
**整合到 README.md**
- ✅ 所有内容统一整合到一个文档中
- ✅ 使用中文编写,更符合用户习惯
- ✅ 结构化组织,便于查找和阅读
### 2. README.md 新结构
```
# AI Shell
├── 项目介绍和特性
├── 快速开始
├── 目录
├── 📦 安装说明
│ ├── 系统要求
│ ├── 方法一:从源码安装(推荐)
│ ├── 方法二:快速安装
│ ├── 验证安装
│ └── 卸载
├── ⚙️ 配置管理
│ ├── 配置文件结构
│ ├── 配置项说明
│ ├── 配置方法
│ ├── 配置优先级
│ └── 查看当前配置
├── 💡 使用示例
│ ├── 基础命令
│ ├── 英文示例
│ ├── 高级用法
│ ├── 交互式确认
│ └── 配置和帮助
├── 🛠️ 开发指南
│ ├── 项目结构
│ ├── 开发环境设置
│ ├── 可用的开发命令
│ └── 代码修改流程
├── 🔄 升级维护
│ ├── 快速升级
│ ├── 版本管理
│ ├── 自动化发布
│ ├── 完整的升级流程
│ ├── 配置迁移
│ └── 验证升级
├── 🌿 Git 工作流
│ ├── 仓库信息
│ ├── 基本 Git 操作
│ ├── 提交信息规范
│ ├── 分支管理
│ ├── 版本发布流程
│ └── 使用 Makefile 简化操作
├── 🔧 故障排除
│ ├── 常见问题
│ ├── 调试模式
│ └── 重新安装
└── 🤝 贡献指南
├── 如何贡献
├── 开发规范
├── 报告问题
└── 许可证
```
### 3. 内容优化
**语言本地化**
- ✅ 全部使用中文编写
- ✅ 保留必要的英文命令和代码示例
- ✅ 符合中文用户的阅读习惯
**结构优化**
- ✅ 清晰的目录结构
- ✅ 逐步递进的内容组织
- ✅ 丰富的示例和说明
- ✅ 完整的故障排除指南
**内容完整性**
- ✅ 从安装到使用的完整流程
- ✅ 开发和维护的详细指南
- ✅ Git 工作流和版本管理
- ✅ 配置管理和安全性说明
## 📊 重构效果
### 文件数量变化
- **重构前**: 1 个 README.md + 9 个分散文档 = 10 个文件
- **重构后**: 1 个完整的 README.md = 1 个文件
- **减少**: 9 个文件,简化了项目结构
### 内容统计
- **总行数**: 约 770 行
- **章节数**: 8 个主要章节
- **子章节数**: 40+ 个子章节
- **代码示例**: 100+ 个
### 用户体验提升
-**一站式文档**: 所有信息集中在一个文件中
-**中文友好**: 完全中文化的说明
-**结构清晰**: 目录导航,便于快速定位
-**内容完整**: 覆盖所有使用场景
-**示例丰富**: 大量实用的代码示例
## 🎯 最终项目结构
```
ai-shell/
├── .env.example # 配置模板
├── .gitignore # Git 忽略文件
├── Makefile # 开发工具
├── README.md # 📖 完整项目文档(重构后)
├── pyproject.toml # 项目配置
├── uv.toml # UV 配置
├── uv.lock # 依赖锁定
├── quick_upgrade.sh # 快速升级脚本
├── ai_shell/ # 主包
│ ├── __init__.py
│ ├── main.py
│ ├── config.py
│ ├── agent.py
│ └── models.py
├── scripts/ # 工具脚本
│ ├── bump_version.py
│ └── release.sh
└── dist/ # 构建产物
```
## 🌟 重构亮点
1. **文档统一**: 从 10 个分散文件整合为 1 个完整文档
2. **中文本地化**: 全面中文化,提升中文用户体验
3. **结构优化**: 清晰的层次结构和目录导航
4. **内容完整**: 覆盖安装、配置、使用、开发、维护全流程
5. **示例丰富**: 大量实用的命令和代码示例
6. **维护简化**: 减少文档维护成本,避免内容重复
## 📈 后续建议
1. **持续更新**: 随着功能更新及时维护 README.md
2. **用户反馈**: 收集用户反馈,持续优化文档结构
3. **多语言支持**: 如有需要,可考虑添加英文版本
4. **视频教程**: 可考虑制作配套的视频教程
---
🎉 **README.md 重构完成!**
现在用户可以通过一个完整、结构化的中文文档了解和使用 AI Shell 项目的所有功能。

View File

@ -4,7 +4,7 @@ AI Shell - AI-powered shell command generator using DeepSeek V3
A command-line tool that generates shell commands from natural language descriptions.
"""
__version__ = "0.1.0"
__version__ = "0.2.0"
__author__ = "AI Shell Team"
__email__ = "ai-shell@example.com"
__description__ = "AI-powered shell command generator using DeepSeek V3"

View File

@ -6,11 +6,12 @@ from textwrap import dedent
from pydantic_ai import Agent
from pydantic_ai.models.openai import OpenAIModel
from .config import get_model, setup_environment
from .config import get_model, setup_environment, generate_modern_commands_prompt
from .models import Answer
# System prompt for the AI agent
SYSTEM_PROMPT = dedent(
def create_system_prompt() -> str:
"""Create system prompt with modern commands preferences"""
base_prompt = dedent(
"""\
You are a professional developer specializing in shell commands.
Your task is to generate the correct shell commands based on the
@ -30,6 +31,11 @@ SYSTEM_PROMPT = dedent(
"""
)
# Add modern commands preferences
modern_commands_prompt = generate_modern_commands_prompt()
return base_prompt + modern_commands_prompt
def create_agent() -> Agent:
"""Create and configure the AI agent"""
# Setup environment variables
@ -38,10 +44,10 @@ def create_agent() -> Agent:
# Create OpenAI compatible model
model = OpenAIModel(get_model())
# Create agent
# Create agent with dynamic system prompt
agent = Agent(
model=model,
system_prompt=SYSTEM_PROMPT,
system_prompt=create_system_prompt(),
output_type=Answer,
)

View File

@ -61,6 +61,158 @@ def get_max_retries() -> int:
"""Get max retries from environment"""
return int(os.getenv("AI_SHELL_MAX_RETRIES", "3"))
def get_modern_commands() -> dict:
"""Get modern command alternatives configuration"""
# Default modern command alternatives
default_alternatives = {
"ls": "eza", # Modern ls replacement
"cat": "bat", # Syntax highlighting cat
"find": "fd", # Fast and user-friendly find
"grep": "rg", # Ripgrep - faster grep
"du": "ncdu", # Interactive disk usage
"df": "duf", # Modern df with better output
"ps": "procs", # Modern ps replacement
"top": "htop", # Interactive process viewer
"ping": "gping", # Ping with graph
"curl": "httpie", # User-friendly HTTP client
"wget": "aria2c", # Multi-connection downloader
"diff": "delta", # Better diff with syntax highlighting
"tree": "tree", # Keep tree as is (already modern)
"sed": "sd", # Simpler sed alternative
"awk": "choose", # Human-friendly awk alternative
"cut": "choose", # Alternative to cut
"sort": "sort", # Keep sort as is
"uniq": "uniq", # Keep uniq as is
"head": "head", # Keep head as is
"tail": "tail", # Keep tail as is
"less": "bat", # Use bat for paging too
"more": "bat", # Use bat for paging
"vim": "nvim", # Modern vim
"nano": "micro", # Modern nano alternative
"cd": "zoxide", # Smart cd with frecency
"cp": "cp", # Keep cp as is (or could use rsync)
"mv": "mv", # Keep mv as is
"rm": "trash", # Safer deletion (trash-cli)
"mkdir": "mkdir", # Keep mkdir as is
"rmdir": "rmdir", # Keep rmdir as is
"chmod": "chmod", # Keep chmod as is
"chown": "chown", # Keep chown as is
"tar": "ouch", # Universal archive tool
"zip": "ouch", # Universal archive tool
"unzip": "ouch", # Universal archive tool
"ssh": "ssh", # Keep ssh as is
"scp": "rsync", # More efficient file transfer
"rsync": "rsync", # Keep rsync as is
"git": "git", # Keep git as is
"docker": "docker", # Keep docker as is
"python": "python", # Keep python as is
"node": "node", # Keep node as is
"npm": "pnpm", # Faster npm alternative
"yarn": "pnpm", # Faster yarn alternative
}
# Try to load custom alternatives from environment or config file
custom_alternatives_str = os.getenv("AI_SHELL_MODERN_COMMANDS", "")
custom_alternatives = {}
if custom_alternatives_str:
try:
# Parse format: "old1:new1,old2:new2,old3:new3"
pairs = custom_alternatives_str.split(",")
for pair in pairs:
if ":" in pair:
old_cmd, new_cmd = pair.strip().split(":", 1)
custom_alternatives[old_cmd.strip()] = new_cmd.strip()
except Exception:
pass # Ignore parsing errors
# Merge default and custom alternatives
alternatives = default_alternatives.copy()
alternatives.update(custom_alternatives)
return alternatives
def get_available_modern_commands() -> dict:
"""Get only the modern commands that are actually installed on the system"""
import shutil
all_alternatives = get_modern_commands()
available_alternatives = {}
for old_cmd, new_cmd in all_alternatives.items():
# Check if the modern command is actually available
if shutil.which(new_cmd):
available_alternatives[old_cmd] = new_cmd
# If modern command not available, keep the original
elif shutil.which(old_cmd):
available_alternatives[old_cmd] = old_cmd
return available_alternatives
def generate_modern_commands_prompt() -> str:
"""Generate prompt text about available modern command alternatives"""
available_commands = get_available_modern_commands()
if not available_commands:
return ""
prompt_parts = [
"\n\n**IMPORTANT: Modern Command Preferences**",
"When generating shell commands, prefer these modern alternatives when available:",
""
]
# Group by categories for better readability
categories = {
"文件操作": ["ls", "cat", "find", "tree", "cp", "mv", "rm"],
"文本处理": ["grep", "sed", "awk", "cut", "sort", "uniq", "head", "tail", "less", "more", "diff"],
"系统监控": ["ps", "top", "du", "df"],
"网络工具": ["ping", "curl", "wget"],
"编辑器": ["vim", "nano"],
"导航": ["cd"],
"压缩工具": ["tar", "zip", "unzip"],
"包管理": ["npm", "yarn"],
"其他": []
}
for category, commands in categories.items():
category_commands = []
for cmd in commands:
if cmd in available_commands and available_commands[cmd] != cmd:
category_commands.append(f" - Use `{available_commands[cmd]}` instead of `{cmd}`")
if category_commands:
prompt_parts.append(f"**{category}:**")
prompt_parts.extend(category_commands)
prompt_parts.append("")
# Add remaining commands not in categories
other_commands = []
categorized_commands = set()
for commands in categories.values():
categorized_commands.update(commands)
for old_cmd, new_cmd in available_commands.items():
if old_cmd not in categorized_commands and new_cmd != old_cmd:
other_commands.append(f" - Use `{new_cmd}` instead of `{old_cmd}`")
if other_commands:
prompt_parts.append("**其他工具:**")
prompt_parts.extend(other_commands)
prompt_parts.append("")
prompt_parts.extend([
"These modern tools typically provide:",
"- Better performance and speed",
"- More intuitive syntax and output",
"- Enhanced features and functionality",
"- Better error messages and user experience",
"",
"Always prioritize these modern alternatives when they fulfill the user's requirements."
])
return "\n".join(prompt_parts)
def setup_environment() -> None:
"""Setup environment variables for OpenAI client"""
os.environ["OPENAI_API_KEY"] = get_api_key()

View File

@ -80,7 +80,8 @@ def create_parser() -> argparse.ArgumentParser:
def show_config() -> None:
"""Show current configuration"""
from .config import get_api_key, get_base_url, get_model, get_timeout, get_max_retries, validate_config
from .config import (get_api_key, get_base_url, get_model, get_timeout,
get_max_retries, validate_config, get_available_modern_commands)
print("AI Shell Configuration:")
print(f" Model: {get_model()}")
@ -110,6 +111,30 @@ def show_config() -> None:
print(" AI_SHELL_MODEL - Model name")
print(" AI_SHELL_TIMEOUT - Request timeout (seconds)")
print(" AI_SHELL_MAX_RETRIES - Maximum retry attempts")
print(" AI_SHELL_MODERN_COMMANDS - Custom modern command alternatives")
# Show modern commands configuration
modern_commands = get_available_modern_commands()
if modern_commands:
print(f"\n现代化命令替代 ({len(modern_commands)} 个可用):")
# Group commands for better display
active_alternatives = {k: v for k, v in modern_commands.items() if k != v}
unchanged_commands = {k: v for k, v in modern_commands.items() if k == v}
if active_alternatives:
print(" 已启用的替代:")
for old_cmd, new_cmd in sorted(active_alternatives.items()):
print(f" {old_cmd}{new_cmd}")
if unchanged_commands:
print(f" 保持原样: {', '.join(sorted(unchanged_commands.keys()))}")
print("\n 自定义配置格式:")
print(" export AI_SHELL_MODERN_COMMANDS=\"old1:new1,old2:new2\"")
print(" 例如: export AI_SHELL_MODERN_COMMANDS=\"ls:exa,cat:bat,find:fd\"")
else:
print("\n现代化命令替代: 未检测到可用的现代化工具")
def main() -> None:
"""Main entry point"""

View File

@ -1,6 +1,6 @@
[project]
name = "ai-shell"
version = "0.1.0"
version = "0.2.0"
description = "AI-powered shell command generator using DeepSeek V3"
authors = [
{name = "AI Shell Team", email = "ai-shell@example.com"}

92
scripts/test_modern_commands.py Executable file
View File

@ -0,0 +1,92 @@
#!/usr/bin/env python3
"""
测试现代化命令替代功能
"""
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
from ai_shell.config import (
get_modern_commands,
get_available_modern_commands,
generate_modern_commands_prompt
)
def test_modern_commands():
"""测试现代化命令配置"""
print("🧪 测试现代化命令替代功能\n")
# 测试获取所有配置的现代化命令
print("1. 所有配置的现代化命令:")
all_commands = get_modern_commands()
for old_cmd, new_cmd in sorted(all_commands.items()):
status = "" if old_cmd != new_cmd else "➡️"
print(f" {status} {old_cmd}{new_cmd}")
print(f" 总计: {len(all_commands)} 个命令\n")
# 测试获取系统中可用的现代化命令
print("2. 系统中可用的现代化命令:")
available_commands = get_available_modern_commands()
active_alternatives = {k: v for k, v in available_commands.items() if k != v}
unchanged_commands = {k: v for k, v in available_commands.items() if k == v}
if active_alternatives:
print(" 已启用的替代:")
for old_cmd, new_cmd in sorted(active_alternatives.items()):
print(f"{old_cmd}{new_cmd}")
if unchanged_commands:
print(f" 保持原样: {', '.join(sorted(unchanged_commands.keys()))}")
print(f" 可用命令总计: {len(available_commands)}\n")
# 测试生成提示词
print("3. 生成的 AI 提示词:")
prompt = generate_modern_commands_prompt()
if prompt:
print(prompt)
else:
print(" 无可用的现代化命令替代")
def test_custom_config():
"""测试自定义配置"""
print("\n" + "="*60)
print("🔧 测试自定义配置")
# 设置自定义环境变量
original_env = os.environ.get("AI_SHELL_MODERN_COMMANDS", "")
os.environ["AI_SHELL_MODERN_COMMANDS"] = "ls:exa,cat:bat,find:fd,test:custom"
print(f"设置环境变量: AI_SHELL_MODERN_COMMANDS={os.environ['AI_SHELL_MODERN_COMMANDS']}")
# 重新导入模块以获取新配置
import importlib
import ai_shell.config
importlib.reload(ai_shell.config)
from ai_shell.config import get_modern_commands
custom_commands = get_modern_commands()
print("\n自定义配置结果:")
custom_overrides = ["ls", "cat", "find", "test"]
for cmd in custom_overrides:
if cmd in custom_commands:
print(f"{cmd}{custom_commands[cmd]}")
# 恢复原始环境变量
if original_env:
os.environ["AI_SHELL_MODERN_COMMANDS"] = original_env
else:
os.environ.pop("AI_SHELL_MODERN_COMMANDS", None)
if __name__ == "__main__":
test_modern_commands()
test_custom_config()
print("\n" + "="*60)
print("✅ 测试完成!")
print("\n使用方法:")
print("1. 查看当前配置: ai --config")
print("2. 设置自定义替代: export AI_SHELL_MODERN_COMMANDS=\"ls:eza,cat:bat\"")
print("3. 测试命令生成: ai \"列出文件\"")

View File

@ -0,0 +1,192 @@
# 现代化命令替代功能说明
## 🎯 功能概述
AI Shell v0.2.0 新增了现代化命令替代功能,可以让 AI 优先推荐更现代、更高效的命令行工具,提升用户体验和工作效率。
## ✨ 主要特性
- 🔧 **智能检测**: 自动检测系统中已安装的现代化工具
- ⚙️ **灵活配置**: 支持自定义命令替代映射
- 🎯 **AI 优化**: 将现代化命令偏好集成到 AI 提示词中
- 📊 **状态显示**: 通过 `ai --config` 查看当前配置状态
- 🔄 **动态更新**: 支持环境变量实时配置
## 📋 默认支持的现代化工具
### 文件操作
- `ls``eza` - 现代化的 ls 替代品,支持图标和颜色
- `cat``bat` - 带语法高亮的 cat
- `find``fd` - 更快更友好的 find
- `tree``tree` - 保持原样(已经很现代)
### 文本处理
- `grep``rg` (ripgrep) - 更快的文本搜索
- `sed``sd` - 更简单的 sed 替代
- `awk``choose` - 人性化的 awk 替代
- `cut``choose` - cut 的替代
- `diff``delta` - 带语法高亮的 diff
- `less`/`more``bat` - 用于分页显示
### 系统监控
- `ps``procs` - 现代化的进程查看器
- `top``htop` - 交互式进程监控
- `du``ncdu` - 交互式磁盘使用分析
- `df``duf` - 更好的磁盘空间显示
### 网络工具
- `ping``gping` - 带图形的 ping
- `curl``httpie` - 更友好的 HTTP 客户端
- `wget``aria2c` - 多连接下载器
### 编辑器
- `vim``nvim` - 现代化的 vim
- `nano``micro` - 现代化的 nano 替代
### 其他工具
- `cd``zoxide` - 智能目录跳转
- `rm``trash` - 安全删除(移到回收站)
- `tar`/`zip`/`unzip``ouch` - 通用压缩工具
- `npm`/`yarn``pnpm` - 更快的包管理器
## ⚙️ 配置方法
### 1. 查看当前配置
```bash
ai --config
```
### 2. 使用环境变量配置
```bash
# 设置自定义替代
export AI_SHELL_MODERN_COMMANDS="ls:eza,cat:bat,find:fd,grep:rg"
# 查看效果
ai --config
```
### 3. 在 .env 文件中配置
编辑 `.env` 文件:
```bash
# 现代化命令替代配置
AI_SHELL_MODERN_COMMANDS="ls:eza,cat:bat,find:fd,grep:rg,du:ncdu"
```
### 4. 配置格式说明
```bash
# 格式: "旧命令:新命令,旧命令2:新命令2"
AI_SHELL_MODERN_COMMANDS="old1:new1,old2:new2,old3:new3"
# 示例
AI_SHELL_MODERN_COMMANDS="ls:eza,cat:bat,find:fd"
```
## 🔍 工作原理
1. **系统检测**: 启动时检测系统中已安装的现代化工具
2. **配置合并**: 合并默认配置和用户自定义配置
3. **提示词生成**: 将可用的现代化命令添加到 AI 提示词中
4. **AI 优化**: AI 在生成命令时优先考虑现代化替代
## 📊 配置示例
### 基础配置
```bash
export AI_SHELL_MODERN_COMMANDS="ls:eza,cat:bat"
```
### 完整配置
```bash
export AI_SHELL_MODERN_COMMANDS="ls:eza,cat:bat,find:fd,grep:rg,du:ncdu,df:duf,ps:procs,top:htop,ping:gping,vim:nvim"
```
### 开发者配置
```bash
export AI_SHELL_MODERN_COMMANDS="ls:eza,cat:bat,find:fd,grep:rg,npm:pnpm,yarn:pnpm,curl:httpie"
```
## 🧪 测试功能
### 1. 测试脚本
```bash
# 运行测试脚本
uv run python scripts/test_modern_commands.py
```
### 2. 实际使用测试
```bash
# 设置配置
export AI_SHELL_MODERN_COMMANDS="ls:eza,find:fd"
# 测试命令生成
ai "列出当前目录文件"
ai "查找 Python 文件"
```
## 🎯 使用效果
### 传统命令
```bash
# AI 可能生成
ls -la
find . -name "*.py"
```
### 现代化命令
```bash
# AI 会优先生成
eza -la
fd "*.py"
```
## 🔧 故障排除
### 1. 命令未生效
```bash
# 检查配置
ai --config
# 确认环境变量
echo $AI_SHELL_MODERN_COMMANDS
```
### 2. 工具未安装
```bash
# 检查工具是否安装
which eza
which bat
which fd
```
### 3. 配置格式错误
```bash
# 正确格式
AI_SHELL_MODERN_COMMANDS="ls:eza,cat:bat"
# 错误格式
AI_SHELL_MODERN_COMMANDS="ls=eza;cat=bat" # 错误
```
## 📈 版本历史
- **v0.2.0**: 新增现代化命令替代功能
- 支持 44 种默认命令映射
- 自动系统检测
- 环境变量配置
- AI 提示词集成
## 🚀 未来计划
- [ ] 支持配置文件管理
- [ ] 添加更多现代化工具
- [ ] 工具安装建议
- [ ] 性能基准测试
- [ ] 社区配置分享
---
💡 **提示**: 这个功能让 AI 更倾向于推荐现代化、高效的命令行工具,提升您的命令行体验!