mirror of
https://github.com/instructkr/claw-code.git
synced 2026-04-03 23:54:49 +08:00
Compare commits
1 Commits
rcc/render
...
rcc/update
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cdf24b87b4 |
3
rust/Cargo.lock
generated
3
rust/Cargo.lock
generated
@@ -1091,8 +1091,11 @@ dependencies = [
|
|||||||
"compat-harness",
|
"compat-harness",
|
||||||
"crossterm",
|
"crossterm",
|
||||||
"pulldown-cmark",
|
"pulldown-cmark",
|
||||||
|
"reqwest",
|
||||||
"runtime",
|
"runtime",
|
||||||
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
|
"sha2",
|
||||||
"syntect",
|
"syntect",
|
||||||
"tokio",
|
"tokio",
|
||||||
"tools",
|
"tools",
|
||||||
|
|||||||
@@ -84,6 +84,15 @@ cargo run -p rusty-claude-cli -- logout
|
|||||||
|
|
||||||
This removes only the stored OAuth credentials and preserves unrelated JSON fields in `credentials.json`.
|
This removes only the stored OAuth credentials and preserves unrelated JSON fields in `credentials.json`.
|
||||||
|
|
||||||
|
### Self-update
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd rust
|
||||||
|
cargo run -p rusty-claude-cli -- self-update
|
||||||
|
```
|
||||||
|
|
||||||
|
The command checks the latest GitHub release for `instructkr/clawd-code`, compares it to the current binary version, downloads the matching binary asset plus checksum manifest, verifies SHA-256, replaces the current executable, and prints the release changelog. If no published release or matching asset exists, it exits safely with an explanatory message.
|
||||||
|
|
||||||
## Usage examples
|
## Usage examples
|
||||||
|
|
||||||
### 1) Prompt mode
|
### 1) Prompt mode
|
||||||
@@ -162,6 +171,7 @@ cargo run -p rusty-claude-cli -- --resume session.json /memory /config
|
|||||||
- `dump-manifests` — print extracted upstream manifest counts
|
- `dump-manifests` — print extracted upstream manifest counts
|
||||||
- `bootstrap-plan` — print the current bootstrap skeleton
|
- `bootstrap-plan` — print the current bootstrap skeleton
|
||||||
- `system-prompt [--cwd PATH] [--date YYYY-MM-DD]` — render the synthesized system prompt
|
- `system-prompt [--cwd PATH] [--date YYYY-MM-DD]` — render the synthesized system prompt
|
||||||
|
- `self-update` — update the installed binary from the latest GitHub release when a matching asset is available
|
||||||
- `--help` / `-h` — show CLI help
|
- `--help` / `-h` — show CLI help
|
||||||
- `--version` / `-V` — print the CLI version and build info locally (no API call)
|
- `--version` / `-V` — print the CLI version and build info locally (no API call)
|
||||||
- `--output-format text|json` — choose non-interactive prompt output rendering
|
- `--output-format text|json` — choose non-interactive prompt output rendering
|
||||||
|
|||||||
@@ -11,8 +11,11 @@ commands = { path = "../commands" }
|
|||||||
compat-harness = { path = "../compat-harness" }
|
compat-harness = { path = "../compat-harness" }
|
||||||
crossterm = "0.28"
|
crossterm = "0.28"
|
||||||
pulldown-cmark = "0.13"
|
pulldown-cmark = "0.13"
|
||||||
|
reqwest = { version = "0.12", default-features = false, features = ["blocking", "json", "rustls-tls"] }
|
||||||
runtime = { path = "../runtime" }
|
runtime = { path = "../runtime" }
|
||||||
|
serde = { version = "1", features = ["derive"] }
|
||||||
serde_json = "1"
|
serde_json = "1"
|
||||||
|
sha2 = "0.10"
|
||||||
syntect = "5"
|
syntect = "5"
|
||||||
tokio = { version = "1", features = ["rt-multi-thread", "time"] }
|
tokio = { version = "1", features = ["rt-multi-thread", "time"] }
|
||||||
tools = { path = "../tools" }
|
tools = { path = "../tools" }
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ mod render;
|
|||||||
|
|
||||||
use std::collections::{BTreeMap, BTreeSet};
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
use std::env;
|
use std::env;
|
||||||
|
use std::fmt::Write as _;
|
||||||
use std::fs;
|
use std::fs;
|
||||||
use std::io::{self, Read, Write};
|
use std::io::{self, Read, Write};
|
||||||
use std::net::TcpListener;
|
use std::net::TcpListener;
|
||||||
@@ -21,6 +22,7 @@ use commands::{
|
|||||||
};
|
};
|
||||||
use compat_harness::{extract_manifest, UpstreamPaths};
|
use compat_harness::{extract_manifest, UpstreamPaths};
|
||||||
use render::{Spinner, TerminalRenderer};
|
use render::{Spinner, TerminalRenderer};
|
||||||
|
use reqwest::blocking::Client;
|
||||||
use runtime::{
|
use runtime::{
|
||||||
clear_oauth_credentials, generate_pkce_pair, generate_state, load_system_prompt,
|
clear_oauth_credentials, generate_pkce_pair, generate_state, load_system_prompt,
|
||||||
parse_oauth_callback_request_target, save_oauth_credentials, ApiClient, ApiRequest,
|
parse_oauth_callback_request_target, save_oauth_credentials, ApiClient, ApiRequest,
|
||||||
@@ -29,7 +31,9 @@ use runtime::{
|
|||||||
OAuthTokenExchangeRequest, PermissionMode, PermissionPolicy, ProjectContext, RuntimeError,
|
OAuthTokenExchangeRequest, PermissionMode, PermissionPolicy, ProjectContext, RuntimeError,
|
||||||
Session, TokenUsage, ToolError, ToolExecutor, UsageTracker,
|
Session, TokenUsage, ToolError, ToolExecutor, UsageTracker,
|
||||||
};
|
};
|
||||||
|
use serde::Deserialize;
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
use tools::{execute_tool, mvp_tool_specs, ToolSpec};
|
use tools::{execute_tool, mvp_tool_specs, ToolSpec};
|
||||||
|
|
||||||
const DEFAULT_MODEL: &str = "claude-sonnet-4-20250514";
|
const DEFAULT_MODEL: &str = "claude-sonnet-4-20250514";
|
||||||
@@ -39,6 +43,18 @@ const DEFAULT_OAUTH_CALLBACK_PORT: u16 = 4545;
|
|||||||
const VERSION: &str = env!("CARGO_PKG_VERSION");
|
const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||||
const BUILD_TARGET: Option<&str> = option_env!("TARGET");
|
const BUILD_TARGET: Option<&str> = option_env!("TARGET");
|
||||||
const GIT_SHA: Option<&str> = option_env!("GIT_SHA");
|
const GIT_SHA: Option<&str> = option_env!("GIT_SHA");
|
||||||
|
const SELF_UPDATE_REPOSITORY: &str = "instructkr/clawd-code";
|
||||||
|
const SELF_UPDATE_LATEST_RELEASE_URL: &str =
|
||||||
|
"https://api.github.com/repos/instructkr/clawd-code/releases/latest";
|
||||||
|
const SELF_UPDATE_USER_AGENT: &str = "rusty-claude-cli-self-update";
|
||||||
|
const CHECKSUM_ASSET_CANDIDATES: &[&str] = &[
|
||||||
|
"SHA256SUMS",
|
||||||
|
"SHA256SUMS.txt",
|
||||||
|
"sha256sums",
|
||||||
|
"sha256sums.txt",
|
||||||
|
"checksums.txt",
|
||||||
|
"checksums.sha256",
|
||||||
|
];
|
||||||
|
|
||||||
type AllowedToolSet = BTreeSet<String>;
|
type AllowedToolSet = BTreeSet<String>;
|
||||||
|
|
||||||
@@ -60,6 +76,7 @@ fn run() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
CliAction::BootstrapPlan => print_bootstrap_plan(),
|
CliAction::BootstrapPlan => print_bootstrap_plan(),
|
||||||
CliAction::PrintSystemPrompt { cwd, date } => print_system_prompt(cwd, date),
|
CliAction::PrintSystemPrompt { cwd, date } => print_system_prompt(cwd, date),
|
||||||
CliAction::Version => print_version(),
|
CliAction::Version => print_version(),
|
||||||
|
CliAction::SelfUpdate => run_self_update()?,
|
||||||
CliAction::ResumeSession {
|
CliAction::ResumeSession {
|
||||||
session_path,
|
session_path,
|
||||||
commands,
|
commands,
|
||||||
@@ -93,6 +110,7 @@ enum CliAction {
|
|||||||
date: String,
|
date: String,
|
||||||
},
|
},
|
||||||
Version,
|
Version,
|
||||||
|
SelfUpdate,
|
||||||
ResumeSession {
|
ResumeSession {
|
||||||
session_path: PathBuf,
|
session_path: PathBuf,
|
||||||
commands: Vec<String>,
|
commands: Vec<String>,
|
||||||
@@ -228,6 +246,7 @@ fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
|||||||
"dump-manifests" => Ok(CliAction::DumpManifests),
|
"dump-manifests" => Ok(CliAction::DumpManifests),
|
||||||
"bootstrap-plan" => Ok(CliAction::BootstrapPlan),
|
"bootstrap-plan" => Ok(CliAction::BootstrapPlan),
|
||||||
"system-prompt" => parse_system_prompt_args(&rest[1..]),
|
"system-prompt" => parse_system_prompt_args(&rest[1..]),
|
||||||
|
"self-update" => Ok(CliAction::SelfUpdate),
|
||||||
"login" => Ok(CliAction::Login),
|
"login" => Ok(CliAction::Login),
|
||||||
"logout" => Ok(CliAction::Logout),
|
"logout" => Ok(CliAction::Logout),
|
||||||
"prompt" => {
|
"prompt" => {
|
||||||
@@ -534,6 +553,375 @@ fn print_version() {
|
|||||||
println!("{}", render_version_report());
|
println!("{}", render_version_report());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
|
||||||
|
struct GitHubRelease {
|
||||||
|
tag_name: String,
|
||||||
|
#[serde(default)]
|
||||||
|
body: String,
|
||||||
|
#[serde(default)]
|
||||||
|
assets: Vec<GitHubReleaseAsset>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
|
||||||
|
struct GitHubReleaseAsset {
|
||||||
|
name: String,
|
||||||
|
browser_download_url: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
struct SelectedReleaseAssets {
|
||||||
|
binary: GitHubReleaseAsset,
|
||||||
|
checksum: GitHubReleaseAsset,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run_self_update() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
let Some(release) = fetch_latest_release()? else {
|
||||||
|
println!(
|
||||||
|
"{}",
|
||||||
|
render_update_report(
|
||||||
|
"No published release available",
|
||||||
|
Some(VERSION),
|
||||||
|
None,
|
||||||
|
Some("GitHub latest release endpoint returned no published release for instructkr/clawd-code."),
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
);
|
||||||
|
return Ok(());
|
||||||
|
};
|
||||||
|
|
||||||
|
let latest_version = normalize_version_tag(&release.tag_name);
|
||||||
|
if !is_newer_version(VERSION, &latest_version) {
|
||||||
|
println!(
|
||||||
|
"{}",
|
||||||
|
render_update_report(
|
||||||
|
"Already up to date",
|
||||||
|
Some(VERSION),
|
||||||
|
Some(&latest_version),
|
||||||
|
Some("Current binary already matches the latest published release."),
|
||||||
|
Some(&release.body),
|
||||||
|
)
|
||||||
|
);
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
let selected = match select_release_assets(&release) {
|
||||||
|
Ok(selected) => selected,
|
||||||
|
Err(message) => {
|
||||||
|
println!(
|
||||||
|
"{}",
|
||||||
|
render_update_report(
|
||||||
|
"Release found, but no installable asset matched this platform",
|
||||||
|
Some(VERSION),
|
||||||
|
Some(&latest_version),
|
||||||
|
Some(&message),
|
||||||
|
Some(&release.body),
|
||||||
|
)
|
||||||
|
);
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let client = build_self_update_client()?;
|
||||||
|
let binary_bytes = download_bytes(&client, &selected.binary.browser_download_url)?;
|
||||||
|
let checksum_manifest = download_text(&client, &selected.checksum.browser_download_url)?;
|
||||||
|
let expected_checksum = parse_checksum_for_asset(&checksum_manifest, &selected.binary.name)
|
||||||
|
.ok_or_else(|| {
|
||||||
|
format!(
|
||||||
|
"checksum manifest did not contain an entry for {}",
|
||||||
|
selected.binary.name
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
let actual_checksum = sha256_hex(&binary_bytes);
|
||||||
|
if actual_checksum != expected_checksum {
|
||||||
|
return Err(format!(
|
||||||
|
"downloaded asset checksum mismatch for {} (expected {}, got {})",
|
||||||
|
selected.binary.name, expected_checksum, actual_checksum
|
||||||
|
)
|
||||||
|
.into());
|
||||||
|
}
|
||||||
|
|
||||||
|
replace_current_executable(&binary_bytes)?;
|
||||||
|
|
||||||
|
println!(
|
||||||
|
"{}",
|
||||||
|
render_update_report(
|
||||||
|
"Update installed",
|
||||||
|
Some(VERSION),
|
||||||
|
Some(&latest_version),
|
||||||
|
Some(&format!(
|
||||||
|
"Installed {} from GitHub release assets for {}.",
|
||||||
|
selected.binary.name,
|
||||||
|
current_target()
|
||||||
|
)),
|
||||||
|
Some(&release.body),
|
||||||
|
)
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fetch_latest_release() -> Result<Option<GitHubRelease>, Box<dyn std::error::Error>> {
|
||||||
|
let client = build_self_update_client()?;
|
||||||
|
let response = client
|
||||||
|
.get(SELF_UPDATE_LATEST_RELEASE_URL)
|
||||||
|
.header(reqwest::header::ACCEPT, "application/vnd.github+json")
|
||||||
|
.send()?;
|
||||||
|
|
||||||
|
if response.status() == reqwest::StatusCode::NOT_FOUND {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
|
||||||
|
let response = response.error_for_status()?;
|
||||||
|
Ok(Some(response.json()?))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn build_self_update_client() -> Result<Client, reqwest::Error> {
|
||||||
|
Client::builder().user_agent(SELF_UPDATE_USER_AGENT).build()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn download_bytes(client: &Client, url: &str) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
|
||||||
|
let response = client.get(url).send()?.error_for_status()?;
|
||||||
|
Ok(response.bytes()?.to_vec())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn download_text(client: &Client, url: &str) -> Result<String, Box<dyn std::error::Error>> {
|
||||||
|
let response = client.get(url).send()?.error_for_status()?;
|
||||||
|
Ok(response.text()?)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn normalize_version_tag(version: &str) -> String {
|
||||||
|
version.trim().trim_start_matches('v').to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_newer_version(current: &str, latest: &str) -> bool {
|
||||||
|
compare_versions(latest, current).is_gt()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn current_target() -> String {
|
||||||
|
BUILD_TARGET.map_or_else(default_target_triple, str::to_string)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn release_asset_candidates() -> Vec<String> {
|
||||||
|
let mut candidates = target_name_candidates()
|
||||||
|
.into_iter()
|
||||||
|
.flat_map(|target| {
|
||||||
|
let mut names = vec![format!("rusty-claude-cli-{target}")];
|
||||||
|
if env::consts::OS == "windows" {
|
||||||
|
names.push(format!("rusty-claude-cli-{target}.exe"));
|
||||||
|
}
|
||||||
|
names
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
if env::consts::OS == "windows" {
|
||||||
|
candidates.push("rusty-claude-cli.exe".to_string());
|
||||||
|
}
|
||||||
|
candidates.push("rusty-claude-cli".to_string());
|
||||||
|
candidates.sort();
|
||||||
|
candidates.dedup();
|
||||||
|
candidates
|
||||||
|
}
|
||||||
|
|
||||||
|
fn select_release_assets(release: &GitHubRelease) -> Result<SelectedReleaseAssets, String> {
|
||||||
|
let binary = release_asset_candidates()
|
||||||
|
.into_iter()
|
||||||
|
.find_map(|candidate| {
|
||||||
|
release
|
||||||
|
.assets
|
||||||
|
.iter()
|
||||||
|
.find(|asset| asset.name == candidate)
|
||||||
|
.cloned()
|
||||||
|
})
|
||||||
|
.ok_or_else(|| {
|
||||||
|
format!(
|
||||||
|
"no binary asset matched target {} (expected one of: {})",
|
||||||
|
current_target(),
|
||||||
|
release_asset_candidates().join(", ")
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let checksum = CHECKSUM_ASSET_CANDIDATES
|
||||||
|
.iter()
|
||||||
|
.find_map(|candidate| {
|
||||||
|
release
|
||||||
|
.assets
|
||||||
|
.iter()
|
||||||
|
.find(|asset| asset.name == *candidate)
|
||||||
|
.cloned()
|
||||||
|
})
|
||||||
|
.ok_or_else(|| {
|
||||||
|
format!(
|
||||||
|
"release did not include a checksum manifest (expected one of: {})",
|
||||||
|
CHECKSUM_ASSET_CANDIDATES.join(", ")
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
|
Ok(SelectedReleaseAssets { binary, checksum })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_checksum_for_asset(manifest: &str, asset_name: &str) -> Option<String> {
|
||||||
|
manifest.lines().find_map(|line| {
|
||||||
|
let trimmed = line.trim();
|
||||||
|
if trimmed.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
if let Some((left, right)) = trimmed.split_once(" = ") {
|
||||||
|
return left
|
||||||
|
.strip_prefix("SHA256 (")
|
||||||
|
.and_then(|value| value.strip_suffix(')'))
|
||||||
|
.filter(|file| *file == asset_name)
|
||||||
|
.map(|_| right.to_ascii_lowercase());
|
||||||
|
}
|
||||||
|
let mut parts = trimmed.split_whitespace();
|
||||||
|
let checksum = parts.next()?;
|
||||||
|
let file = parts
|
||||||
|
.next_back()
|
||||||
|
.or_else(|| parts.next())?
|
||||||
|
.trim_start_matches('*');
|
||||||
|
(file == asset_name).then(|| checksum.to_ascii_lowercase())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sha256_hex(bytes: &[u8]) -> String {
|
||||||
|
format!("{:x}", Sha256::digest(bytes))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn replace_current_executable(binary_bytes: &[u8]) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
let current = env::current_exe()?;
|
||||||
|
replace_executable_at(¤t, binary_bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn replace_executable_at(
|
||||||
|
current: &Path,
|
||||||
|
binary_bytes: &[u8],
|
||||||
|
) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
let temp_path = current.with_extension("download");
|
||||||
|
let backup_path = current.with_extension("bak");
|
||||||
|
|
||||||
|
if backup_path.exists() {
|
||||||
|
fs::remove_file(&backup_path)?;
|
||||||
|
}
|
||||||
|
fs::write(&temp_path, binary_bytes)?;
|
||||||
|
copy_executable_permissions(current, &temp_path)?;
|
||||||
|
|
||||||
|
fs::rename(current, &backup_path)?;
|
||||||
|
if let Err(error) = fs::rename(&temp_path, current) {
|
||||||
|
let _ = fs::rename(&backup_path, current);
|
||||||
|
let _ = fs::remove_file(&temp_path);
|
||||||
|
return Err(format!("failed to replace current executable: {error}").into());
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Err(error) = fs::remove_file(&backup_path) {
|
||||||
|
eprintln!(
|
||||||
|
"warning: failed to remove self-update backup {}: {error}",
|
||||||
|
backup_path.display()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
fn copy_executable_permissions(
|
||||||
|
source: &Path,
|
||||||
|
destination: &Path,
|
||||||
|
) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
|
||||||
|
let mode = fs::metadata(source)?.permissions().mode();
|
||||||
|
fs::set_permissions(destination, fs::Permissions::from_mode(mode))?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(unix))]
|
||||||
|
fn copy_executable_permissions(
|
||||||
|
_source: &Path,
|
||||||
|
_destination: &Path,
|
||||||
|
) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render_update_report(
|
||||||
|
result: &str,
|
||||||
|
current_version: Option<&str>,
|
||||||
|
latest_version: Option<&str>,
|
||||||
|
detail: Option<&str>,
|
||||||
|
changelog: Option<&str>,
|
||||||
|
) -> String {
|
||||||
|
let mut report = String::from(
|
||||||
|
"Self-update
|
||||||
|
",
|
||||||
|
);
|
||||||
|
let _ = writeln!(report, " Repository {SELF_UPDATE_REPOSITORY}");
|
||||||
|
let _ = writeln!(report, " Result {result}");
|
||||||
|
if let Some(current_version) = current_version {
|
||||||
|
let _ = writeln!(report, " Current version {current_version}");
|
||||||
|
}
|
||||||
|
if let Some(latest_version) = latest_version {
|
||||||
|
let _ = writeln!(report, " Latest version {latest_version}");
|
||||||
|
}
|
||||||
|
if let Some(detail) = detail {
|
||||||
|
let _ = writeln!(report, " Detail {detail}");
|
||||||
|
}
|
||||||
|
let trimmed = changelog.map(str::trim).filter(|value| !value.is_empty());
|
||||||
|
if let Some(changelog) = trimmed {
|
||||||
|
report.push_str(
|
||||||
|
"
|
||||||
|
Changelog
|
||||||
|
",
|
||||||
|
);
|
||||||
|
report.push_str(changelog);
|
||||||
|
}
|
||||||
|
report.trim_end().to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn compare_versions(left: &str, right: &str) -> std::cmp::Ordering {
|
||||||
|
let left = normalize_version_tag(left);
|
||||||
|
let right = normalize_version_tag(right);
|
||||||
|
let left_parts = version_components(&left);
|
||||||
|
let right_parts = version_components(&right);
|
||||||
|
let max_len = left_parts.len().max(right_parts.len());
|
||||||
|
for index in 0..max_len {
|
||||||
|
let left_part = *left_parts.get(index).unwrap_or(&0);
|
||||||
|
let right_part = *right_parts.get(index).unwrap_or(&0);
|
||||||
|
match left_part.cmp(&right_part) {
|
||||||
|
std::cmp::Ordering::Equal => {}
|
||||||
|
ordering => return ordering,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
std::cmp::Ordering::Equal
|
||||||
|
}
|
||||||
|
|
||||||
|
fn version_components(version: &str) -> Vec<u64> {
|
||||||
|
version
|
||||||
|
.split(['.', '-'])
|
||||||
|
.map(|part| {
|
||||||
|
part.chars()
|
||||||
|
.take_while(char::is_ascii_digit)
|
||||||
|
.collect::<String>()
|
||||||
|
})
|
||||||
|
.filter(|part| !part.is_empty())
|
||||||
|
.filter_map(|part| part.parse::<u64>().ok())
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_target_triple() -> String {
|
||||||
|
let os = match env::consts::OS {
|
||||||
|
"linux" => "unknown-linux-gnu",
|
||||||
|
"macos" => "apple-darwin",
|
||||||
|
"windows" => "pc-windows-msvc",
|
||||||
|
other => other,
|
||||||
|
};
|
||||||
|
format!("{}-{os}", env::consts::ARCH)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn target_name_candidates() -> Vec<String> {
|
||||||
|
let mut candidates = Vec::new();
|
||||||
|
if let Some(target) = BUILD_TARGET {
|
||||||
|
candidates.push(target.to_string());
|
||||||
|
}
|
||||||
|
candidates.push(default_target_triple());
|
||||||
|
candidates.push(format!("{}-{}", env::consts::ARCH, env::consts::OS));
|
||||||
|
candidates
|
||||||
|
}
|
||||||
|
|
||||||
fn resume_session(session_path: &Path, commands: &[String]) {
|
fn resume_session(session_path: &Path, commands: &[String]) {
|
||||||
let session = match Session::load_from_path(session_path) {
|
let session = match Session::load_from_path(session_path) {
|
||||||
Ok(session) => session,
|
Ok(session) => session,
|
||||||
@@ -2358,6 +2746,8 @@ fn print_help() {
|
|||||||
println!(" rusty-claude-cli system-prompt [--cwd PATH] [--date YYYY-MM-DD]");
|
println!(" rusty-claude-cli system-prompt [--cwd PATH] [--date YYYY-MM-DD]");
|
||||||
println!(" rusty-claude-cli login");
|
println!(" rusty-claude-cli login");
|
||||||
println!(" rusty-claude-cli logout");
|
println!(" rusty-claude-cli logout");
|
||||||
|
println!(" rusty-claude-cli self-update");
|
||||||
|
println!(" Update the installed binary from the latest GitHub release");
|
||||||
println!();
|
println!();
|
||||||
println!("Flags:");
|
println!("Flags:");
|
||||||
println!(" --model MODEL Override the active model");
|
println!(" --model MODEL Override the active model");
|
||||||
@@ -2384,6 +2774,7 @@ fn print_help() {
|
|||||||
println!(" rusty-claude-cli --allowedTools read,glob \"summarize Cargo.toml\"");
|
println!(" rusty-claude-cli --allowedTools read,glob \"summarize Cargo.toml\"");
|
||||||
println!(" rusty-claude-cli --resume session.json /status /diff /export notes.txt");
|
println!(" rusty-claude-cli --resume session.json /status /diff /export notes.txt");
|
||||||
println!(" rusty-claude-cli login");
|
println!(" rusty-claude-cli login");
|
||||||
|
println!(" rusty-claude-cli self-update");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
@@ -2392,10 +2783,11 @@ mod tests {
|
|||||||
filter_tool_specs, format_compact_report, format_cost_report, format_init_report,
|
filter_tool_specs, format_compact_report, format_cost_report, format_init_report,
|
||||||
format_model_report, format_model_switch_report, format_permissions_report,
|
format_model_report, format_model_switch_report, format_permissions_report,
|
||||||
format_permissions_switch_report, format_resume_report, format_status_report,
|
format_permissions_switch_report, format_resume_report, format_status_report,
|
||||||
format_tool_call_start, format_tool_result, normalize_permission_mode, parse_args,
|
format_tool_call_start, format_tool_result, is_newer_version, normalize_permission_mode,
|
||||||
parse_git_status_metadata, render_config_report, render_init_claude_md,
|
normalize_version_tag, parse_args, parse_checksum_for_asset, parse_git_status_metadata,
|
||||||
render_memory_report, render_repl_help, resume_supported_slash_commands, status_context,
|
render_config_report, render_init_claude_md, render_memory_report, render_repl_help,
|
||||||
CliAction, CliOutputFormat, SlashCommand, StatusUsage, DEFAULT_MODEL,
|
render_update_report, resume_supported_slash_commands, select_release_assets,
|
||||||
|
status_context, CliAction, CliOutputFormat, SlashCommand, StatusUsage, DEFAULT_MODEL,
|
||||||
};
|
};
|
||||||
use runtime::{ContentBlock, ConversationMessage, MessageRole, PermissionMode};
|
use runtime::{ContentBlock, ConversationMessage, MessageRole, PermissionMode};
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
@@ -2464,6 +2856,64 @@ mod tests {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_self_update_subcommand() {
|
||||||
|
assert_eq!(
|
||||||
|
parse_args(&["self-update".to_string()]).expect("self-update should parse"),
|
||||||
|
CliAction::SelfUpdate
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn normalize_version_tag_trims_v_prefix() {
|
||||||
|
assert_eq!(normalize_version_tag("v0.1.0"), "0.1.0");
|
||||||
|
assert_eq!(normalize_version_tag("0.1.0"), "0.1.0");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn detects_when_latest_version_differs() {
|
||||||
|
assert!(!is_newer_version("0.1.0", "v0.1.0"));
|
||||||
|
assert!(is_newer_version("0.1.0", "v0.2.0"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_checksum_manifest_for_named_asset() {
|
||||||
|
let manifest = "abc123 *rusty-claude-cli\ndef456 other-file\n";
|
||||||
|
assert_eq!(
|
||||||
|
parse_checksum_for_asset(manifest, "rusty-claude-cli"),
|
||||||
|
Some("abc123".to_string())
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn select_release_assets_requires_checksum_file() {
|
||||||
|
let release = super::GitHubRelease {
|
||||||
|
tag_name: "v0.2.0".to_string(),
|
||||||
|
body: String::new(),
|
||||||
|
assets: vec![super::GitHubReleaseAsset {
|
||||||
|
name: "rusty-claude-cli".to_string(),
|
||||||
|
browser_download_url: "https://example.invalid/rusty-claude-cli".to_string(),
|
||||||
|
}],
|
||||||
|
};
|
||||||
|
|
||||||
|
let error = select_release_assets(&release).expect_err("missing checksum should error");
|
||||||
|
assert!(error.contains("checksum manifest"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn update_report_includes_changelog_when_present() {
|
||||||
|
let report = render_update_report(
|
||||||
|
"Already up to date",
|
||||||
|
Some("0.1.0"),
|
||||||
|
Some("0.1.0"),
|
||||||
|
Some("No action taken."),
|
||||||
|
Some("- Added self-update"),
|
||||||
|
);
|
||||||
|
assert!(report.contains("Self-update"));
|
||||||
|
assert!(report.contains("Changelog"));
|
||||||
|
assert!(report.contains("- Added self-update"));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn parses_permission_mode_flag() {
|
fn parses_permission_mode_flag() {
|
||||||
let args = vec!["--permission-mode=read-only".to_string()];
|
let args = vec!["--permission-mode=read-only".to_string()];
|
||||||
|
|||||||
@@ -21,7 +21,6 @@ pub struct ColorTheme {
|
|||||||
inline_code: Color,
|
inline_code: Color,
|
||||||
link: Color,
|
link: Color,
|
||||||
quote: Color,
|
quote: Color,
|
||||||
table_border: Color,
|
|
||||||
spinner_active: Color,
|
spinner_active: Color,
|
||||||
spinner_done: Color,
|
spinner_done: Color,
|
||||||
spinner_failed: Color,
|
spinner_failed: Color,
|
||||||
@@ -36,7 +35,6 @@ impl Default for ColorTheme {
|
|||||||
inline_code: Color::Green,
|
inline_code: Color::Green,
|
||||||
link: Color::Blue,
|
link: Color::Blue,
|
||||||
quote: Color::DarkGrey,
|
quote: Color::DarkGrey,
|
||||||
table_border: Color::DarkCyan,
|
|
||||||
spinner_active: Color::Blue,
|
spinner_active: Color::Blue,
|
||||||
spinner_done: Color::Green,
|
spinner_done: Color::Green,
|
||||||
spinner_failed: Color::Red,
|
spinner_failed: Color::Red,
|
||||||
@@ -115,70 +113,24 @@ impl Spinner {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
||||||
enum ListKind {
|
|
||||||
Unordered,
|
|
||||||
Ordered { next_index: u64 },
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Default, Clone, PartialEq, Eq)]
|
|
||||||
struct TableState {
|
|
||||||
headers: Vec<String>,
|
|
||||||
rows: Vec<Vec<String>>,
|
|
||||||
current_row: Vec<String>,
|
|
||||||
current_cell: String,
|
|
||||||
in_head: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl TableState {
|
|
||||||
fn push_cell(&mut self) {
|
|
||||||
let cell = self.current_cell.trim().to_string();
|
|
||||||
self.current_row.push(cell);
|
|
||||||
self.current_cell.clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
fn finish_row(&mut self) {
|
|
||||||
if self.current_row.is_empty() {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let row = std::mem::take(&mut self.current_row);
|
|
||||||
if self.in_head {
|
|
||||||
self.headers = row;
|
|
||||||
} else {
|
|
||||||
self.rows.push(row);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Default, Clone, PartialEq, Eq)]
|
#[derive(Debug, Default, Clone, PartialEq, Eq)]
|
||||||
struct RenderState {
|
struct RenderState {
|
||||||
emphasis: usize,
|
emphasis: usize,
|
||||||
strong: usize,
|
strong: usize,
|
||||||
quote: usize,
|
quote: usize,
|
||||||
list_stack: Vec<ListKind>,
|
list: usize,
|
||||||
table: Option<TableState>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RenderState {
|
impl RenderState {
|
||||||
fn style_text(&self, text: &str, theme: &ColorTheme) -> String {
|
fn style_text(&self, text: &str, theme: &ColorTheme) -> String {
|
||||||
let mut styled = text.to_string();
|
|
||||||
if self.strong > 0 {
|
if self.strong > 0 {
|
||||||
styled = format!("{}", styled.bold().with(theme.strong));
|
format!("{}", text.bold().with(theme.strong))
|
||||||
}
|
} else if self.emphasis > 0 {
|
||||||
if self.emphasis > 0 {
|
format!("{}", text.italic().with(theme.emphasis))
|
||||||
styled = format!("{}", styled.italic().with(theme.emphasis));
|
} else if self.quote > 0 {
|
||||||
}
|
format!("{}", text.with(theme.quote))
|
||||||
if self.quote > 0 {
|
|
||||||
styled = format!("{}", styled.with(theme.quote));
|
|
||||||
}
|
|
||||||
styled
|
|
||||||
}
|
|
||||||
|
|
||||||
fn capture_target_mut<'a>(&'a mut self, output: &'a mut String) -> &'a mut String {
|
|
||||||
if let Some(table) = self.table.as_mut() {
|
|
||||||
&mut table.current_cell
|
|
||||||
} else {
|
} else {
|
||||||
output
|
text.to_string()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -238,7 +190,6 @@ impl TerminalRenderer {
|
|||||||
output.trim_end().to_string()
|
output.trim_end().to_string()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(clippy::too_many_lines)]
|
|
||||||
fn render_event(
|
fn render_event(
|
||||||
&self,
|
&self,
|
||||||
event: Event<'_>,
|
event: Event<'_>,
|
||||||
@@ -252,22 +203,12 @@ impl TerminalRenderer {
|
|||||||
Event::Start(Tag::Heading { level, .. }) => self.start_heading(level as u8, output),
|
Event::Start(Tag::Heading { level, .. }) => self.start_heading(level as u8, output),
|
||||||
Event::End(TagEnd::Heading(..) | TagEnd::Paragraph) => output.push_str("\n\n"),
|
Event::End(TagEnd::Heading(..) | TagEnd::Paragraph) => output.push_str("\n\n"),
|
||||||
Event::Start(Tag::BlockQuote(..)) => self.start_quote(state, output),
|
Event::Start(Tag::BlockQuote(..)) => self.start_quote(state, output),
|
||||||
Event::End(TagEnd::BlockQuote(..)) => {
|
Event::End(TagEnd::BlockQuote(..) | TagEnd::Item)
|
||||||
state.quote = state.quote.saturating_sub(1);
|
| Event::SoftBreak
|
||||||
output.push('\n');
|
| Event::HardBreak => output.push('\n'),
|
||||||
}
|
Event::Start(Tag::List(_)) => state.list += 1,
|
||||||
Event::End(TagEnd::Item) | Event::SoftBreak | Event::HardBreak => {
|
|
||||||
state.capture_target_mut(output).push('\n');
|
|
||||||
}
|
|
||||||
Event::Start(Tag::List(first_item)) => {
|
|
||||||
let kind = match first_item {
|
|
||||||
Some(index) => ListKind::Ordered { next_index: index },
|
|
||||||
None => ListKind::Unordered,
|
|
||||||
};
|
|
||||||
state.list_stack.push(kind);
|
|
||||||
}
|
|
||||||
Event::End(TagEnd::List(..)) => {
|
Event::End(TagEnd::List(..)) => {
|
||||||
state.list_stack.pop();
|
state.list = state.list.saturating_sub(1);
|
||||||
output.push('\n');
|
output.push('\n');
|
||||||
}
|
}
|
||||||
Event::Start(Tag::Item) => Self::start_item(state, output),
|
Event::Start(Tag::Item) => Self::start_item(state, output),
|
||||||
@@ -291,85 +232,57 @@ impl TerminalRenderer {
|
|||||||
Event::Start(Tag::Strong) => state.strong += 1,
|
Event::Start(Tag::Strong) => state.strong += 1,
|
||||||
Event::End(TagEnd::Strong) => state.strong = state.strong.saturating_sub(1),
|
Event::End(TagEnd::Strong) => state.strong = state.strong.saturating_sub(1),
|
||||||
Event::Code(code) => {
|
Event::Code(code) => {
|
||||||
let rendered =
|
let _ = write!(
|
||||||
format!("{}", format!("`{code}`").with(self.color_theme.inline_code));
|
output,
|
||||||
state.capture_target_mut(output).push_str(&rendered);
|
"{}",
|
||||||
|
format!("`{code}`").with(self.color_theme.inline_code)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
Event::Rule => output.push_str("---\n"),
|
Event::Rule => output.push_str("---\n"),
|
||||||
Event::Text(text) => {
|
Event::Text(text) => {
|
||||||
self.push_text(text.as_ref(), state, output, code_buffer, *in_code_block);
|
self.push_text(text.as_ref(), state, output, code_buffer, *in_code_block);
|
||||||
}
|
}
|
||||||
Event::Html(html) | Event::InlineHtml(html) => {
|
Event::Html(html) | Event::InlineHtml(html) => output.push_str(&html),
|
||||||
state.capture_target_mut(output).push_str(&html);
|
|
||||||
}
|
|
||||||
Event::FootnoteReference(reference) => {
|
Event::FootnoteReference(reference) => {
|
||||||
let _ = write!(state.capture_target_mut(output), "[{reference}]");
|
let _ = write!(output, "[{reference}]");
|
||||||
}
|
|
||||||
Event::TaskListMarker(done) => {
|
|
||||||
state
|
|
||||||
.capture_target_mut(output)
|
|
||||||
.push_str(if done { "[x] " } else { "[ ] " });
|
|
||||||
}
|
|
||||||
Event::InlineMath(math) | Event::DisplayMath(math) => {
|
|
||||||
state.capture_target_mut(output).push_str(&math);
|
|
||||||
}
|
}
|
||||||
|
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, .. }) => {
|
Event::Start(Tag::Link { dest_url, .. }) => {
|
||||||
let rendered = format!(
|
let _ = write!(
|
||||||
|
output,
|
||||||
"{}",
|
"{}",
|
||||||
format!("[{dest_url}]")
|
format!("[{dest_url}]")
|
||||||
.underlined()
|
.underlined()
|
||||||
.with(self.color_theme.link)
|
.with(self.color_theme.link)
|
||||||
);
|
);
|
||||||
state.capture_target_mut(output).push_str(&rendered);
|
|
||||||
}
|
}
|
||||||
Event::Start(Tag::Image { dest_url, .. }) => {
|
Event::Start(Tag::Image { dest_url, .. }) => {
|
||||||
let rendered = format!(
|
let _ = write!(
|
||||||
|
output,
|
||||||
"{}",
|
"{}",
|
||||||
format!("[image:{dest_url}]").with(self.color_theme.link)
|
format!("[image:{dest_url}]").with(self.color_theme.link)
|
||||||
);
|
);
|
||||||
state.capture_target_mut(output).push_str(&rendered);
|
|
||||||
}
|
}
|
||||||
Event::Start(Tag::Table(..)) => state.table = Some(TableState::default()),
|
Event::Start(
|
||||||
Event::End(TagEnd::Table) => {
|
Tag::Paragraph
|
||||||
if let Some(table) = state.table.take() {
|
| Tag::Table(..)
|
||||||
output.push_str(&self.render_table(&table));
|
| Tag::TableHead
|
||||||
output.push_str("\n\n");
|
| Tag::TableRow
|
||||||
}
|
| Tag::TableCell
|
||||||
}
|
| Tag::MetadataBlock(..)
|
||||||
Event::Start(Tag::TableHead) => {
|
| _,
|
||||||
if let Some(table) = state.table.as_mut() {
|
)
|
||||||
table.in_head = true;
|
| Event::End(
|
||||||
}
|
TagEnd::Link
|
||||||
}
|
| TagEnd::Image
|
||||||
Event::End(TagEnd::TableHead) => {
|
| TagEnd::Table
|
||||||
if let Some(table) = state.table.as_mut() {
|
| TagEnd::TableHead
|
||||||
table.finish_row();
|
| TagEnd::TableRow
|
||||||
table.in_head = false;
|
| TagEnd::TableCell
|
||||||
}
|
| TagEnd::MetadataBlock(..)
|
||||||
}
|
| _,
|
||||||
Event::Start(Tag::TableRow) => {
|
) => {}
|
||||||
if let Some(table) = state.table.as_mut() {
|
|
||||||
table.current_row.clear();
|
|
||||||
table.current_cell.clear();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Event::End(TagEnd::TableRow) => {
|
|
||||||
if let Some(table) = state.table.as_mut() {
|
|
||||||
table.finish_row();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Event::Start(Tag::TableCell) => {
|
|
||||||
if let Some(table) = state.table.as_mut() {
|
|
||||||
table.current_cell.clear();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Event::End(TagEnd::TableCell) => {
|
|
||||||
if let Some(table) = state.table.as_mut() {
|
|
||||||
table.push_cell();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Event::Start(Tag::Paragraph | Tag::MetadataBlock(..) | _)
|
|
||||||
| Event::End(TagEnd::Link | TagEnd::Image | TagEnd::MetadataBlock(..) | _) => {}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -389,19 +302,9 @@ impl TerminalRenderer {
|
|||||||
let _ = write!(output, "{}", "│ ".with(self.color_theme.quote));
|
let _ = write!(output, "{}", "│ ".with(self.color_theme.quote));
|
||||||
}
|
}
|
||||||
|
|
||||||
fn start_item(state: &mut RenderState, output: &mut String) {
|
fn start_item(state: &RenderState, output: &mut String) {
|
||||||
let depth = state.list_stack.len().saturating_sub(1);
|
output.push_str(&" ".repeat(state.list.saturating_sub(1)));
|
||||||
output.push_str(&" ".repeat(depth));
|
output.push_str("• ");
|
||||||
|
|
||||||
let marker = match state.list_stack.last_mut() {
|
|
||||||
Some(ListKind::Ordered { next_index }) => {
|
|
||||||
let value = *next_index;
|
|
||||||
*next_index += 1;
|
|
||||||
format!("{value}. ")
|
|
||||||
}
|
|
||||||
_ => "• ".to_string(),
|
|
||||||
};
|
|
||||||
output.push_str(&marker);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn start_code_block(&self, code_language: &str, output: &mut String) {
|
fn start_code_block(&self, code_language: &str, output: &mut String) {
|
||||||
@@ -425,7 +328,7 @@ impl TerminalRenderer {
|
|||||||
fn push_text(
|
fn push_text(
|
||||||
&self,
|
&self,
|
||||||
text: &str,
|
text: &str,
|
||||||
state: &mut RenderState,
|
state: &RenderState,
|
||||||
output: &mut String,
|
output: &mut String,
|
||||||
code_buffer: &mut String,
|
code_buffer: &mut String,
|
||||||
in_code_block: bool,
|
in_code_block: bool,
|
||||||
@@ -433,82 +336,10 @@ impl TerminalRenderer {
|
|||||||
if in_code_block {
|
if in_code_block {
|
||||||
code_buffer.push_str(text);
|
code_buffer.push_str(text);
|
||||||
} else {
|
} else {
|
||||||
let rendered = state.style_text(text, &self.color_theme);
|
output.push_str(&state.style_text(text, &self.color_theme));
|
||||||
state.capture_target_mut(output).push_str(&rendered);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn render_table(&self, table: &TableState) -> String {
|
|
||||||
let mut rows = Vec::new();
|
|
||||||
if !table.headers.is_empty() {
|
|
||||||
rows.push(table.headers.clone());
|
|
||||||
}
|
|
||||||
rows.extend(table.rows.iter().cloned());
|
|
||||||
|
|
||||||
if rows.is_empty() {
|
|
||||||
return String::new();
|
|
||||||
}
|
|
||||||
|
|
||||||
let column_count = rows.iter().map(Vec::len).max().unwrap_or(0);
|
|
||||||
let widths = (0..column_count)
|
|
||||||
.map(|column| {
|
|
||||||
rows.iter()
|
|
||||||
.filter_map(|row| row.get(column))
|
|
||||||
.map(|cell| visible_width(cell))
|
|
||||||
.max()
|
|
||||||
.unwrap_or(0)
|
|
||||||
})
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
|
|
||||||
let border = format!("{}", "│".with(self.color_theme.table_border));
|
|
||||||
let separator = widths
|
|
||||||
.iter()
|
|
||||||
.map(|width| "─".repeat(*width + 2))
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.join(&format!("{}", "┼".with(self.color_theme.table_border)));
|
|
||||||
let separator = format!("{border}{separator}{border}");
|
|
||||||
|
|
||||||
let mut output = String::new();
|
|
||||||
if !table.headers.is_empty() {
|
|
||||||
output.push_str(&self.render_table_row(&table.headers, &widths, true));
|
|
||||||
output.push('\n');
|
|
||||||
output.push_str(&separator);
|
|
||||||
if !table.rows.is_empty() {
|
|
||||||
output.push('\n');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for (index, row) in table.rows.iter().enumerate() {
|
|
||||||
output.push_str(&self.render_table_row(row, &widths, false));
|
|
||||||
if index + 1 < table.rows.len() {
|
|
||||||
output.push('\n');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
output
|
|
||||||
}
|
|
||||||
|
|
||||||
fn render_table_row(&self, row: &[String], widths: &[usize], is_header: bool) -> String {
|
|
||||||
let border = format!("{}", "│".with(self.color_theme.table_border));
|
|
||||||
let mut line = String::new();
|
|
||||||
line.push_str(&border);
|
|
||||||
|
|
||||||
for (index, width) in widths.iter().enumerate() {
|
|
||||||
let cell = row.get(index).map_or("", String::as_str);
|
|
||||||
line.push(' ');
|
|
||||||
if is_header {
|
|
||||||
let _ = write!(line, "{}", cell.bold().with(self.color_theme.heading));
|
|
||||||
} else {
|
|
||||||
line.push_str(cell);
|
|
||||||
}
|
|
||||||
let padding = width.saturating_sub(visible_width(cell));
|
|
||||||
line.push_str(&" ".repeat(padding + 1));
|
|
||||||
line.push_str(&border);
|
|
||||||
}
|
|
||||||
|
|
||||||
line
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn highlight_code(&self, code: &str, language: &str) -> String {
|
pub fn highlight_code(&self, code: &str, language: &str) -> String {
|
||||||
let syntax = self
|
let syntax = self
|
||||||
@@ -541,9 +372,9 @@ impl TerminalRenderer {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn visible_width(input: &str) -> usize {
|
#[cfg(test)]
|
||||||
strip_ansi(input).chars().count()
|
mod tests {
|
||||||
}
|
use super::{Spinner, TerminalRenderer};
|
||||||
|
|
||||||
fn strip_ansi(input: &str) -> String {
|
fn strip_ansi(input: &str) -> String {
|
||||||
let mut output = String::new();
|
let mut output = String::new();
|
||||||
@@ -567,10 +398,6 @@ fn strip_ansi(input: &str) -> String {
|
|||||||
output
|
output
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::{strip_ansi, Spinner, TerminalRenderer};
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn renders_markdown_with_styling_and_lists() {
|
fn renders_markdown_with_styling_and_lists() {
|
||||||
let terminal_renderer = TerminalRenderer::new();
|
let terminal_renderer = TerminalRenderer::new();
|
||||||
@@ -595,34 +422,6 @@ mod tests {
|
|||||||
assert!(markdown_output.contains('\u{1b}'));
|
assert!(markdown_output.contains('\u{1b}'));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn renders_ordered_and_nested_lists() {
|
|
||||||
let terminal_renderer = TerminalRenderer::new();
|
|
||||||
let markdown_output =
|
|
||||||
terminal_renderer.render_markdown("1. first\n2. second\n - nested\n - child");
|
|
||||||
let plain_text = strip_ansi(&markdown_output);
|
|
||||||
|
|
||||||
assert!(plain_text.contains("1. first"));
|
|
||||||
assert!(plain_text.contains("2. second"));
|
|
||||||
assert!(plain_text.contains(" • nested"));
|
|
||||||
assert!(plain_text.contains(" • child"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn renders_tables_with_alignment() {
|
|
||||||
let terminal_renderer = TerminalRenderer::new();
|
|
||||||
let markdown_output = terminal_renderer
|
|
||||||
.render_markdown("| Name | Value |\n| ---- | ----- |\n| alpha | 1 |\n| beta | 22 |");
|
|
||||||
let plain_text = strip_ansi(&markdown_output);
|
|
||||||
let lines = plain_text.lines().collect::<Vec<_>>();
|
|
||||||
|
|
||||||
assert_eq!(lines[0], "│ Name │ Value │");
|
|
||||||
assert_eq!(lines[1], "│───────┼───────│");
|
|
||||||
assert_eq!(lines[2], "│ alpha │ 1 │");
|
|
||||||
assert_eq!(lines[3], "│ beta │ 22 │");
|
|
||||||
assert!(markdown_output.contains('\u{1b}'));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn spinner_advances_frames() {
|
fn spinner_advances_frames() {
|
||||||
let terminal_renderer = TerminalRenderer::new();
|
let terminal_renderer = TerminalRenderer::new();
|
||||||
|
|||||||
Reference in New Issue
Block a user