Show HN: Shelgon - 一个用 Rust 构建交互式 REPL Shell 的框架
Shelgon 是一个基于 Rust 的框架,用于构建交互式 REPL 应用和自定义 shell。它提供类型安全的命令执行、异步运行时集成、美观的终端 UI (由 `ratatui` 驱动) 以及丰富的输入处理功能,包括命令历史、光标移动、Tab 补全等。用户可以通过定义 `Executor` 和 `Context` 来定制 shell 的行为,并支持 STDIN 输入。文章还提供了安装方法和快速开始示例,以及构建自定义 shell 的指南和贡献方式。
Shelgon 是一个强大的 Rust 框架,用于构建交互式 REPL (Read-Eval-Print Loop) 应用和自定义 shell。 它提供了一个灵活、类型安全的基础,并使用 ratatui
内置了终端 UI 功能。
特性
- 🛡️ 类型安全的命令执行 - 就像 Shelgon 的保护壳一样,你的命令被包装在一个类型安全的接口中
- 🔄 异步运行时集成 - 构建在 tokio 之上,实现高性能异步操作
- 🎨 美观的 TUI - 由 ratatui 驱动,支持样式和颜色
- ⌨️ 丰富的输入处理 - 完整的键盘交互支持,包括:
- 命令历史
- 光标移动
- Tab 补全
- Ctrl+C/Ctrl+D 处理
- 📝 自定义上下文支持 - 使用你自己的上下文类型在命令之间维护状态
- 📥 STDIN 支持 - 处理需要多行输入的命令
安装
将 Shelgon 添加到你的 Cargo.toml
:
[dependencies]
shelgon = "0.1.0"
tokio = { version = "1.43.0", features = ["full"] }
anyhow = "1.0.95"
快速开始
创建一个简单的 echo shell:
use shelgon::{command, renderer};
struct EchoExecutor {}
impl command::New for EchoExecutor {
fn new() -> anyhow::Result<(Self, ())> {
Ok((Self {}, ()))
}
}
impl command::Execute for EchoExecutor {
type Context = ();
fn prompt(&self, _: &Self::Context) -> String {
"$".to_string()
}
fn execute(
&self,
_: &mut Self::Context,
cmd: command::CommandInput,
) -> anyhow::Result<command::OutputAction> {
Ok(command::OutputAction::Command(command::CommandOutput {
prompt: cmd.prompt,
command: cmd.command.clone(),
stdin: cmd.stdin.unwrap_or_default(),
stdout: vec![cmd.command],
stderr: Vec::new(),
}))
}
}
fn main() -> anyhow::Result<()> {
let rt = tokio::runtime::Runtime::new()?;
let app = renderer::App::<EchoExecutor>::new(rt)?;
app.execute()
}
进化指南:构建你自己的 Shell 
以下是如何使用 shelgon
构建一个像龙一样的 shell:
- 定义你的 Executor:创建一个实现
command::Execute
的类型 - 创建你的 Context:设计一个 context 类型来维护命令之间的状态
- 实现命令逻辑:在
execute
方法中添加你的命令执行逻辑 - 添加 Tab 补全:实现
completion
方法以获得智能建议 - 处理 STDIN:使用
prepare
方法来指示哪些命令需要输入
示例
查看 examples 目录,了解更高级的用法模式,包括:
echosh.rs
: 一个基本的 echo shell,展示了核心功能
贡献
欢迎贡献! 请随时提交 Pull Request。 在贡献之前,请:
- 检查现有的 issue 或创建一个新的 issue
- Fork 仓库
- 创建你的特性分支 (
git checkout -b feature/amazing-feature
) - 提交你的更改 (
git commit -m 'Add some amazing feature'
) - 推送到分支 (
git push origin feature/amazing-feature
) - 打开一个 Pull Request
许可协议
该项目根据 MIT 许可证获得许可 - 有关详细信息,请参阅 LICENSE 文件。 Built by Human, Documented by LLM.