mirror of
https://github.com/lWolvesl/claw-code.git
synced 2026-04-02 21:41:52 +08:00
feat: Rust port of Claude Code CLI
Crates: - api: Anthropic Messages API client with SSE streaming - tools: Claude-compatible tool implementations (Bash, Read, Write, Edit, Glob, Grep + extended suite) - runtime: conversation loop, session persistence, permissions, system prompt builder - rusty-claude-cli: terminal UI with markdown rendering, syntax highlighting, spinners - commands: subcommand definitions - compat-harness: upstream TS parity verification All crates pass cargo fmt/clippy/test.
This commit is contained in:
290
rust/crates/rusty-claude-cli/src/app.rs
Normal file
290
rust/crates/rusty-claude-cli/src/app.rs
Normal file
@@ -0,0 +1,290 @@
|
||||
use std::io::{self, Write};
|
||||
use std::path::PathBuf;
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::args::{OutputFormat, PermissionMode};
|
||||
use crate::input::LineEditor;
|
||||
use crate::render::{Spinner, TerminalRenderer};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct SessionConfig {
|
||||
pub model: String,
|
||||
pub permission_mode: PermissionMode,
|
||||
pub config: Option<PathBuf>,
|
||||
pub output_format: OutputFormat,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct SessionState {
|
||||
pub turns: usize,
|
||||
pub compacted_messages: usize,
|
||||
pub last_model: String,
|
||||
}
|
||||
|
||||
impl SessionState {
|
||||
#[must_use]
|
||||
pub fn new(model: impl Into<String>) -> Self {
|
||||
Self {
|
||||
turns: 0,
|
||||
compacted_messages: 0,
|
||||
last_model: model.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum CommandResult {
|
||||
Continue,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum SlashCommand {
|
||||
Help,
|
||||
Status,
|
||||
Compact,
|
||||
Unknown(String),
|
||||
}
|
||||
|
||||
impl SlashCommand {
|
||||
#[must_use]
|
||||
pub fn parse(input: &str) -> Option<Self> {
|
||||
let trimmed = input.trim();
|
||||
if !trimmed.starts_with('/') {
|
||||
return None;
|
||||
}
|
||||
|
||||
let command = trimmed
|
||||
.trim_start_matches('/')
|
||||
.split_whitespace()
|
||||
.next()
|
||||
.unwrap_or_default();
|
||||
Some(match command {
|
||||
"help" => Self::Help,
|
||||
"status" => Self::Status,
|
||||
"compact" => Self::Compact,
|
||||
other => Self::Unknown(other.to_string()),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct SlashCommandHandler {
|
||||
command: SlashCommand,
|
||||
summary: &'static str,
|
||||
}
|
||||
|
||||
const SLASH_COMMAND_HANDLERS: &[SlashCommandHandler] = &[
|
||||
SlashCommandHandler {
|
||||
command: SlashCommand::Help,
|
||||
summary: "Show command help",
|
||||
},
|
||||
SlashCommandHandler {
|
||||
command: SlashCommand::Status,
|
||||
summary: "Show current session status",
|
||||
},
|
||||
SlashCommandHandler {
|
||||
command: SlashCommand::Compact,
|
||||
summary: "Compact local session history",
|
||||
},
|
||||
];
|
||||
|
||||
pub struct CliApp {
|
||||
config: SessionConfig,
|
||||
renderer: TerminalRenderer,
|
||||
state: SessionState,
|
||||
}
|
||||
|
||||
impl CliApp {
|
||||
#[must_use]
|
||||
pub fn new(config: SessionConfig) -> Self {
|
||||
let state = SessionState::new(config.model.clone());
|
||||
Self {
|
||||
config,
|
||||
renderer: TerminalRenderer::new(),
|
||||
state,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run_repl(&mut self) -> io::Result<()> {
|
||||
let editor = LineEditor::new("› ");
|
||||
println!("Rusty Claude CLI interactive mode");
|
||||
println!("Type /help for commands. Shift+Enter or Ctrl+J inserts a newline.");
|
||||
|
||||
while let Some(input) = editor.read_line()? {
|
||||
if input.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
self.handle_submission(&input, &mut io::stdout())?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn run_prompt(&mut self, prompt: &str, out: &mut impl Write) -> io::Result<()> {
|
||||
self.render_response(prompt, out)
|
||||
}
|
||||
|
||||
pub fn handle_submission(
|
||||
&mut self,
|
||||
input: &str,
|
||||
out: &mut impl Write,
|
||||
) -> io::Result<CommandResult> {
|
||||
if let Some(command) = SlashCommand::parse(input) {
|
||||
return self.dispatch_slash_command(command, out);
|
||||
}
|
||||
|
||||
self.state.turns += 1;
|
||||
self.render_response(input, out)?;
|
||||
Ok(CommandResult::Continue)
|
||||
}
|
||||
|
||||
fn dispatch_slash_command(
|
||||
&mut self,
|
||||
command: SlashCommand,
|
||||
out: &mut impl Write,
|
||||
) -> io::Result<CommandResult> {
|
||||
match command {
|
||||
SlashCommand::Help => Self::handle_help(out),
|
||||
SlashCommand::Status => self.handle_status(out),
|
||||
SlashCommand::Compact => self.handle_compact(out),
|
||||
SlashCommand::Unknown(name) => {
|
||||
writeln!(out, "Unknown slash command: /{name}")?;
|
||||
Ok(CommandResult::Continue)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_help(out: &mut impl Write) -> io::Result<CommandResult> {
|
||||
writeln!(out, "Available commands:")?;
|
||||
for handler in SLASH_COMMAND_HANDLERS {
|
||||
let name = match handler.command {
|
||||
SlashCommand::Help => "/help",
|
||||
SlashCommand::Status => "/status",
|
||||
SlashCommand::Compact => "/compact",
|
||||
SlashCommand::Unknown(_) => continue,
|
||||
};
|
||||
writeln!(out, " {name:<9} {}", handler.summary)?;
|
||||
}
|
||||
Ok(CommandResult::Continue)
|
||||
}
|
||||
|
||||
fn handle_status(&mut self, out: &mut impl Write) -> io::Result<CommandResult> {
|
||||
writeln!(
|
||||
out,
|
||||
"status: turns={} model={} permission-mode={:?} output-format={:?} config={}",
|
||||
self.state.turns,
|
||||
self.state.last_model,
|
||||
self.config.permission_mode,
|
||||
self.config.output_format,
|
||||
self.config
|
||||
.config
|
||||
.as_ref()
|
||||
.map_or_else(|| String::from("<none>"), |path| path.display().to_string())
|
||||
)?;
|
||||
Ok(CommandResult::Continue)
|
||||
}
|
||||
|
||||
fn handle_compact(&mut self, out: &mut impl Write) -> io::Result<CommandResult> {
|
||||
self.state.compacted_messages += self.state.turns;
|
||||
self.state.turns = 0;
|
||||
writeln!(
|
||||
out,
|
||||
"Compacted session history into a local summary ({} messages total compacted).",
|
||||
self.state.compacted_messages
|
||||
)?;
|
||||
Ok(CommandResult::Continue)
|
||||
}
|
||||
|
||||
fn render_response(&mut self, input: &str, out: &mut impl Write) -> io::Result<()> {
|
||||
let mut spinner = Spinner::new();
|
||||
for label in [
|
||||
"Planning response",
|
||||
"Running tool execution",
|
||||
"Rendering markdown output",
|
||||
] {
|
||||
spinner.tick(label, self.renderer.color_theme(), out)?;
|
||||
thread::sleep(Duration::from_millis(24));
|
||||
}
|
||||
spinner.finish("Streaming response", self.renderer.color_theme(), out)?;
|
||||
|
||||
let response = demo_response(input, &self.config);
|
||||
match self.config.output_format {
|
||||
OutputFormat::Text => self.renderer.stream_markdown(&response, out)?,
|
||||
OutputFormat::Json => writeln!(out, "{{\"message\":{response:?}}}")?,
|
||||
OutputFormat::Ndjson => {
|
||||
writeln!(out, "{{\"type\":\"message\",\"text\":{response:?}}}")?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn demo_response(input: &str, config: &SessionConfig) -> String {
|
||||
format!(
|
||||
"## Assistant\n\nModel: `{}` \nPermission mode: `{}`\n\nYou said:\n\n> {}\n\nThis renderer now supports **bold**, *italic*, inline `code`, and syntax-highlighted blocks:\n\n```rust\nfn main() {{\n println!(\"streaming from rusty-claude-cli\");\n}}\n```",
|
||||
config.model,
|
||||
permission_mode_label(config.permission_mode),
|
||||
input.trim()
|
||||
)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn permission_mode_label(mode: PermissionMode) -> &'static str {
|
||||
match mode {
|
||||
PermissionMode::ReadOnly => "read-only",
|
||||
PermissionMode::WorkspaceWrite => "workspace-write",
|
||||
PermissionMode::DangerFullAccess => "danger-full-access",
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::path::PathBuf;
|
||||
|
||||
use crate::args::{OutputFormat, PermissionMode};
|
||||
|
||||
use super::{CliApp, CommandResult, SessionConfig, SlashCommand};
|
||||
|
||||
#[test]
|
||||
fn parses_required_slash_commands() {
|
||||
assert_eq!(SlashCommand::parse("/help"), Some(SlashCommand::Help));
|
||||
assert_eq!(SlashCommand::parse(" /status "), Some(SlashCommand::Status));
|
||||
assert_eq!(
|
||||
SlashCommand::parse("/compact now"),
|
||||
Some(SlashCommand::Compact)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn help_status_and_compact_commands_are_wired() {
|
||||
let config = SessionConfig {
|
||||
model: "claude".into(),
|
||||
permission_mode: PermissionMode::WorkspaceWrite,
|
||||
config: Some(PathBuf::from("settings.toml")),
|
||||
output_format: OutputFormat::Text,
|
||||
};
|
||||
let mut app = CliApp::new(config);
|
||||
let mut out = Vec::new();
|
||||
|
||||
let result = app
|
||||
.handle_submission("/help", &mut out)
|
||||
.expect("help succeeds");
|
||||
assert_eq!(result, CommandResult::Continue);
|
||||
|
||||
app.handle_submission("hello", &mut out)
|
||||
.expect("submission succeeds");
|
||||
app.handle_submission("/status", &mut out)
|
||||
.expect("status succeeds");
|
||||
app.handle_submission("/compact", &mut out)
|
||||
.expect("compact succeeds");
|
||||
|
||||
let output = String::from_utf8_lossy(&out);
|
||||
assert!(output.contains("/help"));
|
||||
assert!(output.contains("/status"));
|
||||
assert!(output.contains("/compact"));
|
||||
assert!(output.contains("status: turns=1"));
|
||||
assert!(output.contains("Compacted session history"));
|
||||
}
|
||||
}
|
||||
89
rust/crates/rusty-claude-cli/src/args.rs
Normal file
89
rust/crates/rusty-claude-cli/src/args.rs
Normal file
@@ -0,0 +1,89 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use clap::{Parser, Subcommand, ValueEnum};
|
||||
|
||||
#[derive(Debug, Clone, Parser, PartialEq, Eq)]
|
||||
#[command(
|
||||
name = "rusty-claude-cli",
|
||||
version,
|
||||
about = "Rust Claude CLI prototype"
|
||||
)]
|
||||
pub struct Cli {
|
||||
#[arg(long, default_value = "claude-3-7-sonnet")]
|
||||
pub model: String,
|
||||
|
||||
#[arg(long, value_enum, default_value_t = PermissionMode::WorkspaceWrite)]
|
||||
pub permission_mode: PermissionMode,
|
||||
|
||||
#[arg(long)]
|
||||
pub config: Option<PathBuf>,
|
||||
|
||||
#[arg(long, value_enum, default_value_t = OutputFormat::Text)]
|
||||
pub output_format: OutputFormat,
|
||||
|
||||
#[command(subcommand)]
|
||||
pub command: Option<Command>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Subcommand, PartialEq, Eq)]
|
||||
pub enum Command {
|
||||
/// Read upstream TS sources and print extracted counts
|
||||
DumpManifests,
|
||||
/// Print the current bootstrap phase skeleton
|
||||
BootstrapPlan,
|
||||
/// Run a non-interactive prompt and exit
|
||||
Prompt { prompt: Vec<String> },
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, ValueEnum, PartialEq, Eq)]
|
||||
pub enum PermissionMode {
|
||||
ReadOnly,
|
||||
WorkspaceWrite,
|
||||
DangerFullAccess,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, ValueEnum, PartialEq, Eq)]
|
||||
pub enum OutputFormat {
|
||||
Text,
|
||||
Json,
|
||||
Ndjson,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use clap::Parser;
|
||||
|
||||
use super::{Cli, Command, OutputFormat, PermissionMode};
|
||||
|
||||
#[test]
|
||||
fn parses_requested_flags() {
|
||||
let cli = Cli::parse_from([
|
||||
"rusty-claude-cli",
|
||||
"--model",
|
||||
"claude-3-5-haiku",
|
||||
"--permission-mode",
|
||||
"read-only",
|
||||
"--config",
|
||||
"/tmp/config.toml",
|
||||
"--output-format",
|
||||
"ndjson",
|
||||
"prompt",
|
||||
"hello",
|
||||
"world",
|
||||
]);
|
||||
|
||||
assert_eq!(cli.model, "claude-3-5-haiku");
|
||||
assert_eq!(cli.permission_mode, PermissionMode::ReadOnly);
|
||||
assert_eq!(
|
||||
cli.config.as_deref(),
|
||||
Some(std::path::Path::new("/tmp/config.toml"))
|
||||
);
|
||||
assert_eq!(cli.output_format, OutputFormat::Ndjson);
|
||||
assert_eq!(
|
||||
cli.command,
|
||||
Some(Command::Prompt {
|
||||
prompt: vec!["hello".into(), "world".into()]
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
248
rust/crates/rusty-claude-cli/src/input.rs
Normal file
248
rust/crates/rusty-claude-cli/src/input.rs
Normal file
@@ -0,0 +1,248 @@
|
||||
use std::io::{self, Write};
|
||||
|
||||
use crossterm::cursor::MoveToColumn;
|
||||
use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyModifiers};
|
||||
use crossterm::queue;
|
||||
use crossterm::style::Print;
|
||||
use crossterm::terminal::{disable_raw_mode, enable_raw_mode, Clear, ClearType};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct InputBuffer {
|
||||
buffer: String,
|
||||
cursor: usize,
|
||||
}
|
||||
|
||||
impl InputBuffer {
|
||||
#[must_use]
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
buffer: String::new(),
|
||||
cursor: 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn insert(&mut self, ch: char) {
|
||||
self.buffer.insert(self.cursor, ch);
|
||||
self.cursor += ch.len_utf8();
|
||||
}
|
||||
|
||||
pub fn insert_newline(&mut self) {
|
||||
self.insert('\n');
|
||||
}
|
||||
|
||||
pub fn backspace(&mut self) {
|
||||
if self.cursor == 0 {
|
||||
return;
|
||||
}
|
||||
|
||||
let previous = self.buffer[..self.cursor]
|
||||
.char_indices()
|
||||
.last()
|
||||
.map_or(0, |(idx, _)| idx);
|
||||
self.buffer.drain(previous..self.cursor);
|
||||
self.cursor = previous;
|
||||
}
|
||||
|
||||
pub fn move_left(&mut self) {
|
||||
if self.cursor == 0 {
|
||||
return;
|
||||
}
|
||||
self.cursor = self.buffer[..self.cursor]
|
||||
.char_indices()
|
||||
.last()
|
||||
.map_or(0, |(idx, _)| idx);
|
||||
}
|
||||
|
||||
pub fn move_right(&mut self) {
|
||||
if self.cursor >= self.buffer.len() {
|
||||
return;
|
||||
}
|
||||
if let Some(next) = self.buffer[self.cursor..].chars().next() {
|
||||
self.cursor += next.len_utf8();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn move_home(&mut self) {
|
||||
self.cursor = 0;
|
||||
}
|
||||
|
||||
pub fn move_end(&mut self) {
|
||||
self.cursor = self.buffer.len();
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn as_str(&self) -> &str {
|
||||
&self.buffer
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[must_use]
|
||||
pub fn cursor(&self) -> usize {
|
||||
self.cursor
|
||||
}
|
||||
|
||||
pub fn clear(&mut self) {
|
||||
self.buffer.clear();
|
||||
self.cursor = 0;
|
||||
}
|
||||
}
|
||||
|
||||
pub struct LineEditor {
|
||||
prompt: String,
|
||||
}
|
||||
|
||||
impl LineEditor {
|
||||
#[must_use]
|
||||
pub fn new(prompt: impl Into<String>) -> Self {
|
||||
Self {
|
||||
prompt: prompt.into(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn read_line(&self) -> io::Result<Option<String>> {
|
||||
enable_raw_mode()?;
|
||||
let mut stdout = io::stdout();
|
||||
let mut input = InputBuffer::new();
|
||||
self.redraw(&mut stdout, &input)?;
|
||||
|
||||
loop {
|
||||
let event = event::read()?;
|
||||
if let Event::Key(key) = event {
|
||||
match Self::handle_key(key, &mut input) {
|
||||
EditorAction::Continue => self.redraw(&mut stdout, &input)?,
|
||||
EditorAction::Submit => {
|
||||
disable_raw_mode()?;
|
||||
writeln!(stdout)?;
|
||||
return Ok(Some(input.as_str().to_owned()));
|
||||
}
|
||||
EditorAction::Cancel => {
|
||||
disable_raw_mode()?;
|
||||
writeln!(stdout)?;
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_key(key: KeyEvent, input: &mut InputBuffer) -> EditorAction {
|
||||
match key {
|
||||
KeyEvent {
|
||||
code: KeyCode::Char('c'),
|
||||
modifiers,
|
||||
..
|
||||
} if modifiers.contains(KeyModifiers::CONTROL) => EditorAction::Cancel,
|
||||
KeyEvent {
|
||||
code: KeyCode::Char('j'),
|
||||
modifiers,
|
||||
..
|
||||
} if modifiers.contains(KeyModifiers::CONTROL) => {
|
||||
input.insert_newline();
|
||||
EditorAction::Continue
|
||||
}
|
||||
KeyEvent {
|
||||
code: KeyCode::Enter,
|
||||
modifiers,
|
||||
..
|
||||
} if modifiers.contains(KeyModifiers::SHIFT) => {
|
||||
input.insert_newline();
|
||||
EditorAction::Continue
|
||||
}
|
||||
KeyEvent {
|
||||
code: KeyCode::Enter,
|
||||
..
|
||||
} => EditorAction::Submit,
|
||||
KeyEvent {
|
||||
code: KeyCode::Backspace,
|
||||
..
|
||||
} => {
|
||||
input.backspace();
|
||||
EditorAction::Continue
|
||||
}
|
||||
KeyEvent {
|
||||
code: KeyCode::Left,
|
||||
..
|
||||
} => {
|
||||
input.move_left();
|
||||
EditorAction::Continue
|
||||
}
|
||||
KeyEvent {
|
||||
code: KeyCode::Right,
|
||||
..
|
||||
} => {
|
||||
input.move_right();
|
||||
EditorAction::Continue
|
||||
}
|
||||
KeyEvent {
|
||||
code: KeyCode::Home,
|
||||
..
|
||||
} => {
|
||||
input.move_home();
|
||||
EditorAction::Continue
|
||||
}
|
||||
KeyEvent {
|
||||
code: KeyCode::End, ..
|
||||
} => {
|
||||
input.move_end();
|
||||
EditorAction::Continue
|
||||
}
|
||||
KeyEvent {
|
||||
code: KeyCode::Esc, ..
|
||||
} => {
|
||||
input.clear();
|
||||
EditorAction::Cancel
|
||||
}
|
||||
KeyEvent {
|
||||
code: KeyCode::Char(ch),
|
||||
modifiers,
|
||||
..
|
||||
} if modifiers.is_empty() || modifiers == KeyModifiers::SHIFT => {
|
||||
input.insert(ch);
|
||||
EditorAction::Continue
|
||||
}
|
||||
_ => EditorAction::Continue,
|
||||
}
|
||||
}
|
||||
|
||||
fn redraw(&self, out: &mut impl Write, input: &InputBuffer) -> io::Result<()> {
|
||||
let display = input.as_str().replace('\n', "\\n\n> ");
|
||||
queue!(
|
||||
out,
|
||||
MoveToColumn(0),
|
||||
Clear(ClearType::CurrentLine),
|
||||
Print(&self.prompt),
|
||||
Print(display),
|
||||
)?;
|
||||
out.flush()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum EditorAction {
|
||||
Continue,
|
||||
Submit,
|
||||
Cancel,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::InputBuffer;
|
||||
|
||||
#[test]
|
||||
fn supports_basic_line_editing() {
|
||||
let mut input = InputBuffer::new();
|
||||
input.insert('h');
|
||||
input.insert('i');
|
||||
input.move_end();
|
||||
input.insert_newline();
|
||||
input.insert('x');
|
||||
|
||||
assert_eq!(input.as_str(), "hi\nx");
|
||||
assert_eq!(input.cursor(), 4);
|
||||
|
||||
input.move_left();
|
||||
input.backspace();
|
||||
assert_eq!(input.as_str(), "hix");
|
||||
assert_eq!(input.cursor(), 2);
|
||||
}
|
||||
}
|
||||
63
rust/crates/rusty-claude-cli/src/main.rs
Normal file
63
rust/crates/rusty-claude-cli/src/main.rs
Normal file
@@ -0,0 +1,63 @@
|
||||
mod app;
|
||||
mod args;
|
||||
mod input;
|
||||
mod render;
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use app::{CliApp, SessionConfig};
|
||||
use args::{Cli, Command};
|
||||
use clap::Parser;
|
||||
use compat_harness::{extract_manifest, UpstreamPaths};
|
||||
use runtime::BootstrapPlan;
|
||||
|
||||
fn main() {
|
||||
let cli = Cli::parse();
|
||||
|
||||
let result = match &cli.command {
|
||||
Some(Command::DumpManifests) => dump_manifests(),
|
||||
Some(Command::BootstrapPlan) => {
|
||||
print_bootstrap_plan();
|
||||
Ok(())
|
||||
}
|
||||
Some(Command::Prompt { prompt }) => {
|
||||
let joined = prompt.join(" ");
|
||||
let mut app = CliApp::new(build_session_config(&cli));
|
||||
app.run_prompt(&joined, &mut std::io::stdout())
|
||||
}
|
||||
None => {
|
||||
let mut app = CliApp::new(build_session_config(&cli));
|
||||
app.run_repl()
|
||||
}
|
||||
};
|
||||
|
||||
if let Err(error) = result {
|
||||
eprintln!("{error}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
fn build_session_config(cli: &Cli) -> SessionConfig {
|
||||
SessionConfig {
|
||||
model: cli.model.clone(),
|
||||
permission_mode: cli.permission_mode,
|
||||
config: cli.config.clone(),
|
||||
output_format: cli.output_format,
|
||||
}
|
||||
}
|
||||
|
||||
fn dump_manifests() -> std::io::Result<()> {
|
||||
let workspace_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..");
|
||||
let paths = UpstreamPaths::from_workspace_dir(&workspace_dir);
|
||||
let manifest = extract_manifest(&paths)?;
|
||||
println!("commands: {}", manifest.commands.entries().len());
|
||||
println!("tools: {}", manifest.tools.entries().len());
|
||||
println!("bootstrap phases: {}", manifest.bootstrap.phases().len());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn print_bootstrap_plan() {
|
||||
for phase in BootstrapPlan::claude_code_default().phases() {
|
||||
println!("- {phase:?}");
|
||||
}
|
||||
}
|
||||
420
rust/crates/rusty-claude-cli/src/render.rs
Normal file
420
rust/crates/rusty-claude-cli/src/render.rs
Normal file
@@ -0,0 +1,420 @@
|
||||
use std::fmt::Write as FmtWrite;
|
||||
use std::io::{self, Write};
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
|
||||
use crossterm::cursor::{MoveToColumn, RestorePosition, SavePosition};
|
||||
use crossterm::style::{Color, Print, ResetColor, SetForegroundColor, Stylize};
|
||||
use crossterm::terminal::{Clear, ClearType};
|
||||
use crossterm::{execute, queue};
|
||||
use pulldown_cmark::{CodeBlockKind, Event, Options, Parser, Tag, TagEnd};
|
||||
use syntect::easy::HighlightLines;
|
||||
use syntect::highlighting::{Theme, ThemeSet};
|
||||
use syntect::parsing::SyntaxSet;
|
||||
use syntect::util::{as_24_bit_terminal_escaped, LinesWithEndings};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct ColorTheme {
|
||||
heading: Color,
|
||||
emphasis: Color,
|
||||
strong: Color,
|
||||
inline_code: Color,
|
||||
link: Color,
|
||||
quote: Color,
|
||||
spinner_active: Color,
|
||||
spinner_done: Color,
|
||||
}
|
||||
|
||||
impl Default for ColorTheme {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
heading: Color::Cyan,
|
||||
emphasis: Color::Magenta,
|
||||
strong: Color::Yellow,
|
||||
inline_code: Color::Green,
|
||||
link: Color::Blue,
|
||||
quote: Color::DarkGrey,
|
||||
spinner_active: Color::Blue,
|
||||
spinner_done: Color::Green,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, PartialEq, Eq)]
|
||||
pub struct Spinner {
|
||||
frame_index: usize,
|
||||
}
|
||||
|
||||
impl Spinner {
|
||||
const FRAMES: [&str; 10] = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
|
||||
|
||||
#[must_use]
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
pub fn tick(
|
||||
&mut self,
|
||||
label: &str,
|
||||
theme: &ColorTheme,
|
||||
out: &mut impl Write,
|
||||
) -> io::Result<()> {
|
||||
let frame = Self::FRAMES[self.frame_index % Self::FRAMES.len()];
|
||||
self.frame_index += 1;
|
||||
queue!(
|
||||
out,
|
||||
SavePosition,
|
||||
MoveToColumn(0),
|
||||
Clear(ClearType::CurrentLine),
|
||||
SetForegroundColor(theme.spinner_active),
|
||||
Print(format!("{frame} {label}")),
|
||||
ResetColor,
|
||||
RestorePosition
|
||||
)?;
|
||||
out.flush()
|
||||
}
|
||||
|
||||
pub fn finish(
|
||||
&mut self,
|
||||
label: &str,
|
||||
theme: &ColorTheme,
|
||||
out: &mut impl Write,
|
||||
) -> io::Result<()> {
|
||||
self.frame_index = 0;
|
||||
execute!(
|
||||
out,
|
||||
MoveToColumn(0),
|
||||
Clear(ClearType::CurrentLine),
|
||||
SetForegroundColor(theme.spinner_done),
|
||||
Print(format!("✔ {label}\n")),
|
||||
ResetColor
|
||||
)?;
|
||||
out.flush()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, PartialEq, Eq)]
|
||||
struct RenderState {
|
||||
emphasis: usize,
|
||||
strong: usize,
|
||||
quote: usize,
|
||||
list: usize,
|
||||
}
|
||||
|
||||
impl RenderState {
|
||||
fn style_text(&self, text: &str, theme: &ColorTheme) -> String {
|
||||
if self.strong > 0 {
|
||||
format!("{}", text.bold().with(theme.strong))
|
||||
} else if self.emphasis > 0 {
|
||||
format!("{}", text.italic().with(theme.emphasis))
|
||||
} else if self.quote > 0 {
|
||||
format!("{}", text.with(theme.quote))
|
||||
} else {
|
||||
text.to_string()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct TerminalRenderer {
|
||||
syntax_set: SyntaxSet,
|
||||
syntax_theme: Theme,
|
||||
color_theme: ColorTheme,
|
||||
}
|
||||
|
||||
impl Default for TerminalRenderer {
|
||||
fn default() -> Self {
|
||||
let syntax_set = SyntaxSet::load_defaults_newlines();
|
||||
let syntax_theme = ThemeSet::load_defaults()
|
||||
.themes
|
||||
.remove("base16-ocean.dark")
|
||||
.unwrap_or_default();
|
||||
Self {
|
||||
syntax_set,
|
||||
syntax_theme,
|
||||
color_theme: ColorTheme::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TerminalRenderer {
|
||||
#[must_use]
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn color_theme(&self) -> &ColorTheme {
|
||||
&self.color_theme
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn render_markdown(&self, markdown: &str) -> String {
|
||||
let mut output = String::new();
|
||||
let mut state = RenderState::default();
|
||||
let mut code_language = String::new();
|
||||
let mut code_buffer = String::new();
|
||||
let mut in_code_block = false;
|
||||
|
||||
for event in Parser::new_ext(markdown, Options::all()) {
|
||||
self.render_event(
|
||||
event,
|
||||
&mut state,
|
||||
&mut output,
|
||||
&mut code_buffer,
|
||||
&mut code_language,
|
||||
&mut in_code_block,
|
||||
);
|
||||
}
|
||||
|
||||
output.trim_end().to_string()
|
||||
}
|
||||
|
||||
fn render_event(
|
||||
&self,
|
||||
event: Event<'_>,
|
||||
state: &mut RenderState,
|
||||
output: &mut String,
|
||||
code_buffer: &mut String,
|
||||
code_language: &mut String,
|
||||
in_code_block: &mut bool,
|
||||
) {
|
||||
match event {
|
||||
Event::Start(Tag::Heading { level, .. }) => self.start_heading(level as u8, output),
|
||||
Event::End(TagEnd::Heading(..) | TagEnd::Paragraph) => output.push_str("\n\n"),
|
||||
Event::Start(Tag::BlockQuote(..)) => self.start_quote(state, output),
|
||||
Event::End(TagEnd::BlockQuote(..) | TagEnd::Item)
|
||||
| Event::SoftBreak
|
||||
| Event::HardBreak => output.push('\n'),
|
||||
Event::Start(Tag::List(_)) => state.list += 1,
|
||||
Event::End(TagEnd::List(..)) => {
|
||||
state.list = state.list.saturating_sub(1);
|
||||
output.push('\n');
|
||||
}
|
||||
Event::Start(Tag::Item) => Self::start_item(state, output),
|
||||
Event::Start(Tag::CodeBlock(kind)) => {
|
||||
*in_code_block = true;
|
||||
*code_language = match kind {
|
||||
CodeBlockKind::Indented => String::from("text"),
|
||||
CodeBlockKind::Fenced(lang) => lang.to_string(),
|
||||
};
|
||||
code_buffer.clear();
|
||||
self.start_code_block(code_language, output);
|
||||
}
|
||||
Event::End(TagEnd::CodeBlock) => {
|
||||
self.finish_code_block(code_buffer, code_language, output);
|
||||
*in_code_block = false;
|
||||
code_language.clear();
|
||||
code_buffer.clear();
|
||||
}
|
||||
Event::Start(Tag::Emphasis) => state.emphasis += 1,
|
||||
Event::End(TagEnd::Emphasis) => state.emphasis = state.emphasis.saturating_sub(1),
|
||||
Event::Start(Tag::Strong) => state.strong += 1,
|
||||
Event::End(TagEnd::Strong) => state.strong = state.strong.saturating_sub(1),
|
||||
Event::Code(code) => {
|
||||
let _ = write!(
|
||||
output,
|
||||
"{}",
|
||||
format!("`{code}`").with(self.color_theme.inline_code)
|
||||
);
|
||||
}
|
||||
Event::Rule => output.push_str("---\n"),
|
||||
Event::Text(text) => {
|
||||
self.push_text(text.as_ref(), state, output, code_buffer, *in_code_block);
|
||||
}
|
||||
Event::Html(html) | Event::InlineHtml(html) => output.push_str(&html),
|
||||
Event::FootnoteReference(reference) => {
|
||||
let _ = write!(output, "[{reference}]");
|
||||
}
|
||||
Event::TaskListMarker(done) => output.push_str(if done { "[x] " } else { "[ ] " }),
|
||||
Event::InlineMath(math) | Event::DisplayMath(math) => output.push_str(&math),
|
||||
Event::Start(Tag::Link { dest_url, .. }) => {
|
||||
let _ = write!(
|
||||
output,
|
||||
"{}",
|
||||
format!("[{dest_url}]")
|
||||
.underlined()
|
||||
.with(self.color_theme.link)
|
||||
);
|
||||
}
|
||||
Event::Start(Tag::Image { dest_url, .. }) => {
|
||||
let _ = write!(
|
||||
output,
|
||||
"{}",
|
||||
format!("[image:{dest_url}]").with(self.color_theme.link)
|
||||
);
|
||||
}
|
||||
Event::Start(
|
||||
Tag::Paragraph
|
||||
| Tag::Table(..)
|
||||
| Tag::TableHead
|
||||
| Tag::TableRow
|
||||
| Tag::TableCell
|
||||
| Tag::MetadataBlock(..)
|
||||
| _,
|
||||
)
|
||||
| Event::End(
|
||||
TagEnd::Link
|
||||
| TagEnd::Image
|
||||
| TagEnd::Table
|
||||
| TagEnd::TableHead
|
||||
| TagEnd::TableRow
|
||||
| TagEnd::TableCell
|
||||
| TagEnd::MetadataBlock(..)
|
||||
| _,
|
||||
) => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn start_heading(&self, level: u8, output: &mut String) {
|
||||
output.push('\n');
|
||||
let prefix = match level {
|
||||
1 => "# ",
|
||||
2 => "## ",
|
||||
3 => "### ",
|
||||
_ => "#### ",
|
||||
};
|
||||
let _ = write!(output, "{}", prefix.bold().with(self.color_theme.heading));
|
||||
}
|
||||
|
||||
fn start_quote(&self, state: &mut RenderState, output: &mut String) {
|
||||
state.quote += 1;
|
||||
let _ = write!(output, "{}", "│ ".with(self.color_theme.quote));
|
||||
}
|
||||
|
||||
fn start_item(state: &RenderState, output: &mut String) {
|
||||
output.push_str(&" ".repeat(state.list.saturating_sub(1)));
|
||||
output.push_str("• ");
|
||||
}
|
||||
|
||||
fn start_code_block(&self, code_language: &str, output: &mut String) {
|
||||
if !code_language.is_empty() {
|
||||
let _ = writeln!(
|
||||
output,
|
||||
"{}",
|
||||
format!("╭─ {code_language}").with(self.color_theme.heading)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn finish_code_block(&self, code_buffer: &str, code_language: &str, output: &mut String) {
|
||||
output.push_str(&self.highlight_code(code_buffer, code_language));
|
||||
if !code_language.is_empty() {
|
||||
let _ = write!(output, "{}", "╰─".with(self.color_theme.heading));
|
||||
}
|
||||
output.push_str("\n\n");
|
||||
}
|
||||
|
||||
fn push_text(
|
||||
&self,
|
||||
text: &str,
|
||||
state: &RenderState,
|
||||
output: &mut String,
|
||||
code_buffer: &mut String,
|
||||
in_code_block: bool,
|
||||
) {
|
||||
if in_code_block {
|
||||
code_buffer.push_str(text);
|
||||
} else {
|
||||
output.push_str(&state.style_text(text, &self.color_theme));
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn highlight_code(&self, code: &str, language: &str) -> String {
|
||||
let syntax = self
|
||||
.syntax_set
|
||||
.find_syntax_by_token(language)
|
||||
.unwrap_or_else(|| self.syntax_set.find_syntax_plain_text());
|
||||
let mut syntax_highlighter = HighlightLines::new(syntax, &self.syntax_theme);
|
||||
let mut colored_output = String::new();
|
||||
|
||||
for line in LinesWithEndings::from(code) {
|
||||
match syntax_highlighter.highlight_line(line, &self.syntax_set) {
|
||||
Ok(ranges) => {
|
||||
colored_output.push_str(&as_24_bit_terminal_escaped(&ranges[..], false));
|
||||
}
|
||||
Err(_) => colored_output.push_str(line),
|
||||
}
|
||||
}
|
||||
|
||||
colored_output
|
||||
}
|
||||
|
||||
pub fn stream_markdown(&self, markdown: &str, out: &mut impl Write) -> io::Result<()> {
|
||||
let rendered_markdown = self.render_markdown(markdown);
|
||||
for chunk in rendered_markdown.split_inclusive(char::is_whitespace) {
|
||||
write!(out, "{chunk}")?;
|
||||
out.flush()?;
|
||||
thread::sleep(Duration::from_millis(8));
|
||||
}
|
||||
writeln!(out)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{Spinner, TerminalRenderer};
|
||||
|
||||
fn strip_ansi(input: &str) -> String {
|
||||
let mut output = String::new();
|
||||
let mut chars = input.chars().peekable();
|
||||
|
||||
while let Some(ch) = chars.next() {
|
||||
if ch == '\u{1b}' {
|
||||
if chars.peek() == Some(&'[') {
|
||||
chars.next();
|
||||
for next in chars.by_ref() {
|
||||
if next.is_ascii_alphabetic() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
output.push(ch);
|
||||
}
|
||||
}
|
||||
|
||||
output
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renders_markdown_with_styling_and_lists() {
|
||||
let terminal_renderer = TerminalRenderer::new();
|
||||
let markdown_output = terminal_renderer
|
||||
.render_markdown("# Heading\n\nThis is **bold** and *italic*.\n\n- item\n\n`code`");
|
||||
|
||||
assert!(markdown_output.contains("Heading"));
|
||||
assert!(markdown_output.contains("• item"));
|
||||
assert!(markdown_output.contains("code"));
|
||||
assert!(markdown_output.contains('\u{1b}'));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn highlights_fenced_code_blocks() {
|
||||
let terminal_renderer = TerminalRenderer::new();
|
||||
let markdown_output =
|
||||
terminal_renderer.render_markdown("```rust\nfn hi() { println!(\"hi\"); }\n```");
|
||||
let plain_text = strip_ansi(&markdown_output);
|
||||
|
||||
assert!(plain_text.contains("╭─ rust"));
|
||||
assert!(plain_text.contains("fn hi"));
|
||||
assert!(markdown_output.contains('\u{1b}'));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spinner_advances_frames() {
|
||||
let terminal_renderer = TerminalRenderer::new();
|
||||
let mut spinner = Spinner::new();
|
||||
let mut out = Vec::new();
|
||||
spinner
|
||||
.tick("Working", terminal_renderer.color_theme(), &mut out)
|
||||
.expect("tick succeeds");
|
||||
spinner
|
||||
.tick("Working", terminal_renderer.color_theme(), &mut out)
|
||||
.expect("tick succeeds");
|
||||
|
||||
let output = String::from_utf8_lossy(&out);
|
||||
assert!(output.contains("Working"));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user