Files
HEL/hel/src/parser.rs
T
ok 4cb3464e86 hel: pb multi-sink copy, enc command-consumer, proper help
pb: built-in fan-out to every clipboard on PATH (pbcopy/wl-copy/xclip
-selection clipboard/xsel -ib/tmux in a session); no HEL_PB script needed.
Override via 'set hel_pb' or $HEL_PB still honored; no sink -> data on stdout.

enc: takes a sub-command like pb. 'enc ls|ld <regex>' encodes the last match
(newest for ld); literal name/id wins first. ls/ld emit bare names when
captured (LKEval.capture), so 'pb ld <re>' copies names. Producers limited to
ls/ld (enc never runs a mutating command). 'set hel_enc_strict 1' errors on
>1 match.

help: 'help [topic]' — grouped overview + per-topic detail (every command, the
entry descriptor, all modes with examples, parent/master chaining, config keys,
files/env, Notion store/load subcommands). Old inline help string removed.

Tests added for all three; native + wasm32 builds green.
2026-06-14 17:58:05 +02:00

508 lines
22 KiB
Rust

extern crate peg;
use crate::password::Password;
use crate::structs::{Command, LKErr, Mode};
use crate::utils::date::Date;
peg::parser! {
pub grammar command_parser() for str {
pub rule cmd() -> Command<'input> = c:(info_cmd_list() / mod_cmd_list() / enc_cmd_list() / asides_cmd_list()) { c }
pub rule info_cmd_list() -> Command<'input> = space()* c:(ls_cmd() / ld_cmd() / pb_cmd() / save_cmd() / save_def_cmd() / dump_cmd()) { c }
pub rule mod_cmd_list() -> Command<'input> = space()* c:(add_cmd() / keep_cmd() / mv_cmd() / rm_cmd() / comment_cmd ()) { c }
pub rule asides_cmd_list() -> Command<'input> = space()* c:(help_cmd() / source_cmd() / set_cmd() / quit_cmd() / noop_cmd() / error_cmd()) { c }
pub rule enc_cmd_list() -> Command<'input> = space()* c:(enc_cmd() / gen_cmd() / pass_cmd() / unpass_cmd() / correct_cmd() / uncorrect_cmd()) { c }
pub rule script() -> Vec<Command<'input>> = c:(info_cmd_list() / mod_cmd_list() / enc_cmd_list() / asides_cmd_list()) ++ "\n" { c }
rule space() -> &'input str = s:$(
" " // Space (U+0020)
/ "\u{00A0}" // Non-breaking space (U+00A0)
/ "\u{2009}" // Thin space (U+2009)
/ "\u{2003}" // Em space (U+2003)
/ "\u{2002}" // En space (U+2002)
/ "\t" // Tab (U+0009)
// / "\n" // Line feed (U+000A)
/ "\r" // Carriage return (U+000D)
/ "\u{000C}" // Form feed (U+000C)
/ "\u{200B}" // Zero-width space (U+200B)
/ "\u{3000}" // Ideographic space (U+3000)
) { s }
rule _() -> &'input str = s:$(space()+) { s }
rule comment() -> String = _ c:$([' '..='~']+) { c.to_string() }
rule word() -> String = n:$(['!'..='~']+) { n.to_string() }
rule num() -> u32 = n:$(['0'..='9']+) {? n.parse().or(Err("not a number")) }
rule pname() -> Password = &(word() _ word() _ num()? mode() _ num() _ date()) pr:word() _ pn:word() _ pl:num()? pm:mode() _ ps:num() _ pd:date() pc:comment()?
{ Password::new(Some(pr), pn, pl, pm, ps, pd, pc) }
rule jname() -> Password = &(word() _ num()? mode() _ num() _ date()) pn:word() _ pl:num()? pm:mode() _ ps:num() _ pd:date() pc:comment()?
{ Password::new(None, pn, pl, pm, ps, pd, pc) }
rule mname() -> Password = &(word() _ word() _ num()? mode() _ date()) pr:word() _ pn:word() _ pl:num()? pm:mode() _ pd:date() pc:comment()?
{ Password::new(Some(pr), pn, pl, pm, 99, pd, pc) }
// prefix + name + [len]mode (no seq/date) -> defaults seq 99, date now
rule npname() -> Password = &(word() _ word() _ num()? mode()) pr:word() _ pn:word() _ pl:num()? pm:mode() pc:comment()?
{ Password::new(Some(pr), pn, pl, pm, 99, Date::now(), pc) }
rule sname() -> Password = &(word() _ num()? mode() _ date()) pn:word() _ pl:num()? pm:mode() _ pd:date() pc:comment()?
{ Password::new(None, pn, pl, pm, 99, pd, pc) }
rule nname() -> Password = &(word() _ num()? mode()) pn:word() _ pl:num()? pm:mode() pc:comment()?
{ Password::new(None, pn, pl, pm, 99, Date::now(), pc) }
// prefix + name (+ optional comment) -> defaults mode R, seq 99, date now.
// A `^parent` token is never a name, so a `^`-leading second word fails here and
// falls through to qname, which keeps it as the comment (the parent marker).
rule qpname() -> Password = &(word() _ word()) pr:word() _ pn:$(!"^" ['!'..='~']+) pc:comment()?
{ Password::new(Some(pr), pn.to_string(), None, Mode::Regular, 99, Date::now(), pc) }
// name (+ optional comment) -> e.g. `github` or `github ^work`
rule qname() -> Password = pn:word() pc:comment()?
{ Password::new(None, pn, None, Mode::Regular, 99, Date::now(), pc) }
pub rule name() -> Password = name:(jname() / pname() / mname() / npname() / sname() / nname() / qpname() / qname())? {?
match name { Some(n) => Ok(n), None => Err("failed to parse password description") }
}
rule ndate() -> Date = y:$("-"? ['0'..='9']*<1,4>) "-" m:$(['0'..='9']*<1,2>) "-" d:$(['0'..='9']*<1,2>) {?
let year: i32 = match y.parse() { Ok(n) => n, Err(_) => return Err("year") };
let month: u32 = match m.parse() { Ok(n) => n, Err(_) => return Err("month") };
let day: u32 = match d.parse() { Ok(n) => n, Err(_) => return Err("day") };
Date::try_new(year, month, day)
}
rule cdate() -> Date = "now" { Date::now() }
rule date() -> Date = d:(ndate() / cdate()) { d }
rule umode() -> Mode = ("U" / "u") m:$("R" / "r" / "N" / "n" / "H" / "h" / "B" / "b") {?
match m.to_uppercase().as_str() {
"R" => Ok(Mode::RegularUpcase),
"N" => Ok(Mode::NoSpaceUpcase),
"H" => Ok(Mode::HexUpcase),
"B" => Ok(Mode::Base64Upcase),
_ => Err("unknown mode"),
}
}
rule rmode() -> Mode = m:$("R" / "r" / "U" / "u" / "N" / "n" / "C" / "c" / "H" / "h" / "B" / "b" / "D" / "d") {?
match m.to_uppercase().as_str() {
"R" => Ok(Mode::Regular),
"N" => Ok(Mode::NoSpace),
"C" => Ok(Mode::NoSpaceCamel),
"U" => Ok(Mode::RegularUpcase),
"H" => Ok(Mode::Hex),
"B" => Ok(Mode::Base64),
"D" => Ok(Mode::Decimal),
_ => Err("unknown mode"),
}
}
// A mode is a whole token: it must not be followed by another letter/digit, or
// a single letter would be stolen from a longer word (e.g. the `n` of `now`,
// making `name r now` mis-parse as name=`r`, mode=`n` instead of date=`now`).
rule mode() -> Mode = m:(umode() / rmode()) !['0'..='9' | 'a'..='z' | 'A'..='Z'] { m }
rule noop_cmd() -> Command<'input> = ("#" [' '..='~']*)? { Command::Noop }
rule help_cmd() -> Command<'input> = "help" t:(_ w:word() { w })? { Command::Help(t) }
rule quit_cmd() -> Command<'input> = "quit" { Command::Quit }
rule pb_cmd() -> Command<'input> = "pb" _ e:$(([' '..='~'])+) { Command::PasteBuffer(e.to_string()) }
rule save_cmd() -> Command<'input> = "save" _ s:$(([' '..='~'])+) { Command::Dump(Some(s.to_string())) }
rule save_def_cmd() -> Command<'input> = "save" { Command::Dump(None) }
rule dump_cmd() -> Command<'input> = "dump" { Command::Dump(Some("-".to_string())) }
rule source_cmd() -> Command<'input> = "source" _ s:$(([' '..='~'])+) { Command::Source(s.to_string()) }
rule set_cmd() -> Command<'input> = "set" _ k:word() _ v:$(([' '..='~'])+) { Command::Set(k, v.to_string()) }
rule ls_cmd() -> Command<'input> = "ls" f:comment()? { Command::Ls(f.unwrap_or(".".to_string())) }
rule ld_cmd() -> Command<'input> = "ld" f:comment()? { Command::Ld(f.unwrap_or(".".to_string())) }
rule add_cmd() -> Command<'input> = "add" _ name:name() { Command::Add(Password::from_password(name)) }
rule keep_cmd() -> Command<'input> = "keep" _ name:word() { Command::Keep(name.to_string()) }
rule gen_cmd() -> Command<'input> = "gen" n:num()? _ name:name() {
Command::Gen(match n { Some(n) => n, None => 10_u32 }, Password::from_password(name))
}
rule error_cmd() -> Command<'input> = "error" _ e:$(([' '..='~'])+) { Command::Error(LKErr::Error(e)) }
rule mv_cmd() -> Command<'input> = "mv" _ name:word() _ folder:word() { Command::Mv(name, folder) }
rule pass_short_cmd() -> Command<'input> = "pass" _ name:word() { Command::Pass(name, None) }
rule pass_long_cmd() -> Command<'input> = "pass" _ name:word() _ pass:$(([' '..='~'])+) { Command::Pass(name, Some(pass.to_string())) }
rule pass_cmd() -> Command<'input> = p:(pass_long_cmd() / pass_short_cmd()) { p }
rule correct_cmd() -> Command<'input> = "correct" _ name:word() { Command::Correct(name) }
rule uncorrect_cmd() -> Command<'input> = "uncorrect" _ name:word() { Command::Uncorrect(name) }
rule unpass_cmd() -> Command<'input> = "unpass" name:(_ w:word() { w })? { Command::UnPass(name) }
// `enc` takes the rest of the line (like `pb`): a bare name/id, or a
// sub-command whose output names the entry to encode (e.g. `enc ld re`).
rule enc_cmd() -> Command<'input> = "enc" _ e:$(([' '..='~'])+) { Command::Enc(e.to_string()) }
rule rm_cmd() -> Command<'input> = "rm" _ name:word() { Command::Rm(name) }
rule comment_cmd() -> Command<'input> = "comment" _ name:word() c:comment()? { Command::Comment(name, c) }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_script_test() {
assert_eq!(
command_parser::script(
r###"add t1 C 99 2022-12-14
add t2 C 99 2022-12-14
add t3 C 99 2022-12-14"###
),
Ok(vec![
Command::Add(Password::from_password(Password {
parent: None,
prefix: None,
name: "t1".to_string(),
length: None,
mode: Mode::NoSpaceCamel,
seq: 99,
date: Date::new(2022, 12, 14),
comment: None
})),
Command::Add(Password::from_password(Password {
parent: None,
prefix: None,
name: "t2".to_string(),
length: None,
mode: Mode::NoSpaceCamel,
seq: 99,
date: Date::new(2022, 12, 14),
comment: None
})),
Command::Add(Password::from_password(Password {
parent: None,
prefix: None,
name: "t3".to_string(),
length: None,
mode: Mode::NoSpaceCamel,
seq: 99,
date: Date::new(2022, 12, 14),
comment: None
}))
])
);
assert_eq!(
command_parser::script(
r###"add t1 C 99 2022-12-14
add t2 C 99 2022-12-14
add t3 C 99 2022-12-14
"###
),
Ok(vec![
Command::Add(Password::from_password(Password {
parent: None,
prefix: None,
name: "t1".to_string(),
length: None,
mode: Mode::NoSpaceCamel,
seq: 99,
date: Date::new(2022, 12, 14),
comment: None
})),
Command::Add(Password::from_password(Password {
parent: None,
prefix: None,
name: "t2".to_string(),
length: None,
mode: Mode::NoSpaceCamel,
seq: 99,
date: Date::new(2022, 12, 14),
comment: None
})),
Command::Add(Password::from_password(Password {
parent: None,
prefix: None,
name: "t3".to_string(),
length: None,
mode: Mode::NoSpaceCamel,
seq: 99,
date: Date::new(2022, 12, 14),
comment: None
})),
Command::Noop
])
);
assert_eq!(
command_parser::script(
r###"add t1 C 99 2022-12-14
add t2 C 99 2022-12-14
add t3 C 99 2022-12-14
# some comment
"###
),
Ok(vec![
Command::Add(Password::from_password(Password {
parent: None,
prefix: None,
name: "t1".to_string(),
length: None,
mode: Mode::NoSpaceCamel,
seq: 99,
date: Date::new(2022, 12, 14),
comment: None
})),
Command::Add(Password::from_password(Password {
parent: None,
prefix: None,
name: "t2".to_string(),
length: None,
mode: Mode::NoSpaceCamel,
seq: 99,
date: Date::new(2022, 12, 14),
comment: None
})),
Command::Add(Password::from_password(Password {
parent: None,
prefix: None,
name: "t3".to_string(),
length: None,
mode: Mode::NoSpaceCamel,
seq: 99,
date: Date::new(2022, 12, 14),
comment: None
})),
Command::Noop,
Command::Noop
])
);
}
#[test]
fn parse_enc_arg_test() {
// `enc` now captures the rest of the line (like `pb`): a bare name/id,
// or a sub-command (`ld <regex>`) resolved at eval time.
assert_eq!(command_parser::cmd("enc t3"), Ok(Command::Enc("t3".to_string())));
assert_eq!(command_parser::cmd("enc 3"), Ok(Command::Enc("3".to_string())));
assert_eq!(
command_parser::cmd("enc ld micro.*exa"),
Ok(Command::Enc("ld micro.*exa".to_string()))
);
assert_eq!(
command_parser::cmd("enc ls foo"),
Ok(Command::Enc("ls foo".to_string()))
);
// Display round-trips.
assert_eq!(Command::Enc("ld micro.*exa".to_string()).to_string(), "enc ld micro.*exa");
}
#[test]
fn parse_help_test() {
assert_eq!(command_parser::cmd("help"), Ok(Command::Help(None)));
assert_eq!(command_parser::cmd("help enc"), Ok(Command::Help(Some("enc".to_string()))));
assert_eq!(command_parser::cmd("help modes"), Ok(Command::Help(Some("modes".to_string()))));
assert_eq!(Command::Help(Some("enc".to_string())).to_string(), "help enc");
assert_eq!(Command::Help(None).to_string(), "help");
}
#[test]
fn parse_short_parent_test() {
// `name ^parent` (no mode/date): name is the name, ^parent stays in the comment
// for fix_hierarchy — it must NOT be read as prefix+name.
let p = command_parser::name("x ^acc").unwrap();
assert_eq!(p.name, "x");
assert_eq!(p.prefix, None);
assert_eq!(p.comment, Some("^acc".to_string()));
// `name [len]mode ^parent` keeps the parent in the comment too
let p2 = command_parser::name("x 20R ^acc").unwrap();
assert_eq!(p2.name, "x");
assert_eq!(p2.length, Some(20));
assert_eq!(p2.mode, Mode::Regular);
assert_eq!(p2.comment, Some("^acc".to_string()));
// a real prefix + name (second word not ^-led) still parses as prefix+name
let p3 = command_parser::name("#W9 github").unwrap();
assert_eq!(p3.prefix, Some("#W9".to_string()));
assert_eq!(p3.name, "github");
assert_eq!(p3.comment, None);
}
#[test]
fn parse_mode_word_boundary_test() {
// `now` must be the date, not mode `n` + leftover `ow`: name=testG mode=Regular.
let g = command_parser::name("testG r now").unwrap();
assert_eq!(g.name, "testG");
assert_eq!(g.prefix, None);
assert_eq!(g.mode, Mode::Regular);
// the whole gen command parses with no trailing-input error (so `now` was
// consumed as the date, not as a mode that left `ow` dangling)
assert!(command_parser::cmd("gen testG r now").is_ok());
assert!(command_parser::cmd("gen testG R now").is_ok());
// a length+mode token still works right up to a word boundary
let h = command_parser::name("github 20R").unwrap();
assert_eq!(h.name, "github");
assert_eq!(h.length, Some(20));
assert_eq!(h.mode, Mode::Regular);
}
#[test]
fn parse_password_test() {
assert_eq!(
command_parser::name("ableton89 R 99 2020-12-09 xx.ableton@domain.info https://www.ableton.com"),
Ok(Password {
name: "ableton89".to_string(),
parent: None,
prefix: None,
mode: Mode::Regular,
length: None,
seq: 99,
date: Date::new(2020, 12, 09),
comment: Some("xx.ableton@domain.info https://www.ableton.com".to_string())
})
);
assert_eq!(
command_parser::name("ableton89 U 99 2020-12-09 xx.ableton@domain.info https://www.ableton.com"),
Ok(Password {
name: "ableton89".to_string(),
parent: None,
prefix: None,
mode: Mode::RegularUpcase,
length: None,
seq: 99,
date: Date::new(2020, 12, 09),
comment: Some("xx.ableton@domain.info https://www.ableton.com".to_string())
})
);
assert_eq!(
command_parser::name("ableton89 U 2020-12-09"),
Ok(Password {
name: "ableton89".to_string(),
parent: None,
prefix: None,
mode: Mode::RegularUpcase,
length: None,
seq: 99,
date: Date::new(2020, 12, 09),
comment: None
})
);
assert_eq!(
command_parser::name("#W9 ableton89 R 99 2020-12-09 xx.ableton@domain.info https://www.ableton.com"),
Ok(Password {
name: "ableton89".to_string(),
parent: None,
prefix: Some("#W9".to_string()),
mode: Mode::Regular,
length: None,
seq: 99,
date: Date::new(2020, 12, 09),
comment: Some("xx.ableton@domain.info https://www.ableton.com".to_string())
})
);
assert_eq!(
command_parser::name("#W9 ableton89 N 99 2020-12-09 xx.ableton@domain.info https://www.ableton.com"),
Ok(Password {
name: "ableton89".to_string(),
parent: None,
prefix: Some("#W9".to_string()),
mode: Mode::NoSpace,
length: None,
seq: 99,
date: Date::new(2020, 12, 09),
comment: Some("xx.ableton@domain.info https://www.ableton.com".to_string())
})
);
assert_eq!(
command_parser::name("#W9 ableton89 UN 99 2020-12-09 xx.ableton@domain.info https://www.ableton.com"),
Ok(Password {
name: "ableton89".to_string(),
parent: None,
prefix: Some("#W9".to_string()),
mode: Mode::NoSpaceUpcase,
length: None,
seq: 99,
date: Date::new(2020, 12, 09),
comment: Some("xx.ableton@domain.info https://www.ableton.com".to_string())
})
);
assert_eq!(
command_parser::name("#W9 ableton89 20R 99 2020-12-09 a b c"),
Ok(Password {
name: "ableton89".to_string(),
parent: None,
prefix: Some("#W9".to_string()),
mode: Mode::Regular,
length: Some(20),
seq: 99,
date: Date::new(2020, 12, 09),
comment: Some("a b c".to_string())
})
);
assert_eq!(
command_parser::name("#W9 ableton89 20UR 99 2020-12-09 a b c"),
Ok(Password {
name: "ableton89".to_string(),
parent: None,
prefix: Some("#W9".to_string()),
mode: Mode::RegularUpcase,
length: Some(20),
seq: 99,
date: Date::new(2020, 12, 09),
comment: Some("a b c".to_string())
})
);
assert_eq!(
command_parser::name("#W9 ableton89 20UH 99 2020-12-09 a b c"),
Ok(Password {
name: "ableton89".to_string(),
parent: None,
prefix: Some("#W9".to_string()),
mode: Mode::HexUpcase,
length: Some(20),
seq: 99,
date: Date::new(2020, 12, 09),
comment: Some("a b c".to_string())
})
);
assert_eq!(
command_parser::name("#W9 ableton89 20UB 99 2020-12-09 a b c"),
Ok(Password {
name: "ableton89".to_string(),
parent: None,
prefix: Some("#W9".to_string()),
mode: Mode::Base64Upcase,
length: Some(20),
seq: 99,
date: Date::new(2020, 12, 09),
comment: Some("a b c".to_string())
})
);
assert_eq!(
command_parser::name("#W9 ableton89 20D 99 2020-12-09 a b c"),
Ok(Password {
name: "ableton89".to_string(),
parent: None,
prefix: Some("#W9".to_string()),
mode: Mode::Decimal,
length: Some(20),
seq: 99,
date: Date::new(2020, 12, 09),
comment: Some("a b c".to_string())
})
);
assert_eq!(
command_parser::name("ableton89 20D 98 2020-12-09 a b c"),
Ok(Password {
name: "ableton89".to_string(),
parent: None,
prefix: None,
mode: Mode::Decimal,
length: Some(20),
seq: 98,
date: Date::new(2020, 12, 09),
comment: Some("a b c".to_string())
})
);
assert_eq!(
command_parser::name("ableton89 20C 98 2020-12-09 a b c"),
Ok(Password {
name: "ableton89".to_string(),
parent: None,
prefix: None,
mode: Mode::NoSpaceCamel,
length: Some(20),
seq: 98,
date: Date::new(2020, 12, 09),
comment: Some("a b c".to_string())
})
);
assert_eq!(
command_parser::name("ableton89 20D 2020-12-09 a b c"),
Ok(Password {
name: "ableton89".to_string(),
parent: None,
prefix: None,
mode: Mode::Decimal,
length: Some(20),
seq: 99,
date: Date::new(2020, 12, 09),
comment: Some("a b c".to_string())
})
);
}
}