refactor(cli-rs): delete unused prompt kit options

Every CLI step is merged, so drop the kit-wide dead_code allowance and
the builder options nothing calls: output on confirm, text, select,
multiselect, password and spinner; the spinner timer and messages;
password mask; multiselect max_items and cursor_at; autocomplete
placeholder and initial values. Options only the prompt demo uses keep
an item-level allowance. signals::on_shutdown had no allowance left.
This commit is contained in:
Simon Klee
2026-11-05 00:38:58 +01:00
Unverified
parent 39c15c3516
commit 586360f821
9 changed files with 48 additions and 205 deletions
-2
View File
@@ -100,7 +100,6 @@ pub struct PermissionFlags {
pub dangerously_skip_permissions: bool,
}
#[allow(dead_code, reason = "read by the handlers of later steps")]
impl PermissionFlags {
/// `--yolo` and `--dangerously-skip-permissions` are hidden spellings of `--auto`.
pub fn auto(&self) -> bool {
@@ -608,7 +607,6 @@ pub struct RunArgs {
pub server: ServerFlags,
}
#[allow(dead_code, reason = "read by the handlers of later steps")]
impl RunArgs {
/// `None` without `-w`; `Some(None)` for `-w` without a name.
pub fn worktree(&self) -> Option<Option<&str>> {
@@ -216,7 +216,11 @@ mod tests {
let text = links(
&["http://127.0.0.1:4096".into(), "http://[::1]:4096/".into()],
"abc",
600 work once and expire in 10 minutes.\n\n http://127.0.0.1:4096/auth/connect/abc\n http://[::1]:4096/auth/connect/abc\n\n"
600,
);
assert_eq!(
text,
"\n Open a link to connect. Links work once and expire in 10 minutes.\n\n http://127.0.0.1:4096/auth/connect/abc\n http://[::1]:4096/auth/connect/abc\n\n"
);
assert!(links(&[], "abc", 90).contains("expire in 2 minutes.\n\n (no server URLs)\n"));
let remote = links(&["https://x.example/base".into()], "abc", 600);
@@ -16,9 +16,6 @@ type Render<'a, T> = Box<dyn Fn(&View<'_, T>) -> String + 'a>;
pub struct Autocomplete<'a, T> {
message: String,
options: Vec<Choice<T>>,
placeholder: Option<String>,
initial_value: Option<T>,
initial_user_input: Option<String>,
max_items: Option<usize>,
validate: Option<Validate<'a, Option<T>>>,
filter: Option<Filter<'a, T>>,
@@ -33,9 +30,6 @@ pub fn autocomplete<T: Clone + PartialEq + ToString>(
Autocomplete {
message: message.into(),
options,
placeholder: None,
initial_value: None,
initial_user_input: None,
max_items: None,
validate: None,
filter: None,
@@ -61,22 +55,6 @@ pub struct View<'v, T> {
}
impl<'a, T: Clone + PartialEq + ToString> Autocomplete<'a, T> {
/// Shown instead of the search text. Clack shows it for as long as nothing is submitted.
pub fn placeholder(mut self, placeholder: impl Into<String>) -> Self {
self.placeholder = Some(placeholder.into());
self
}
pub fn initial_value(mut self, value: T) -> Self {
self.initial_value = Some(value);
self
}
pub fn initial_user_input(mut self, input: impl Into<String>) -> Self {
self.initial_user_input = Some(input.into());
self
}
pub fn max_items(mut self, items: usize) -> Self {
self.max_items = Some(items);
self
@@ -125,28 +103,20 @@ impl<'a, T: Clone + PartialEq + ToString> Autocomplete<'a, T> {
/// The focused option on Enter, `None` when nothing matched the search.
pub fn prompt(self) -> Result<Option<T>, Cancelled> {
let initial = self
.initial_value
.clone()
.or_else(|| self.options.first().map(|option| option.value.clone()));
let cursor =
initial.and_then(|value| self.options.iter().position(|option| option.value == value));
let input = self.initial_user_input.clone();
// Clack focuses and selects the first option.
let first = (!self.options.is_empty()).then_some(0);
let output = self.output;
let mut prompt = AutocompletePrompt {
filtered: (0..self.options.len()).collect(),
selected: cursor.map(|cursor| vec![Some(cursor)]).unwrap_or_default(),
focused: self
.options
.get(cursor.unwrap_or(0))
.map(|_| cursor.unwrap_or(0)),
cursor: cursor.unwrap_or(0),
selected: first.map(|first| vec![Some(first)]).unwrap_or_default(),
focused: first,
cursor: 0,
navigating: false,
last_input: String::new(),
value: None,
options: self,
};
core::run(&mut prompt, output, input.as_deref())?;
core::run(&mut prompt, output, None)?;
Ok(prompt
.value
.flatten()
@@ -306,16 +276,10 @@ impl<T: Clone + PartialEq + ToString> Prompt for AutocompletePrompt<'_, T> {
strikethrough(&dim(&base.user_input))
),
_ => {
// Clack compares `String(this.value ?? "")`, which stays empty until Enter.
let placeholder = self
.options
.placeholder
.as_deref()
.filter(|_| self.value.flatten().is_none());
let search = match placeholder {
Some(placeholder) => dim(placeholder),
None if self.navigating => dim(&base.user_input),
None => Self::user_input_with_cursor(base),
let search = if self.navigating {
dim(&base.user_input)
} else {
Self::user_input_with_cursor(base)
};
let count = self.filtered.len();
let matches = if count != self.options.options.len() {
@@ -13,7 +13,6 @@ pub struct Confirm {
active: String,
inactive: String,
initial_value: bool,
output: Output,
}
pub fn confirm(message: impl Into<String>) -> Confirm {
@@ -22,17 +21,18 @@ pub fn confirm(message: impl Into<String>) -> Confirm {
active: "Yes".to_string(),
inactive: "No".to_string(),
initial_value: true,
output: Output::Stdout,
}
}
impl Confirm {
#[allow(dead_code, reason = "only opencode-prompt-demo uses it")]
/// The label of `true` (default "Yes").
pub fn active(mut self, label: impl Into<String>) -> Self {
self.active = label.into();
self
}
#[allow(dead_code, reason = "only opencode-prompt-demo uses it")]
/// The label of `false` (default "No").
pub fn inactive(mut self, label: impl Into<String>) -> Self {
self.inactive = label.into();
@@ -45,18 +45,12 @@ impl Confirm {
self
}
pub fn output(mut self, output: Output) -> Self {
self.output = output;
self
}
pub fn prompt(self) -> Result<bool, Cancelled> {
let output = self.output;
let mut prompt = ConfirmPrompt {
value: self.initial_value,
options: self,
};
core::run(&mut prompt, output, None)?;
core::run(&mut prompt, Output::Stdout, None)?;
Ok(prompt.value)
}
}
@@ -2,7 +2,7 @@
//! P-PTY and P-CLI can compare them with `@clack/prompts`.
// The demo drives a subset of the kit; the CLI uses the rest.
#[allow(unused_imports)]
#[allow(unused_imports, dead_code)]
#[path = "mod.rs"]
mod prompt;
+5 -5
View File
@@ -18,11 +18,9 @@
//! [`is_interactive`] first, as `requireInteractive` does. Unlike Clack, which waits forever, a
//! prompt whose input ends is cancelled.
// What no command uses yet: `note`, the box-drawing symbols, the spinner's options and `message`, and builder
// options (`output`, `max_items`, `placeholder`, `default_value`, `mask`, `cursor_at`, ...) that C.8 and C.9
// may need. The builder types and `limit_options` are not re-exported until a caller names them. The wizard
// (C.15) draws Effect CLI's prompts and uses only `with_keys`, `Keys`, `Press`, and `stdout_size`.
#![allow(dead_code)]
// A few options only `opencode-prompt-demo` uses (P-CLI compares them with Clack) carry their own
// `dead_code` allowance. The wizard (C.15) draws Effect CLI's prompts and uses only `with_keys`, `Keys`,
// `Press`, and `stdout_size`.
mod autocomplete;
mod confirm;
@@ -141,11 +139,13 @@ impl Output {
}
}
#[allow(dead_code, reason = "only opencode-prompt-demo uses it")]
/// A boxed note with a title, its lines dim.
pub fn note(message: &str, title: &str) {
note_with(message, title, dim);
}
#[allow(dead_code, reason = "only opencode-prompt-demo uses it")]
/// [`note`] with each line styled by `format`.
pub fn note_with(message: &str, title: &str, format: impl Fn(&str) -> String) {
// Clack measures in UTF-16 units of the text without escape sequences.
@@ -33,6 +33,7 @@ impl<T> Choice<T> {
}
impl<T: ToString> Choice<T> {
#[allow(dead_code, reason = "only opencode-prompt-demo uses it")]
/// An option labeled with its value, as Clack labels an option without `label`.
pub fn plain(value: T) -> Choice<T> {
let label = value.to_string();
@@ -96,7 +97,6 @@ pub struct Select<T> {
options: Vec<Choice<T>>,
initial_value: Option<T>,
max_items: Option<usize>,
output: Output,
}
pub fn select<T: Clone + PartialEq>(
@@ -108,7 +108,6 @@ pub fn select<T: Clone + PartialEq>(
options,
initial_value: None,
max_items: None,
output: Output::Stdout,
}
}
@@ -119,16 +118,12 @@ impl<T: Clone + PartialEq> Select<T> {
self
}
#[allow(dead_code, reason = "only opencode-prompt-demo uses it")]
pub fn max_items(mut self, items: usize) -> Self {
self.max_items = Some(items);
self
}
pub fn output(mut self, output: Output) -> Self {
self.output = output;
self
}
/// Cancelled without showing anything when there are no options.
pub fn prompt(self) -> Result<T, Cancelled> {
if self.options.is_empty() {
@@ -143,12 +138,11 @@ impl<T: Clone + PartialEq> Select<T> {
.position(|option| option.value == *initial)
})
.unwrap_or(0);
let output = self.output;
let mut prompt = SelectPrompt {
options: self,
cursor,
};
core::run(&mut prompt, output, None)?;
core::run(&mut prompt, Output::Stdout, None)?;
Ok(prompt.options.options[prompt.cursor].value.clone())
}
}
@@ -190,7 +184,7 @@ impl<T> Prompt for SelectPrompt<T> {
&self.options.options,
self.cursor,
self.options.max_items,
self.options.output,
Output::Stdout,
|option, active| {
if active {
let hint = option
@@ -241,10 +235,7 @@ pub struct MultiSelect<T> {
message: String,
options: Vec<Choice<T>>,
initial_values: Vec<T>,
max_items: Option<usize>,
required: bool,
cursor_at: Option<T>,
output: Output,
}
pub fn multiselect<T: Clone + PartialEq>(
@@ -255,10 +246,7 @@ pub fn multiselect<T: Clone + PartialEq>(
message: message.into(),
options,
initial_values: Vec::new(),
max_items: None,
required: true,
cursor_at: None,
output: Output::Stdout,
}
}
@@ -268,47 +256,25 @@ impl<T: Clone + PartialEq> MultiSelect<T> {
self
}
pub fn max_items(mut self, items: usize) -> Self {
self.max_items = Some(items);
self
}
/// Whether at least one value must be selected (default `true`).
pub fn required(mut self, required: bool) -> Self {
self.required = required;
self
}
/// The option focused first.
pub fn cursor_at(mut self, value: T) -> Self {
self.cursor_at = Some(value);
self
}
pub fn output(mut self, output: Output) -> Self {
self.output = output;
self
}
/// The selected values in the order they were selected. Cancelled without showing anything when
/// there are no options.
pub fn prompt(self) -> Result<Vec<T>, Cancelled> {
if self.options.is_empty() {
return Err(Cancelled);
}
let cursor = self
.cursor_at
.as_ref()
.and_then(|at| self.options.iter().position(|option| option.value == *at))
.unwrap_or(0);
let value = self.initial_values.clone();
let output = self.output;
let mut prompt = MultiSelectPrompt {
options: self,
cursor,
cursor: 0,
value,
};
core::run(&mut prompt, output, None)?;
core::run(&mut prompt, Output::Stdout, None)?;
Ok(prompt.value)
}
}
@@ -341,8 +307,8 @@ impl<T: Clone + PartialEq> MultiSelectPrompt<T> {
limit_options(
&self.options.options,
self.cursor,
self.options.max_items,
self.options.output,
None,
Output::Stdout,
|option, active| {
let selected = self.value.contains(&option.value);
let state = match (active, selected) {
@@ -4,7 +4,7 @@ use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{self, RecvTimeoutError, Sender};
use std::sync::{Arc, Mutex, MutexGuard};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};
use std::time::Duration;
use super::Output;
use super::core::{ERASE_DOWN, HIDE, SHOW, move_cursor};
@@ -13,13 +13,12 @@ use super::style::{
};
use super::term::{Keys, Raw};
/// Printed when Ctrl+C ends the process, or when the spinner is dropped while spinning.
const CANCELED: &str = "Canceled";
/// A line with an animated frame while work runs. While it spins, Ctrl+C or Escape prints the cancel
/// message and exits the process with code 0, as Clack's spinner does.
pub struct Spinner {
timer: bool,
cancel_message: String,
error_message: String,
output: Output,
shared: Arc<Mutex<Shared>>,
threads: Option<Threads>,
}
@@ -27,7 +26,6 @@ pub struct Spinner {
struct Shared {
message: String,
previous: Option<String>,
origin: Instant,
raw: Option<Raw>,
}
@@ -40,14 +38,9 @@ struct Threads {
pub fn spinner() -> Spinner {
Spinner {
timer: false,
cancel_message: "Canceled".to_string(),
error_message: "Something went wrong".to_string(),
output: Output::Stdout,
shared: Arc::new(Mutex::new(Shared {
message: String::new(),
previous: None,
origin: Instant::now(),
raw: None,
})),
threads: None,
@@ -55,45 +48,21 @@ pub fn spinner() -> Spinner {
}
impl Spinner {
/// Shows the elapsed time (`[1m 5s]`) instead of growing dots (`indicator: "timer"`).
pub fn timer(mut self) -> Self {
self.timer = true;
self
}
/// Printed when Ctrl+C ends the process, or when the spinner is dropped while spinning.
pub fn cancel_message(mut self, message: impl Into<String>) -> Self {
self.cancel_message = message.into();
self
}
pub fn error_message(mut self, message: impl Into<String>) -> Self {
self.error_message = message.into();
self
}
pub fn output(mut self, output: Output) -> Self {
self.output = output;
self
}
pub fn start(&mut self, message: &str) {
if self.threads.is_some() {
self.stop("");
}
let output = self.output;
let output = Output::Stdout;
{
let mut shared = lock(&self.shared);
shared.raw = Some(Raw::enable());
shared.message = trim_dots(message);
shared.origin = Instant::now();
shared.previous = None;
}
output.write(HIDE);
output.write(&format!("{}\n", gray(S_BAR())));
let (frames, receive) = mpsc::channel();
let shared = self.shared.clone();
let timer = self.timer;
let frame_thread = std::thread::spawn(move || {
let ci = std::env::var("CI").as_deref() == Ok("true");
let frames: [&str; 4] = if unicode() {
@@ -114,8 +83,6 @@ impl Spinner {
let frame = magenta(frames[index]);
let line = if ci {
format!("{frame} {}...", shared.message)
} else if timer {
format!("{frame} {} {}", shared.message, elapsed(shared.origin))
} else {
format!(
"{frame} {}{}",
@@ -135,7 +102,6 @@ impl Spinner {
let input_thread = {
let stop = stop_input.clone();
let shared = self.shared.clone();
let message = self.cancel_message.clone();
std::thread::spawn(move || {
let mut keys = Keys::stoppable(stop);
while let Some(press) = keys.next() {
@@ -150,11 +116,7 @@ impl Spinner {
output,
std::env::var("CI").as_deref() == Ok("true"),
);
output.write(&format!(
"{} {message}{}\n",
green(S_STEP_SUBMIT()),
timer_suffix(timer, &shared)
));
output.write(&format!("{} {CANCELED}\n", green(S_STEP_SUBMIT())));
output.write(SHOW);
shared.raw.take();
std::process::exit(0);
@@ -170,6 +132,7 @@ impl Spinner {
});
}
#[allow(dead_code, reason = "only opencode-prompt-demo uses it")]
/// Changes the message while it spins.
pub fn message(&self, message: &str) {
lock(&self.shared).message = trim_dots(message);
@@ -190,20 +153,16 @@ impl Spinner {
threads.stop_input.store(true, Ordering::Relaxed);
let _ = threads.input_thread.join();
let mut shared = lock(&self.shared);
clear_previous(
&shared,
self.output,
std::env::var("CI").as_deref() == Ok("true"),
);
let output = Output::Stdout;
clear_previous(&shared, output, std::env::var("CI").as_deref() == Ok("true"));
let step = match code {
0 => green(S_STEP_SUBMIT()),
1 => red(S_STEP_CANCEL()),
_ => red(S_STEP_ERROR()),
};
shared.message = message.to_string();
let suffix = timer_suffix(self.timer, &shared);
self.output.write(&format!("{step} {message}{suffix}\n"));
self.output.write(SHOW);
output.write(&format!("{step} {message}\n"));
output.write(SHOW);
shared.raw.take();
}
}
@@ -212,8 +171,7 @@ impl Drop for Spinner {
/// A spinner dropped while spinning stops as Clack's does when the process exits with code 1.
fn drop(&mut self) {
if self.threads.is_some() {
let message = self.cancel_message.clone();
self.stop_with(&message, 1);
self.stop_with(CANCELED, 1);
}
}
}
@@ -240,21 +198,3 @@ fn clear_previous(shared: &Shared, output: Output, ci: bool) {
fn trim_dots(message: &str) -> String {
message.trim_end_matches('.').to_string()
}
fn elapsed(origin: Instant) -> String {
let seconds = origin.elapsed().as_secs();
let minutes = seconds / 60;
if minutes > 0 {
format!("[{minutes}m {}s]", seconds % 60)
} else {
format!("[{seconds}s]")
}
}
fn timer_suffix(timer: bool, shared: &Shared) -> String {
if timer {
format!(" {}", elapsed(shared.origin))
} else {
String::new()
}
}
+4 -27
View File
@@ -15,7 +15,6 @@ pub struct Text<'a> {
default_value: Option<String>,
initial_value: Option<String>,
validate: Option<Validate<'a, str>>,
output: Output,
}
pub fn text(message: impl Into<String>) -> Text<'static> {
@@ -25,7 +24,6 @@ pub fn text(message: impl Into<String>) -> Text<'static> {
default_value: None,
initial_value: None,
validate: None,
output: Output::Stdout,
}
}
@@ -36,6 +34,7 @@ impl<'a> Text<'a> {
self
}
#[allow(dead_code, reason = "only opencode-prompt-demo uses it")]
/// The answer when the input is empty on submit.
pub fn default_value(mut self, value: impl Into<String>) -> Self {
self.default_value = Some(value.into());
@@ -60,19 +59,13 @@ impl<'a> Text<'a> {
}
}
pub fn output(mut self, output: Output) -> Self {
self.output = output;
self
}
pub fn prompt(self) -> Result<String, Cancelled> {
let initial = self.initial_value.clone();
let output = self.output;
let mut prompt = TextPrompt {
options: self,
value: None,
};
core::run(&mut prompt, output, initial.as_deref())?;
core::run(&mut prompt, Output::Stdout, initial.as_deref())?;
Ok(prompt.value.unwrap_or_default())
}
}
@@ -171,26 +164,17 @@ pub fn with_cursor(base: &Base) -> String {
/// Hidden input shown as one mask character per character.
pub struct Password<'a> {
message: String,
mask: Option<String>,
validate: Option<Validate<'a, str>>,
output: Output,
}
pub fn password(message: impl Into<String>) -> Password<'static> {
Password {
message: message.into(),
mask: None,
validate: None,
output: Output::Stdout,
}
}
impl<'a> Password<'a> {
pub fn mask(mut self, mask: impl Into<String>) -> Self {
self.mask = Some(mask.into());
self
}
pub fn validate<'b>(self, validate: impl Fn(&str) -> Option<String> + 'b) -> Password<'b>
where
'a: 'b,
@@ -201,18 +185,12 @@ impl<'a> Password<'a> {
}
}
pub fn output(mut self, output: Output) -> Self {
self.output = output;
self
}
pub fn prompt(self) -> Result<String, Cancelled> {
let output = self.output;
let mut prompt = PasswordPrompt {
options: self,
value: String::new(),
};
core::run(&mut prompt, output, None)?;
core::run(&mut prompt, Output::Stdout, None)?;
Ok(prompt.value)
}
}
@@ -225,7 +203,7 @@ struct PasswordPrompt<'a> {
impl PasswordPrompt<'_> {
/// `userInput.replaceAll(/./g, mask)`: line terminators stay as they are.
fn masked(&self, base: &Base) -> String {
let mask = self.options.mask.as_deref().unwrap_or(S_PASSWORD_MASK());
let mask = S_PASSWORD_MASK();
base.user_input
.chars()
.map(|char| {
@@ -246,7 +224,6 @@ impl PasswordPrompt<'_> {
if base.cursor >= base.user_input.chars().count() {
return format!("{masked}{}", inverse(&hidden("_")));
}
// Clack slices the masked text at the input's cursor, also for a mask longer than one character.
let chars: Vec<char> = masked.chars().collect();
let cursor = base.cursor;
let before: String = chars[..cursor].iter().collect();