Skip to main content

link_cli/
cli.rs

1//! Command-line argument parsing for the `clink` binary.
2
3use crate::protocol::ArityRange;
4use anyhow::{bail, Result};
5use std::env;
6use std::ffi::OsString;
7
8const DEFAULT_DATABASE_FILENAME: &str = "db.links";
9
10#[derive(Debug, Clone, PartialEq, Eq)]
11pub struct Cli {
12    pub db: String,
13    pub query: Option<String>,
14    pub query_arg: Option<String>,
15    pub trace: bool,
16    pub indexed_lookups: bool,
17    pub auto_create_missing_references: bool,
18    pub structure: Option<u32>,
19    pub before: bool,
20    pub changes: bool,
21    pub after: bool,
22    pub lino_input: Option<String>,
23    pub lino_output: Option<String>,
24    pub binary_input: Option<String>,
25    pub binary_output: Option<String>,
26    pub always: bool,
27    pub once: bool,
28    pub never: bool,
29    pub triggers: bool,
30    pub triggers_file: Option<String>,
31    pub embed_triggers: bool,
32    pub transactions: bool,
33    pub transactions_file: Option<String>,
34    pub commit_mode: Option<String>,
35    pub retention: Option<String>,
36    pub vc: bool,
37    pub vc_file: Option<String>,
38    pub branch: Option<String>,
39    pub branch_from: Option<i64>,
40    pub checkout: Option<String>,
41    pub tag: Option<String>,
42    pub list_branches: bool,
43    pub list_tags: bool,
44    pub show_log: bool,
45    pub serve: Option<String>,
46    pub connect: Option<String>,
47    pub protocol: Option<String>,
48    pub external_references: bool,
49    pub arity: ArityRange,
50    pub packed_widths: bool,
51    /// `--permissions`: `self` or a links file of permission rules (issue #149).
52    pub permissions: Option<String>,
53    /// `--subject`: the link index or name queries run as.
54    pub subject: Option<String>,
55    /// `--tokens`: `self` or a links file of the token table.
56    pub tokens: Option<String>,
57    pub grant_token: Option<String>,
58    pub revoke_token: Option<String>,
59    /// `--token`: authenticates a `--connect` client.
60    pub token: Option<String>,
61}
62
63impl Default for Cli {
64    fn default() -> Self {
65        Self {
66            db: DEFAULT_DATABASE_FILENAME.to_string(),
67            query: None,
68            query_arg: None,
69            trace: false,
70            indexed_lookups: false,
71            auto_create_missing_references: false,
72            structure: None,
73            before: false,
74            changes: false,
75            after: false,
76            lino_input: None,
77            lino_output: None,
78            binary_input: None,
79            binary_output: None,
80            always: false,
81            once: false,
82            never: false,
83            triggers: false,
84            triggers_file: None,
85            embed_triggers: false,
86            transactions: false,
87            transactions_file: None,
88            commit_mode: None,
89            retention: None,
90            vc: false,
91            vc_file: None,
92            branch: None,
93            branch_from: None,
94            checkout: None,
95            tag: None,
96            list_branches: false,
97            list_tags: false,
98            show_log: false,
99            serve: None,
100            connect: None,
101            protocol: None,
102            external_references: false,
103            arity: ArityRange::DOUBLETS,
104            packed_widths: false,
105            permissions: None,
106            subject: None,
107            tokens: None,
108            grant_token: None,
109            revoke_token: None,
110            token: None,
111        }
112    }
113}
114
115#[derive(Debug, Clone, PartialEq, Eq)]
116pub enum CliCommand {
117    Run(Box<Cli>),
118    Help,
119    Version,
120}
121
122impl Cli {
123    /// True when any flag in the transactions decorator family was passed.
124    pub fn transactions_requested(&self) -> bool {
125        self.transactions
126            || self.transactions_file.is_some()
127            || self.commit_mode.is_some()
128            || self.retention.is_some()
129            || self.show_log
130            || self.vc_requested()
131    }
132
133    /// True when a trigger command — `--always`, `--once` or `--never` — was
134    /// passed. Exactly one of them may be used at a time.
135    pub fn trigger_command_count(&self) -> usize {
136        usize::from(self.always) + usize::from(self.once) + usize::from(self.never)
137    }
138
139    /// True when any flag in the persistent transformation family was passed.
140    ///
141    /// Mirrors `persistentTransformationsEnabled` in the C# tool, minus the
142    /// "the triggers file already exists" clause, which needs the resolved
143    /// path and therefore lives next to it in `main`.
144    pub fn persistent_transformations_requested(&self) -> bool {
145        self.always
146            || self.once
147            || self.never
148            || self.triggers
149            || self.embed_triggers
150            || self.triggers_file.is_some()
151    }
152
153    /// True when any flag in the version-control decorator family was passed.
154    pub fn vc_requested(&self) -> bool {
155        self.vc
156            || self.vc_file.is_some()
157            || self.branch.is_some()
158            || self.branch_from.is_some()
159            || self.checkout.is_some()
160            || self.tag.is_some()
161            || self.list_branches
162            || self.list_tags
163    }
164
165    pub fn parse() -> Result<CliCommand> {
166        lino_arguments::init();
167        Self::parse_from(env::args_os())
168    }
169
170    pub fn parse_from<I, T>(args: I) -> Result<CliCommand>
171    where
172        I: IntoIterator<Item = T>,
173        T: Into<OsString>,
174    {
175        let mut cli = Cli::default();
176        let mut args = args
177            .into_iter()
178            .map(|arg| arg.into().to_string_lossy().into_owned())
179            .peekable();
180
181        let _program = args.next();
182
183        while let Some(arg) = args.next() {
184            if let Some(value) = inline_value(&arg, &["--db", "--data-source", "--data"]) {
185                cli.db = value.to_string();
186                continue;
187            }
188            if let Some(value) = inline_value(&arg, &["--query", "--apply", "--do"]) {
189                cli.query = Some(value.to_string());
190                continue;
191            }
192            if let Some(value) = inline_value(&arg, &["--structure"]) {
193                cli.structure = Some(parse_link_id("--structure", value)?);
194                continue;
195            }
196            if let Some(value) = inline_value(&arg, &["--indexed-lookups"]) {
197                cli.indexed_lookups = parse_bool("--indexed-lookups", value)?;
198                continue;
199            }
200            if let Some(value) = inline_value(&arg, &["--trace"]) {
201                cli.trace = parse_bool("--trace", value)?;
202                continue;
203            }
204            if let Some(value) = inline_value(&arg, &["--auto-create-missing-references"]) {
205                cli.auto_create_missing_references =
206                    parse_bool("--auto-create-missing-references", value)?;
207                continue;
208            }
209            if let Some(value) = inline_value(&arg, &["--before"]) {
210                cli.before = parse_bool("--before", value)?;
211                continue;
212            }
213            if let Some(value) = inline_value(&arg, &["--changes"]) {
214                cli.changes = parse_bool("--changes", value)?;
215                continue;
216            }
217            if let Some(value) = inline_value(&arg, &["--after", "--links"]) {
218                cli.after = parse_bool("--after", value)?;
219                continue;
220            }
221            if let Some(value) = inline_value(&arg, &["--out", "--lino-output", "--export"]) {
222                cli.lino_output = Some(value.to_string());
223                continue;
224            }
225            if let Some(value) = inline_value(&arg, &["--in", "--lino-input", "--import"]) {
226                cli.lino_input = Some(value.to_string());
227                continue;
228            }
229            if let Some(value) = inline_value(
230                &arg,
231                &["--export-binary", "--binary-output", "--binary-out"],
232            ) {
233                cli.binary_output = Some(value.to_string());
234                continue;
235            }
236            if let Some(value) =
237                inline_value(&arg, &["--import-binary", "--binary-input", "--binary-in"])
238            {
239                cli.binary_input = Some(value.to_string());
240                continue;
241            }
242            if let Some(value) = inline_value(&arg, &["--always"]) {
243                cli.always = parse_bool("--always", value)?;
244                continue;
245            }
246            if let Some(value) = inline_value(&arg, &["--once"]) {
247                cli.once = parse_bool("--once", value)?;
248                continue;
249            }
250            if let Some(value) = inline_value(&arg, &["--never"]) {
251                cli.never = parse_bool("--never", value)?;
252                continue;
253            }
254            if let Some(value) = inline_value(&arg, &["--triggers"]) {
255                cli.triggers = parse_bool("--triggers", value)?;
256                continue;
257            }
258            if let Some(value) = inline_value(&arg, &["--triggers-file"]) {
259                cli.triggers_file = Some(value.to_string());
260                continue;
261            }
262            if let Some(value) = inline_value(&arg, &["--embed-triggers"]) {
263                cli.embed_triggers = parse_bool("--embed-triggers", value)?;
264                continue;
265            }
266            if let Some(value) = inline_value(&arg, &["--transactions"]) {
267                cli.transactions = parse_bool("--transactions", value)?;
268                continue;
269            }
270            if let Some(value) = inline_value(&arg, &["--transactions-file"]) {
271                cli.transactions_file = Some(value.to_string());
272                continue;
273            }
274            if let Some(value) = inline_value(&arg, &["--commit-mode"]) {
275                cli.commit_mode = Some(value.to_string());
276                continue;
277            }
278            if let Some(value) = inline_value(&arg, &["--retention"]) {
279                cli.retention = Some(value.to_string());
280                continue;
281            }
282            if let Some(value) = inline_value(&arg, &["--vc"]) {
283                cli.vc = parse_bool("--vc", value)?;
284                continue;
285            }
286            if let Some(value) = inline_value(&arg, &["--vc-file"]) {
287                cli.vc_file = Some(value.to_string());
288                continue;
289            }
290            if let Some(value) = inline_value(&arg, &["--branch"]) {
291                cli.branch = Some(value.to_string());
292                continue;
293            }
294            if let Some(value) = inline_value(&arg, &["--branch-from"]) {
295                cli.branch_from = Some(parse_seq("--branch-from", value)?);
296                continue;
297            }
298            if let Some(value) = inline_value(&arg, &["--checkout"]) {
299                cli.checkout = Some(value.to_string());
300                continue;
301            }
302            if let Some(value) = inline_value(&arg, &["--tag"]) {
303                cli.tag = Some(value.to_string());
304                continue;
305            }
306            if let Some(value) = inline_value(&arg, &["--list-branches"]) {
307                cli.list_branches = parse_bool("--list-branches", value)?;
308                continue;
309            }
310            if let Some(value) = inline_value(&arg, &["--list-tags"]) {
311                cli.list_tags = parse_bool("--list-tags", value)?;
312                continue;
313            }
314            if let Some(value) = inline_value(&arg, &["--log"]) {
315                cli.show_log = parse_bool("--log", value)?;
316                continue;
317            }
318            if let Some(value) = inline_value(&arg, &["--serve"]) {
319                cli.serve = Some(value.to_string());
320                continue;
321            }
322            if let Some(value) = inline_value(&arg, &["--connect"]) {
323                cli.connect = Some(value.to_string());
324                continue;
325            }
326            if let Some(value) = inline_value(&arg, &["--protocol"]) {
327                cli.protocol = Some(value.to_string());
328                continue;
329            }
330            if let Some(value) = inline_value(&arg, &["--external-references"]) {
331                cli.external_references = parse_bool("--external-references", value)?;
332                continue;
333            }
334            if let Some(value) = inline_value(&arg, &["--arity"]) {
335                cli.arity = parse_arity(value)?;
336                continue;
337            }
338            if let Some(value) = inline_value(&arg, &["--packed-widths"]) {
339                cli.packed_widths = parse_bool("--packed-widths", value)?;
340                continue;
341            }
342            if let Some(value) = inline_value(&arg, &["--permissions"]) {
343                cli.permissions = Some(value.to_string());
344                continue;
345            }
346            if let Some(value) = inline_value(&arg, &["--subject"]) {
347                cli.subject = Some(value.to_string());
348                continue;
349            }
350            if let Some(value) = inline_value(&arg, &["--tokens"]) {
351                cli.tokens = Some(value.to_string());
352                continue;
353            }
354            if let Some(value) = inline_value(&arg, &["--grant-token"]) {
355                cli.grant_token = Some(value.to_string());
356                continue;
357            }
358            if let Some(value) = inline_value(&arg, &["--revoke-token"]) {
359                cli.revoke_token = Some(value.to_string());
360                continue;
361            }
362            if let Some(value) = inline_value(&arg, &["--token"]) {
363                cli.token = Some(value.to_string());
364                continue;
365            }
366
367            match arg.as_str() {
368                "-h" | "--help" => return Ok(CliCommand::Help),
369                "-V" | "--version" => return Ok(CliCommand::Version),
370                "-d" | "--db" | "--data-source" | "--data" => {
371                    cli.db = next_value(&mut args, &arg)?;
372                }
373                "-q" | "--query" | "--apply" | "--do" => {
374                    cli.query = Some(next_value(&mut args, &arg)?);
375                }
376                "--indexed-lookups" => {
377                    cli.indexed_lookups = next_bool_value(&mut args, true)?;
378                }
379                "-t" | "--trace" => {
380                    cli.trace = next_bool_value(&mut args, true)?;
381                }
382                "--auto-create-missing-references" => {
383                    cli.auto_create_missing_references = next_bool_value(&mut args, true)?;
384                }
385                "-s" | "--structure" => {
386                    let value = next_value(&mut args, &arg)?;
387                    cli.structure = Some(parse_link_id(&arg, &value)?);
388                }
389                "-b" | "--before" => {
390                    cli.before = next_bool_value(&mut args, true)?;
391                }
392                "-c" | "--changes" => {
393                    cli.changes = next_bool_value(&mut args, true)?;
394                }
395                "-a" | "--after" | "--links" => {
396                    cli.after = next_bool_value(&mut args, true)?;
397                }
398                "--out" | "--lino-output" | "--export" => {
399                    cli.lino_output = Some(next_value(&mut args, &arg)?);
400                }
401                "--in" | "--lino-input" | "--import" => {
402                    cli.lino_input = Some(next_value(&mut args, &arg)?);
403                }
404                "--export-binary" | "--binary-output" | "--binary-out" => {
405                    cli.binary_output = Some(next_value(&mut args, &arg)?);
406                }
407                "--import-binary" | "--binary-input" | "--binary-in" => {
408                    cli.binary_input = Some(next_value(&mut args, &arg)?);
409                }
410                "--always" => {
411                    cli.always = next_bool_value(&mut args, true)?;
412                }
413                "--once" => {
414                    cli.once = next_bool_value(&mut args, true)?;
415                }
416                "--never" => {
417                    cli.never = next_bool_value(&mut args, true)?;
418                }
419                "--triggers" => {
420                    cli.triggers = next_bool_value(&mut args, true)?;
421                }
422                "--triggers-file" => {
423                    cli.triggers_file = Some(next_value(&mut args, &arg)?);
424                }
425                "--embed-triggers" => {
426                    cli.embed_triggers = next_bool_value(&mut args, true)?;
427                }
428                "--transactions" => {
429                    cli.transactions = next_bool_value(&mut args, true)?;
430                }
431                "--transactions-file" => {
432                    cli.transactions_file = Some(next_value(&mut args, &arg)?);
433                }
434                "--commit-mode" => {
435                    cli.commit_mode = Some(next_value(&mut args, &arg)?);
436                }
437                "--retention" => {
438                    cli.retention = Some(next_value(&mut args, &arg)?);
439                }
440                "--vc" => {
441                    cli.vc = next_bool_value(&mut args, true)?;
442                }
443                "--vc-file" => {
444                    cli.vc_file = Some(next_value(&mut args, &arg)?);
445                }
446                "--branch" => {
447                    cli.branch = Some(next_value(&mut args, &arg)?);
448                }
449                "--branch-from" => {
450                    let value = next_value(&mut args, &arg)?;
451                    cli.branch_from = Some(parse_seq(&arg, &value)?);
452                }
453                "--checkout" => {
454                    cli.checkout = Some(next_value(&mut args, &arg)?);
455                }
456                "--tag" => {
457                    cli.tag = Some(next_value(&mut args, &arg)?);
458                }
459                "--list-branches" => {
460                    cli.list_branches = next_bool_value(&mut args, true)?;
461                }
462                "--list-tags" => {
463                    cli.list_tags = next_bool_value(&mut args, true)?;
464                }
465                "--log" => {
466                    cli.show_log = next_bool_value(&mut args, true)?;
467                }
468                "--serve" => {
469                    cli.serve = Some(next_value(&mut args, &arg)?);
470                }
471                "--connect" => {
472                    cli.connect = Some(next_value(&mut args, &arg)?);
473                }
474                "--protocol" => {
475                    cli.protocol = Some(next_value(&mut args, &arg)?);
476                }
477                "--external-references" => {
478                    cli.external_references = next_bool_value(&mut args, true)?;
479                }
480                "--arity" => {
481                    cli.arity = parse_arity(&next_value(&mut args, &arg)?)?;
482                }
483                "--packed-widths" => {
484                    cli.packed_widths = next_bool_value(&mut args, true)?;
485                }
486                "--permissions" => {
487                    cli.permissions = Some(next_value(&mut args, &arg)?);
488                }
489                "--subject" => {
490                    cli.subject = Some(next_value(&mut args, &arg)?);
491                }
492                "--tokens" => {
493                    cli.tokens = Some(next_value(&mut args, &arg)?);
494                }
495                "--grant-token" => {
496                    cli.grant_token = Some(next_value(&mut args, &arg)?);
497                }
498                "--revoke-token" => {
499                    cli.revoke_token = Some(next_value(&mut args, &arg)?);
500                }
501                "--token" => {
502                    cli.token = Some(next_value(&mut args, &arg)?);
503                }
504                "--" => {
505                    for value in args.by_ref() {
506                        set_positional_query(&mut cli, value)?;
507                    }
508                    break;
509                }
510                value if value.starts_with('-') => {
511                    bail!("unknown option '{value}'");
512                }
513                value => {
514                    set_positional_query(&mut cli, value.to_string())?;
515                }
516            }
517        }
518
519        Ok(CliCommand::Run(Box::new(cli)))
520    }
521
522    pub fn print_help() {
523        print!("{}", Self::help_text());
524    }
525
526    pub fn help_text() -> &'static str {
527        concat!(
528            "LiNo CLI Tool for managing links data store\n\n",
529            "Usage: clink [OPTIONS] [QUERY]\n\n",
530            "Arguments:\n",
531            "  [QUERY]  LiNo query for CRUD operation\n\n",
532            "Options:\n",
533            "  -d, --db <DB>, --data-source <DB>, --data <DB>\n",
534            "          Path to the links database file [default: db.links]\n",
535            "  -q, --query <QUERY>, --apply <QUERY>, --do <QUERY>\n",
536            "          LiNo query for CRUD operation\n",
537            "      --indexed-lookups\n",
538            "          Use optional lookup-index decorators for local links and names (Rust only)\n",
539            "  -t, --trace\n",
540            "          Enable trace (verbose output)\n",
541            "      --auto-create-missing-references\n",
542            "          Create missing numeric and named references as self-referential point links\n",
543            "  -s, --structure <STRUCTURE>\n",
544            "          ID of the link to format its structure\n",
545            "  -b, --before\n",
546            "          Print the state of the database before applying changes\n",
547            "  -c, --changes\n",
548            "          Print the changes applied by the query\n",
549            "  -a, --after, --links\n",
550            "          Print the state of the database after applying changes\n",
551            "      --in <IN>, --lino-input <IN>, --import <IN>\n",
552            "          Read and import a LiNo file into the database\n",
553            "      --out <OUT>, --lino-output <OUT>, --export <OUT>\n",
554            "          Write the complete database as a LiNo file\n",
555            "      --import-binary <PATH>, --binary-input <PATH>, --binary-in <PATH>\n",
556            "          Read and import a store archive in binary links notation\n",
557            "      --export-binary <PATH>, --binary-output <PATH>, --binary-out <PATH>\n",
558            "          Write the complete database, names included, as a store archive in\n",
559            "          binary links notation\n",
560            "      --always\n",
561            "          Store the query as an always-on persistent transformation trigger\n",
562            "      --once\n",
563            "          Store the query as a persistent transformation trigger that deletes\n",
564            "          itself after it fires\n",
565            "      --never\n",
566            "          Remove stored persistent transformation triggers matching the query\n",
567            "      --triggers\n",
568            "          Enable persistent transformation triggers for this command\n",
569            "      --triggers-file <FILE>\n",
570            "          Path to the persistent transformation trigger links database\n",
571            "          (default: <db>.triggers.links)\n",
572            "      --embed-triggers\n",
573            "          Store persistent transformation triggers directly in the main links\n",
574            "          database\n",
575            "      --transactions\n",
576            "          Enable the transactions layer (default log path: <db>.transitions.links)\n",
577            "      --transactions-file <FILE>\n",
578            "          Path to the transitions log store (implies --transactions)\n",
579            "      --commit-mode <MODE>\n",
580            "          Choose 'sync' or 'async' commits (default: sync, implies --transactions)\n",
581            "      --retention <SPEC>\n",
582            "          Log retention policy: 'infinite', 'sized:<n>', or 'chunked:<n>:<dir>'\n",
583            "          (implies --transactions)\n",
584            "      --vc\n",
585            "          Enable the version-control decorator (implies --transactions)\n",
586            "      --vc-file <FILE>\n",
587            "          Path to the version-control branches store\n",
588            "          (default: <db>.versioncontrol.links)\n",
589            "      --branch <NAME>\n",
590            "          Switch to a branch (creating it if --branch-from is also passed).\n",
591            "          Implies --vc.\n",
592            "      --branch-from <SEQ>\n",
593            "          When creating a branch with --branch, fork from this sequence point\n",
594            "      --checkout <POINT>\n",
595            "          Time-travel to a specific transition sequence or named tag.\n",
596            "          Implies --vc.\n",
597            "      --tag <NAME[=SEQ]>\n",
598            "          Create a tag at current head or at the given sequence point.\n",
599            "          Implies --vc.\n",
600            "      --list-branches\n",
601            "          List version-control branches and exit\n",
602            "      --list-tags\n",
603            "          List version-control tags and exit\n",
604            "      --log\n",
605            "          Print the transitions log and exit (implies --transactions)\n",
606            "      --serve <ADDR>\n",
607            "          Serve the database over TCP (e.g. 127.0.0.1:7878) until stopped;\n",
608            "          each message may use the text or the binary LiNo protocol\n",
609            "      --connect <ADDR>\n",
610            "          Send the query to a clink server instead of opening a database;\n",
611            "          an empty query reads every link\n",
612            "      --protocol <PROTOCOL>\n",
613            "          'text' or 'binary' for --connect (default: text); 'text', 'binary'\n",
614            "          or 'any' for --serve (default: any)\n",
615            "      --external-references\n",
616            "          Binary protocol: send numbers and characters as external references\n",
617            "      --arity <RANGE>\n",
618            "          Binary protocol: link lengths to use, 'n', 'min..max' or 'min..'\n",
619            "          (default: 2, doublets only; e.g. 2..3 adds triplets, 1.. any length)\n",
620            "      --packed-widths\n",
621            "          Binary protocol: give each section of links the narrowest reference\n",
622            "          width it needs instead of one width for the whole packet\n",
623            "      --permissions <RULES>\n",
624            "          Check every read and write against permission rules stored as links:\n",
625            "          'self' (rules in the data) or a links file of rules; without it,\n",
626            "          nothing is checked\n",
627            "      --subject <LINK>\n",
628            "          The subject (a link index or name) queries run as with --permissions,\n",
629            "          and the subject of --serve connections before (auth: token)\n",
630            "          (default: 0, a guest)\n",
631            "      --tokens <TOKENS>\n",
632            "          The token table of (auth: token) for --serve, --grant-token and\n",
633            "          --revoke-token: 'self' (tokens in the data) or a links file\n",
634            "      --grant-token <TOKEN>\n",
635            "          Let a token authenticate as --subject in the --tokens table, then exit\n",
636            "      --revoke-token <TOKEN>\n",
637            "          Forget a token of the --tokens table, then exit\n",
638            "      --token <TOKEN>\n",
639            "          With --connect: authenticate with (auth: token) before sending the query\n",
640            "  -h, --help\n",
641            "          Print help\n",
642            "  -V, --version\n",
643            "          Print version\n",
644        )
645    }
646
647    pub fn version_text() -> String {
648        format!("clink {}", env!("CARGO_PKG_VERSION"))
649    }
650}
651
652fn parse_arity(value: &str) -> Result<ArityRange> {
653    value
654        .trim()
655        .parse()
656        .map_err(|error| anyhow::anyhow!("invalid value for '--arity': {error}"))
657}
658
659fn inline_value<'a>(arg: &'a str, names: &[&str]) -> Option<&'a str> {
660    names.iter().find_map(|name| {
661        arg.strip_prefix(name)
662            .and_then(|rest| rest.strip_prefix('='))
663    })
664}
665
666fn next_value<I>(args: &mut I, option: &str) -> Result<String>
667where
668    I: Iterator<Item = String>,
669{
670    args.next()
671        .ok_or_else(|| anyhow::anyhow!("missing value for option '{option}'"))
672}
673
674fn next_bool_value<I>(args: &mut std::iter::Peekable<I>, default: bool) -> Result<bool>
675where
676    I: Iterator<Item = String>,
677{
678    if let Some(value) = args.peek().and_then(|value| bool_literal(value)) {
679        args.next();
680        Ok(value)
681    } else {
682        Ok(default)
683    }
684}
685
686fn parse_bool(option: &str, value: &str) -> Result<bool> {
687    bool_literal(value)
688        .ok_or_else(|| anyhow::anyhow!("invalid boolean value '{value}' for {option}"))
689}
690
691fn bool_literal(value: &str) -> Option<bool> {
692    match value.to_ascii_lowercase().as_str() {
693        "true" | "1" | "yes" | "on" => Some(true),
694        "false" | "0" | "no" | "off" => Some(false),
695        _ => None,
696    }
697}
698
699fn parse_link_id(option: &str, value: &str) -> Result<u32> {
700    value
701        .parse()
702        .map_err(|_| anyhow::anyhow!("invalid link id '{value}' for {option}"))
703}
704
705fn parse_seq(option: &str, value: &str) -> Result<i64> {
706    value
707        .parse()
708        .map_err(|_| anyhow::anyhow!("invalid sequence value '{value}' for {option}"))
709}
710
711fn set_positional_query(cli: &mut Cli, value: String) -> Result<()> {
712    if cli.query_arg.is_some() {
713        bail!("unexpected extra positional argument '{value}'");
714    }
715
716    cli.query_arg = Some(value);
717    Ok(())
718}