mod engine;
pub mod man;
mod shell;
use std::{
ffi::OsStr,
io::Write as _,
path::Path,
};
pub use engine::{
Completions,
Fallback,
Line,
};
use pound::spec::CommandSpec;
pub use shell::{
Shell,
UnknownShell,
};
pub fn handle(spec: &CommandSpec) {
let Some(request) = Request::from_env(spec) else {
return;
};
let code = match request {
Ok(request) => {
let answer = request.answer(spec);
i32::from(std::io::stdout().write_all(answer.as_bytes()).is_err())
},
Err(err) => {
let _ = writeln!(std::io::stderr(), "error: {err}");
2
},
};
std::process::exit(code);
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Request {
Script { shell: Shell, program: String },
Complete { shell: Shell, line: Line },
}
impl Request {
#[must_use]
pub fn from_env(spec: &CommandSpec) -> Option<Result<Self, UnknownShell>> {
let shell = std::env::var_os("COMPLETE").filter(|v| !v.is_empty() && v != "0")?;
let shell = match shell.to_string_lossy().parse::<Shell>() {
Ok(shell) => shell,
Err(err) => return Some(Err(err)),
};
let mut args = std::env::args_os();
let program = args
.next()
.and_then(|arg0| program_name(&arg0))
.unwrap_or_else(|| spec.name.to_owned());
let rest = args.map(|arg| arg.to_string_lossy().into_owned());
let cursor = std::env::var("COMPLETE_INDEX")
.ok()
.and_then(|i| i.parse().ok());
Some(Ok(Self::from_args(shell, program, rest, cursor)))
}
#[must_use]
pub fn from_args(
shell: Shell,
program: String,
args: impl IntoIterator<Item = String>,
cursor: Option<usize>,
) -> Self {
let mut args = args.into_iter();
if args.next().as_deref() != Some("--") {
return Self::Script { shell, program };
}
let mut words = args.collect::<Vec<_>>();
let typed = match cursor {
Some(at) => {
let typed = words.get(at).cloned().unwrap_or_default();
words.truncate(at);
typed
},
None => words.pop().unwrap_or_default(),
};
Self::Complete {
shell,
line: Line::new(words, typed),
}
}
#[must_use]
pub fn answer(&self, spec: &CommandSpec) -> String {
match self {
Self::Script { shell, program } => shell.script(program),
Self::Complete { shell, line } => shell.render(&line.complete(spec)),
}
}
}
fn program_name(arg0: &OsStr) -> Option<String> {
let name = Path::new(arg0).file_name()?.to_string_lossy();
(!name.is_empty()).then(|| name.into_owned())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn words_after_dashes_are_a_line_with_the_cursor_last() {
let args = ["--", "open", "db"].map(String::from);
let request = Request::from_args(Shell::Fish, "vault".to_owned(), args, None);
let line = Line::new(vec!["open".to_owned()], "db".to_owned());
assert_eq!(request, Request::Complete {
shell: Shell::Fish,
line,
});
let script = Request::from_args(Shell::Fish, "vault".to_owned(), [], None);
assert!(matches!(script, Request::Script { .. }));
}
}