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