1use crate::command_line::{Cursor, Read, Skipped, read_word};
2use crate::{DirectRender, ParseError, ParseErrorKind, Parsed, help};
3use alux_cli::{
4 ArgumentInfo, CliArgumentError, CliCommandsAlg, CliContextAlg, CliDecodeSources, CliFailureAlg, CliNestAlg,
5 CliOperationAlg, CliOutcome, CliOutcomeOf, CliProgramAlg, CliSources, CommandDescription, Conventions, SourceInfo,
6 USAGE_STATUS,
7};
8use alux_ext::{ApplyAlg, OperationAlg};
9use core::{fmt::Display, future::Future, marker::PhantomData, pin::Pin};
10use std::{
11 ffi::{OsStr, OsString},
12 io::Write,
13 path::Path,
14 sync::Arc,
15 task::{Context, Poll, Wake, Waker},
16 thread::{self, Thread},
17};
18
19#[derive(Clone, Debug, PartialEq, Eq)]
21pub struct Exit {
22 pub status: u8,
24 pub stdout: String,
26 pub stderr: String,
28}
29
30impl Exit {
31 fn out(status: u8, stdout: String) -> Self {
32 Self { status, stdout, stderr: String::new() }
33 }
34
35 fn err(status: u8, stderr: String) -> Self {
36 Self { status, stdout: String::new(), stderr }
37 }
38
39 pub fn exit(self) -> ! {
41 print!("{}", self.stdout);
42 eprint!("{}", self.stderr);
43 let _ = std::io::stdout().flush();
44 std::process::exit(i32::from(self.status))
45 }
46}
47
48pub type Running = Pin<Box<dyn Future<Output = Exit> + Send>>;
50
51pub type Ready<Handle> = Box<dyn FnOnce(Handle) -> Running + Send>;
53
54type Decode<Handle, Decoder> = Arc<
60 dyn Fn(&Decoder, &[ArgumentInfo], &[ArgumentInfo], &str) -> Result<Ready<Handle>, CliArgumentError<String>>
61 + Send
62 + Sync,
63>;
64
65pub struct Entry<Handle, Decoder = Parsed> {
68 description: CommandDescription,
69 decode: Decode<Handle, Decoder>,
70}
71
72impl<Handle, Decoder> Clone for Entry<Handle, Decoder> {
73 fn clone(&self) -> Self {
74 Self { description: self.description.clone(), decode: Arc::clone(&self.decode) }
75 }
76}
77
78impl<Handle, Decoder> Entry<Handle, Decoder> {
79 pub fn description(&self) -> &CommandDescription {
81 &self.description
82 }
83
84 pub fn decode(&self, decoder: &Decoder, prefix: &str) -> Result<Ready<Handle>, CliArgumentError<String>> {
91 (self.decode)(decoder, &self.description.context, &self.description.arguments, prefix)
92 }
93}
94
95pub struct DirectCompiler<Handle, Decoder = Parsed> {
101 selected: Option<&'static str>,
103 marker: PhantomData<fn() -> (Handle, Decoder)>,
104}
105
106impl<Handle, Decoder> DirectCompiler<Handle, Decoder> {
107 pub fn selecting(name: &'static str) -> Self {
110 Self { selected: Some(name), marker: PhantomData }
111 }
112
113 fn compiles(&self, name: &str) -> bool {
115 self.selected.is_none_or(|selected| selected == name)
116 }
117}
118
119impl<Handle, Decoder> Default for DirectCompiler<Handle, Decoder> {
120 fn default() -> Self {
121 Self { selected: None, marker: PhantomData }
122 }
123}
124
125pub struct CliDirect<Handle> {
131 handle: Handle,
132 name: Option<String>,
133 prefix: FailurePrefix,
134 unknown: Option<Unknown>,
135 usage: u8,
136 selected: Option<&'static str>,
137 version: Option<&'static str>,
138}
139
140type Unknown = (u8, Arc<dyn Fn(&str) -> String + Send + Sync>);
142
143pub const DUPLICATE_STATUS: u8 = 70;
146
147#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
149pub enum FailurePrefix {
150 #[default]
152 Error,
153 Invocation,
155 Command,
157}
158
159impl<Handle> CliDirect<Handle> {
160 pub fn new(handle: Handle) -> Self {
162 Self {
163 handle,
164 name: None,
165 prefix: FailurePrefix::Error,
166 unknown: None,
167 usage: USAGE_STATUS.get(),
168 selected: None,
169 version: None,
170 }
171 }
172
173 #[must_use]
176 pub fn named(self, name: impl Into<String>) -> Self {
177 Self { name: Some(name.into()), ..self }
178 }
179
180 #[must_use]
182 pub fn failures_after(self, prefix: FailurePrefix) -> Self {
183 Self { prefix, ..self }
184 }
185
186 #[must_use]
189 pub fn usage_status(self, status: u8) -> Self {
190 Self { usage: status, ..self }
191 }
192
193 #[must_use]
197 pub fn selecting(self, name: Option<&'static str>) -> Self {
198 Self { selected: name, ..self }
199 }
200
201 #[must_use]
204 pub fn version(self, version: &'static str) -> Self {
205 Self { version: Some(version), ..self }
206 }
207
208 #[must_use]
211 pub fn unknown_command(self, status: u8, message: impl Fn(&str) -> String + Send + Sync + 'static) -> Self {
212 Self { unknown: Some((status, Arc::new(message))), ..self }
213 }
214
215 fn start<Program, Words>(&self, program: Program, words: Words) -> Result<Ready<Handle>, Exit>
217 where
218 Program: CliProgramAlg<DirectCompiler<Handle>, Commands = Vec<Entry<Handle>>>,
219 Words: IntoIterator,
220 Words::Item: Into<OsString>,
221 {
222 let mut words = words.into_iter().map(Into::into);
223 let first = words.next().unwrap_or_default();
224 let invoked = Path::new(&first).file_name().map(|name| name.to_string_lossy().into_owned()).unwrap_or_default();
225 let words = words.collect::<Vec<_>>();
226 let compiler = DirectCompiler { selected: self.selected, marker: PhantomData };
227 let entries = program.compile_cli(&compiler);
228 let name = self.name.clone().unwrap_or_else(|| invoked.clone());
229 let invocation = Invocation {
230 name: &name,
231 invoked: &invoked,
232 prefix: self.prefix,
233 unknown: self.unknown.as_ref(),
234 usage: self.usage,
235 version: self.version,
236 };
237 select(&invocation, &entries, &words)
238 }
239
240 pub fn run_once<Program, Words>(self, program: Program, words: Words) -> Running
244 where
245 Program: CliProgramAlg<DirectCompiler<Handle>, Commands = Vec<Entry<Handle>>>,
246 Words: IntoIterator,
247 Words::Item: Into<OsString>,
248 {
249 match self.start(program, words) {
250 Ok(ready) => ready(self.handle),
251 Err(exit) => Box::pin(async move { exit }),
252 }
253 }
254
255 pub fn run_once_blocking<Program, Words>(self, program: Program, words: Words) -> Exit
257 where
258 Program: CliProgramAlg<DirectCompiler<Handle>, Commands = Vec<Entry<Handle>>>,
259 Words: IntoIterator,
260 Words::Item: Into<OsString>,
261 {
262 block_on(self.run_once(program, words))
263 }
264
265 pub fn run_main<Program>(self, program: Program) -> !
268 where
269 Program: CliProgramAlg<DirectCompiler<Handle>, Commands = Vec<Entry<Handle>>>,
270 {
271 self.run_once_blocking(program, std::env::args_os()).exit()
272 }
273}
274
275impl<Handle> CliDirect<Handle>
276where
277 Handle: Clone,
278{
279 pub fn run<Program, Words>(
281 &self,
282 program: Program,
283 words: Words,
284 ) -> impl Future<Output = Exit> + use<Handle, Program, Words>
285 where
286 Program: CliProgramAlg<DirectCompiler<Handle>, Commands = Vec<Entry<Handle>>>,
287 Words: IntoIterator,
288 Words::Item: Into<OsString>,
289 {
290 let selected = self.start(program, words).map(|ready| ready(self.handle.clone()));
291
292 async move {
293 match selected {
294 Ok(running) => running.await,
295 Err(exit) => exit,
296 }
297 }
298 }
299
300 pub fn run_blocking<Program, Words>(&self, program: Program, words: Words) -> Exit
302 where
303 Program: CliProgramAlg<DirectCompiler<Handle>, Commands = Vec<Entry<Handle>>>,
304 Words: IntoIterator,
305 Words::Item: Into<OsString>,
306 {
307 block_on(self.run(program, words))
308 }
309}
310
311struct Invocation<'a> {
315 name: &'a str,
316 invoked: &'a str,
317 prefix: FailurePrefix,
318 unknown: Option<&'a Unknown>,
319 usage: u8,
320 version: Option<&'static str>,
321}
322
323impl Invocation<'_> {
324 fn prefix(&self, command: Option<&CommandDescription>) -> String {
326 match self.prefix {
327 FailurePrefix::Error => "error".to_owned(),
328 FailurePrefix::Invocation => self.invoked.to_owned(),
329 FailurePrefix::Command => command
330 .and_then(|command| command.path.last())
331 .map_or_else(|| self.invoked.to_owned(), |name| (*name).to_owned()),
332 }
333 }
334}
335
336fn is(word: &OsStr, text: &str) -> bool {
338 word.to_str() == Some(text)
339}
340
341fn select<Handle>(
343 invocation: &Invocation<'_>,
344 entries: &[Entry<Handle>],
345 words: &[OsString],
346) -> Result<Ready<Handle>, Exit> {
347 #[cfg(debug_assertions)]
351 if let Some(duplicated) = duplicated(entries) {
352 return Err(Exit::err(DUPLICATE_STATUS, format!("error: commands declared more than once: {duplicated}\n")));
353 }
354 let name = invocation.name;
355 let descriptions = entries.iter().map(|entry| &entry.description).collect::<Vec<_>>();
356 if let Some(version) = invocation.version
357 && words.first().is_some_and(|word| is(word, "--version") || is(word, "-V"))
358 {
359 return Err(Exit::out(0, format!("{name} {version}\n")));
360 }
361 let selected = entries
362 .iter()
363 .filter_map(|entry| path_words(&entry.description, words).map(|words| (entry, words)))
364 .max_by_key(|(entry, _)| entry.description.path.len());
365 let Some((entry, words)) = selected else {
366 let prefix = invocation.prefix(None);
367 let help = |word: &OsString| is(word, "--help") || is(word, "-h");
368 let first = words.iter().find(|word| !help(word) && word.as_encoded_bytes().starts_with(b"-"));
369 if let Some(option) = first.filter(|_| !words.iter().any(help)) {
370 let option = option.to_string_lossy();
371 let spelled = option.split_once('=').map_or(&*option, |(spelled, _)| spelled);
372 return Err(Exit::err(
373 invocation.usage,
374 format!(
375 "{prefix}: unknown option `{spelled}`\n\n{}",
376 help::program(name, &descriptions, invocation.version)
377 ),
378 ));
379 }
380 return Err(match words.first().map(|word| word.to_string_lossy()) {
381 None => Exit::err(invocation.usage, help::program(name, &descriptions, invocation.version)),
382 Some(word) if matches!(&*word, "--help" | "-h" | "help") => {
383 Exit::out(0, help::program(name, &descriptions, invocation.version))
384 }
385 Some(word) => match invocation.unknown {
386 Some((status, message)) => Exit::err(*status, format!("{}\n", message(&word))),
387 None => Exit::err(
388 invocation.usage,
389 format!(
390 "{prefix}: unknown command `{word}`\n\n{}",
391 help::program(name, &descriptions, invocation.version)
392 ),
393 ),
394 },
395 });
396 };
397 let description = &entry.description;
398 let conventions = description.conventions;
399 let prefix = invocation.prefix(Some(description));
400 let rest = &words[..];
401 let arguments = description.context.iter().chain(&description.arguments).cloned().collect::<Vec<_>>();
402 let declares_help = arguments.iter().any(|argument| {
403 matches!(&argument.source, SourceInfo::Named { long, short, short_aliases } if long == "help" || *short == Some('h') || short_aliases.contains(&'h'))
404 });
405 let options = rest.iter().take_while(|word| !(conventions.double_dash_ends_options && is(word, "--")));
407 if !declares_help && !conventions.verbatim && options.into_iter().any(|word| is(word, "--help") || is(word, "-h")) {
408 if description.path.is_empty() {
410 return Err(Exit::out(0, help::program(name, &descriptions, invocation.version)));
411 }
412 return Err(Exit::out(0, help::command(name, description)));
413 }
414 let usage =
415 |error: String| Exit::err(invocation.usage, format!("{prefix}: {error}\n\n{}", help::usage(name, description)));
416 let parsed = Parsed::new(&arguments, rest, conventions).map_err(|error| usage(parse_error(&error, rest)))?;
417
418 entry.decode(&parsed, &prefix).map_err(|error| usage(argument_error(&error)))
419}
420
421#[cfg(debug_assertions)]
424fn duplicated<Handle>(entries: &[Entry<Handle>]) -> Option<String> {
425 let paths = entries.iter().map(|entry| &entry.description.path).collect::<Vec<_>>();
426 let mut duplicated = Vec::new();
427 for (at, path) in paths.iter().enumerate() {
428 if paths[..at].contains(path) && !duplicated.contains(path) {
429 duplicated.push(*path);
430 }
431 }
432 let named = duplicated.iter().map(|path| format!("`{}`", path.join(" "))).collect::<Vec<_>>();
433 (!named.is_empty()).then(|| named.join(", "))
434}
435
436fn path_words(description: &CommandDescription, words: &[OsString]) -> Option<Vec<OsString>> {
442 let mut cursor = Cursor::new(words);
443 let mut global = Vec::new();
444 for segment in &description.path {
445 loop {
446 let start = cursor.at();
447 if is(words.get(start)?, segment) {
448 cursor.bump();
449 break;
450 }
451 let conventions = Conventions { double_dash_ends_options: false, ..Conventions::default() };
453 let read = read_word(&description.context, conventions, &mut cursor, &mut Skipped).ok()??;
454 if read != Read::Options {
455 return None;
456 }
457 global.extend_from_slice(&words[start..cursor.at()]);
458 }
459 }
460 global.extend_from_slice(&words[cursor.at()..]);
461
462 Some(global)
463}
464
465fn parse_error(error: &ParseError, words: &[OsString]) -> String {
467 let said = match &error.kind {
468 ParseErrorKind::Unknown(spelling) => format!("unknown option `{spelling}`"),
469 ParseErrorKind::MissingValue(spelling) => format!("`{spelling}` needs a value"),
470 ParseErrorKind::SwitchValue(spelling) => format!("`{spelling}` takes no value"),
471 ParseErrorKind::Unexpected(word) => return format!("unexpected argument `{word}`"),
472 };
473 match words.get(error.at.word).map(|word| word.to_string_lossy()) {
474 Some(word) if error.at.byte > 1 => format!("{said} in `{word}`"),
476 _ => said,
477 }
478}
479
480fn argument_error(error: &CliArgumentError<String>) -> String {
481 let spelled = |name: &str| name.replace('_', "-");
483 match error {
484 CliArgumentError::Missing(name) => format!("missing <{}>", spelled(name)),
485 CliArgumentError::Repeated(name) => format!("<{}> given more than once", spelled(name)),
486 CliArgumentError::Word(name, reason) => format!("invalid <{}>: {reason}", spelled(name)),
487 CliArgumentError::Conflict(first, second) => {
488 format!("<{}> and <{}> cannot be given together", spelled(first), spelled(second))
489 }
490 }
491}
492
493fn outcome<Value, Error>(outcome: CliOutcome<Value, Error>, prefix: &str) -> Result<Value, Exit>
495where
496 Error: Display + CliFailureAlg,
497{
498 let status = outcome.cli_status();
499 match outcome {
500 CliOutcome::Success(value) => Ok(value),
501 CliOutcome::Failure(error) if error.cli_reported() => Err(Exit::err(status, String::new())),
503 CliOutcome::Failure(error) => Err(Exit::err(status, format!("{prefix}: {error:#}\n"))),
505 }
506}
507
508impl<Handle, Decoder> CliCommandsAlg for DirectCompiler<Handle, Decoder> {
509 type Commands = Vec<Entry<Handle, Decoder>>;
510
511 fn cli_empty(&self) -> Self::Commands {
512 Vec::new()
513 }
514
515 fn cli_merge(&self, mut left: Self::Commands, right: Self::Commands) -> Self::Commands {
516 left.extend(right);
517 left
518 }
519}
520
521impl<Handle, Decoder> CliNestAlg for DirectCompiler<Handle, Decoder> {
522 type Commands = Vec<Entry<Handle, Decoder>>;
523
524 fn cli_nest(&self, name: &'static str, mut commands: Self::Commands) -> Self::Commands {
525 for entry in &mut commands {
526 entry.description.path.insert(0, name);
527 }
528 commands
529 }
530
531 fn cli_nest_with(&self, name: &'static str, compile: impl FnOnce(&Self) -> Self::Commands) -> Self::Commands {
533 if !self.compiles(name) {
534 return Vec::new();
535 }
536 self.cli_nest(name, compile(&Self::default()))
537 }
538}
539
540impl<Handle, Decoder, Operation, Sources, Mode> CliOperationAlg<Operation, Sources, Mode>
541 for DirectCompiler<Handle, Decoder>
542where
543 Handle: Send + 'static,
544 Decoder: 'static,
545 Operation: OperationAlg + ApplyAlg<Handle, Operation::Args> + Send + Sync + 'static,
546 Operation::Args: Send,
547 Sources: CliSources<Operation::Args> + CliDecodeSources<Operation::Args, Decoder, String> + Send + Sync + 'static,
548 Mode: CliOutcomeOf<Operation::Output> + Send + Sync + 'static,
549 Mode::Value: DirectRender,
550 Mode::Error: Display + CliFailureAlg,
551{
552 type Commands = Vec<Entry<Handle, Decoder>>;
553
554 fn cli_operation(
555 &self,
556 name: &'static str,
557 operation: Operation,
558 sources: Sources,
559 mode: Mode,
560 conventions: Conventions,
561 ) -> Self::Commands {
562 if !self.compiles(name) {
563 return Vec::new();
564 }
565 let mut description = CommandDescription::of::<Operation, Sources>(name, &sources);
566 description.conventions = conventions;
567 let (operation, mode) = (Arc::new(operation), Arc::new(mode));
568 let decode: Decode<Handle, Decoder> = Arc::new(move |parsed, _, arguments, prefix| {
569 let args = sources.cli_decode(arguments, parsed)?;
570 let (operation, mode, prefix) = (Arc::clone(&operation), Arc::clone(&mode), prefix.to_owned());
571 Ok(Box::new(move |handle| {
572 Box::pin(async move {
573 match outcome(mode.cli_outcome(operation.apply(handle, args).await), &prefix) {
574 Ok(value) => {
575 let mut out = String::new();
576 value.render(&mut out);
577 if !out.is_empty() {
578 out.push('\n');
579 }
580 Exit::out(0, out)
581 }
582 Err(exit) => exit,
583 }
584 }) as Running
585 }) as Ready<Handle>)
586 });
587 vec![Entry { description, decode }]
588 }
589}
590
591impl<Handle, Decoder, Operation, Sources, Mode> CliContextAlg<Operation, Sources, Mode>
596 for DirectCompiler<Handle, Decoder>
597where
598 Handle: Send + 'static,
599 Decoder: 'static,
600 Operation: OperationAlg + ApplyAlg<Handle, Operation::Args> + Send + Sync + 'static,
601 Operation::Args: Send,
602 Sources: CliSources<Operation::Args> + CliDecodeSources<Operation::Args, Decoder, String> + Send + Sync + 'static,
603 Mode: CliOutcomeOf<Operation::Output> + Send + Sync + 'static,
604 Mode::Value: Send + 'static,
605 Mode::Error: Display + CliFailureAlg,
606{
607 type Inner = DirectCompiler<Mode::Value, Decoder>;
608 type InnerCommands = Vec<Entry<Mode::Value, Decoder>>;
609 type Commands = Vec<Entry<Handle, Decoder>>;
610
611 fn cli_inner(&self) -> Self::Inner {
613 DirectCompiler { selected: self.selected, marker: PhantomData }
614 }
615
616 fn cli_within(
617 &self,
618 operation: Operation,
619 sources: Sources,
620 mode: Mode,
621 commands: Self::InnerCommands,
622 ) -> Self::Commands {
623 let global = sources.cli_arguments(Operation::ARG_NAMES);
624 let count = global.len();
625 let (operation, sources, mode) = (Arc::new(operation), Arc::new(sources), Arc::new(mode));
626 commands
627 .into_iter()
628 .map(|Entry { mut description, decode: inner }| {
629 description.context.splice(0..0, global.iter().cloned());
630 let (operation, sources, mode) = (Arc::clone(&operation), Arc::clone(&sources), Arc::clone(&mode));
631 let decode: Decode<Handle, Decoder> = Arc::new(move |parsed, context, arguments, prefix| {
632 let (global, inner_context) = context.split_at(count);
634 let args = sources.cli_decode(global, parsed)?;
635 let command = inner(parsed, inner_context, arguments, prefix)?;
636 let (operation, mode, prefix) = (Arc::clone(&operation), Arc::clone(&mode), prefix.to_owned());
637 Ok(Box::new(move |handle| {
638 Box::pin(async move {
639 match outcome(mode.cli_outcome(operation.apply(handle, args).await), &prefix) {
640 Ok(context) => command(context).await,
641 Err(exit) => exit,
642 }
643 }) as Running
644 }) as Ready<Handle>)
645 });
646 Entry { description, decode }
647 })
648 .collect()
649 }
650}
651
652struct Unpark(Thread);
654
655impl Wake for Unpark {
656 fn wake(self: Arc<Self>) {
657 self.0.unpark();
658 }
659}
660
661fn block_on<Output>(future: impl Future<Output = Output>) -> Output {
663 let mut future = core::pin::pin!(future);
664 let waker = Waker::from(Arc::new(Unpark(thread::current())));
665 let mut context = Context::from_waker(&waker);
666 loop {
667 if let Poll::Ready(output) = future.as_mut().poll(&mut context) {
668 return output;
669 }
670 thread::park();
671 }
672}