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    /// The first `--serve` endpoint, such as `127.0.0.1:7878` or
46    /// `unix:/tmp/links.sock` (issue #140).
47    pub serve: Option<String>,
48    /// Every later `--serve` endpoint: one server listens on all of them.
49    pub serve_also: Vec<String>,
50    /// `--forward`: relay each `--serve` connection to this endpoint, byte
51    /// for byte, instead of serving a database (issue #140).
52    pub forward: Option<String>,
53    /// `--graphql`: `--serve` speaks Hasura's GraphQL for Deep (issue #153).
54    pub graphql: bool,
55    /// `--jwt-secret`: signs the tokens of `--graphql`; random when absent.
56    pub jwt_secret: Option<String>,
57    /// `--graphql-admin-secret`: what `x-hasura-admin-secret` must be.
58    pub graphql_admin_secret: Option<String>,
59    /// `--deep-package`: Deep links, as JSON rows, to load before serving.
60    pub deep_packages: Vec<String>,
61    pub connect: Option<String>,
62    pub protocol: Option<String>,
63    pub external_references: bool,
64    pub arity: ArityRange,
65    pub packed_widths: bool,
66    /// `--triplets`: `--serve` reads every request as triplets (issue #152).
67    pub triplets: bool,
68    /// `--permissions`: `self` or a links file of permission rules (issue #149).
69    pub permissions: Option<String>,
70    /// `--subject`: the link index or name queries run as.
71    pub subject: Option<String>,
72    /// `--tokens`: `self` or a links file of the token table.
73    pub tokens: Option<String>,
74    pub grant_token: Option<String>,
75    pub revoke_token: Option<String>,
76    /// `--token`: authenticates a `--connect` client.
77    pub token: Option<String>,
78    /// `--lock` (`--no-lock` is `none`), `--lock-timeout` and `--lock-status`;
79    /// see [`crate::store_lock`].
80    pub lock: Option<String>,
81    pub lock_timeout: Option<String>,
82    pub lock_status: bool,
83}
84
85impl Default for Cli {
86    fn default() -> Self {
87        Self {
88            db: DEFAULT_DATABASE_FILENAME.to_string(),
89            query: None,
90            query_arg: None,
91            trace: false,
92            indexed_lookups: false,
93            auto_create_missing_references: false,
94            structure: None,
95            before: false,
96            changes: false,
97            after: false,
98            lino_input: None,
99            lino_output: None,
100            binary_input: None,
101            binary_output: None,
102            always: false,
103            once: false,
104            never: false,
105            triggers: false,
106            triggers_file: None,
107            embed_triggers: false,
108            transactions: false,
109            transactions_file: None,
110            commit_mode: None,
111            retention: None,
112            vc: false,
113            vc_file: None,
114            branch: None,
115            branch_from: None,
116            checkout: None,
117            tag: None,
118            list_branches: false,
119            list_tags: false,
120            show_log: false,
121            serve: None,
122            serve_also: Vec::new(),
123            forward: None,
124            graphql: false,
125            jwt_secret: None,
126            graphql_admin_secret: None,
127            deep_packages: Vec::new(),
128            connect: None,
129            protocol: None,
130            external_references: false,
131            arity: ArityRange::DOUBLETS,
132            packed_widths: false,
133            triplets: false,
134            permissions: None,
135            subject: None,
136            tokens: None,
137            grant_token: None,
138            revoke_token: None,
139            token: None,
140            lock: None,
141            lock_timeout: None,
142            lock_status: false,
143        }
144    }
145}
146
147#[derive(Debug, Clone, PartialEq, Eq)]
148pub enum CliCommand {
149    Run(Box<Cli>),
150    Help,
151    Version,
152}
153
154impl Cli {
155    /// True when any flag in the transactions decorator family was passed.
156    pub fn transactions_requested(&self) -> bool {
157        self.transactions
158            || self.transactions_file.is_some()
159            || self.commit_mode.is_some()
160            || self.retention.is_some()
161            || self.show_log
162            || self.vc_requested()
163    }
164
165    /// True when a trigger command — `--always`, `--once` or `--never` — was
166    /// passed. Exactly one of them may be used at a time.
167    pub fn trigger_command_count(&self) -> usize {
168        usize::from(self.always) + usize::from(self.once) + usize::from(self.never)
169    }
170
171    /// True when any flag in the persistent transformation family was passed.
172    ///
173    /// Mirrors `persistentTransformationsEnabled` in the C# tool, minus the
174    /// "the triggers file already exists" clause, which needs the resolved
175    /// path and therefore lives next to it in `main`.
176    pub fn persistent_transformations_requested(&self) -> bool {
177        self.always
178            || self.once
179            || self.never
180            || self.triggers
181            || self.embed_triggers
182            || self.triggers_file.is_some()
183    }
184
185    /// Every `--serve` endpoint, in the order given.
186    pub fn serve_endpoints(&self) -> Vec<&str> {
187        self.serve
188            .iter()
189            .chain(&self.serve_also)
190            .map(String::as_str)
191            .collect()
192    }
193
194    fn add_serve(&mut self, endpoint: String) {
195        if self.serve.is_none() {
196            self.serve = Some(endpoint);
197        } else {
198            self.serve_also.push(endpoint);
199        }
200    }
201
202    /// True when any flag in the version-control decorator family was passed.
203    pub fn vc_requested(&self) -> bool {
204        self.vc
205            || self.vc_file.is_some()
206            || self.branch.is_some()
207            || self.branch_from.is_some()
208            || self.checkout.is_some()
209            || self.tag.is_some()
210            || self.list_branches
211            || self.list_tags
212    }
213
214    pub fn parse() -> Result<CliCommand> {
215        lino_arguments::init();
216        Self::parse_from(env::args_os())
217    }
218
219    pub fn parse_from<I, T>(args: I) -> Result<CliCommand>
220    where
221        I: IntoIterator<Item = T>,
222        T: Into<OsString>,
223    {
224        let mut cli = Cli::default();
225        let mut args = args
226            .into_iter()
227            .map(|arg| arg.into().to_string_lossy().into_owned())
228            .peekable();
229
230        let _program = args.next();
231
232        while let Some(arg) = args.next() {
233            if let Some(value) = inline_value(&arg, &["--db", "--data-source", "--data"]) {
234                cli.db = value.to_string();
235                continue;
236            }
237            if let Some(value) = inline_value(&arg, &["--query", "--apply", "--do"]) {
238                cli.query = Some(value.to_string());
239                continue;
240            }
241            if let Some(value) = inline_value(&arg, &["--structure"]) {
242                cli.structure = Some(parse_link_id("--structure", value)?);
243                continue;
244            }
245            if let Some(value) = inline_value(&arg, &["--indexed-lookups"]) {
246                cli.indexed_lookups = parse_bool("--indexed-lookups", value)?;
247                continue;
248            }
249            if let Some(value) = inline_value(&arg, &["--trace"]) {
250                cli.trace = parse_bool("--trace", value)?;
251                continue;
252            }
253            if let Some(value) = inline_value(&arg, &["--auto-create-missing-references"]) {
254                cli.auto_create_missing_references =
255                    parse_bool("--auto-create-missing-references", value)?;
256                continue;
257            }
258            if let Some(value) = inline_value(&arg, &["--before"]) {
259                cli.before = parse_bool("--before", value)?;
260                continue;
261            }
262            if let Some(value) = inline_value(&arg, &["--changes"]) {
263                cli.changes = parse_bool("--changes", value)?;
264                continue;
265            }
266            if let Some(value) = inline_value(&arg, &["--after", "--links"]) {
267                cli.after = parse_bool("--after", value)?;
268                continue;
269            }
270            if let Some(value) = inline_value(&arg, &["--out", "--lino-output", "--export"]) {
271                cli.lino_output = Some(value.to_string());
272                continue;
273            }
274            if let Some(value) = inline_value(&arg, &["--in", "--lino-input", "--import"]) {
275                cli.lino_input = Some(value.to_string());
276                continue;
277            }
278            if let Some(value) = inline_value(
279                &arg,
280                &["--export-binary", "--binary-output", "--binary-out"],
281            ) {
282                cli.binary_output = Some(value.to_string());
283                continue;
284            }
285            if let Some(value) =
286                inline_value(&arg, &["--import-binary", "--binary-input", "--binary-in"])
287            {
288                cli.binary_input = Some(value.to_string());
289                continue;
290            }
291            if let Some(value) = inline_value(&arg, &["--always"]) {
292                cli.always = parse_bool("--always", value)?;
293                continue;
294            }
295            if let Some(value) = inline_value(&arg, &["--once"]) {
296                cli.once = parse_bool("--once", value)?;
297                continue;
298            }
299            if let Some(value) = inline_value(&arg, &["--never"]) {
300                cli.never = parse_bool("--never", value)?;
301                continue;
302            }
303            if let Some(value) = inline_value(&arg, &["--triggers"]) {
304                cli.triggers = parse_bool("--triggers", value)?;
305                continue;
306            }
307            if let Some(value) = inline_value(&arg, &["--triggers-file"]) {
308                cli.triggers_file = Some(value.to_string());
309                continue;
310            }
311            if let Some(value) = inline_value(&arg, &["--embed-triggers"]) {
312                cli.embed_triggers = parse_bool("--embed-triggers", value)?;
313                continue;
314            }
315            if let Some(value) = inline_value(&arg, &["--transactions"]) {
316                cli.transactions = parse_bool("--transactions", value)?;
317                continue;
318            }
319            if let Some(value) = inline_value(&arg, &["--transactions-file"]) {
320                cli.transactions_file = Some(value.to_string());
321                continue;
322            }
323            if let Some(value) = inline_value(&arg, &["--commit-mode"]) {
324                cli.commit_mode = Some(value.to_string());
325                continue;
326            }
327            if let Some(value) = inline_value(&arg, &["--retention"]) {
328                cli.retention = Some(value.to_string());
329                continue;
330            }
331            if let Some(value) = inline_value(&arg, &["--vc"]) {
332                cli.vc = parse_bool("--vc", value)?;
333                continue;
334            }
335            if let Some(value) = inline_value(&arg, &["--vc-file"]) {
336                cli.vc_file = Some(value.to_string());
337                continue;
338            }
339            if let Some(value) = inline_value(&arg, &["--branch"]) {
340                cli.branch = Some(value.to_string());
341                continue;
342            }
343            if let Some(value) = inline_value(&arg, &["--branch-from"]) {
344                cli.branch_from = Some(parse_seq("--branch-from", value)?);
345                continue;
346            }
347            if let Some(value) = inline_value(&arg, &["--checkout"]) {
348                cli.checkout = Some(value.to_string());
349                continue;
350            }
351            if let Some(value) = inline_value(&arg, &["--tag"]) {
352                cli.tag = Some(value.to_string());
353                continue;
354            }
355            if let Some(value) = inline_value(&arg, &["--list-branches"]) {
356                cli.list_branches = parse_bool("--list-branches", value)?;
357                continue;
358            }
359            if let Some(value) = inline_value(&arg, &["--list-tags"]) {
360                cli.list_tags = parse_bool("--list-tags", value)?;
361                continue;
362            }
363            if let Some(value) = inline_value(&arg, &["--log"]) {
364                cli.show_log = parse_bool("--log", value)?;
365                continue;
366            }
367            if let Some(value) = inline_value(&arg, &["--jwt-secret"]) {
368                cli.jwt_secret = Some(value.to_string());
369                continue;
370            }
371            if let Some(value) = inline_value(&arg, &["--graphql-admin-secret"]) {
372                cli.graphql_admin_secret = Some(value.to_string());
373                continue;
374            }
375            if let Some(value) = inline_value(&arg, &["--deep-package"]) {
376                cli.deep_packages.push(value.to_string());
377                continue;
378            }
379            if let Some(value) = inline_value(&arg, &["--serve"]) {
380                cli.add_serve(value.to_string());
381                continue;
382            }
383            if let Some(value) = inline_value(&arg, &["--forward"]) {
384                cli.forward = Some(value.to_string());
385                continue;
386            }
387            if let Some(value) = inline_value(&arg, &["--connect"]) {
388                cli.connect = Some(value.to_string());
389                continue;
390            }
391            if let Some(value) = inline_value(&arg, &["--protocol"]) {
392                cli.protocol = Some(value.to_string());
393                continue;
394            }
395            if let Some(value) = inline_value(&arg, &["--external-references"]) {
396                cli.external_references = parse_bool("--external-references", value)?;
397                continue;
398            }
399            if let Some(value) = inline_value(&arg, &["--arity"]) {
400                cli.arity = parse_arity(value)?;
401                continue;
402            }
403            if let Some(value) = inline_value(&arg, &["--packed-widths"]) {
404                cli.packed_widths = parse_bool("--packed-widths", value)?;
405                continue;
406            }
407            if let Some(value) = inline_value(&arg, &["--triplets"]) {
408                cli.triplets = parse_bool("--triplets", value)?;
409                continue;
410            }
411            if let Some(value) = inline_value(&arg, &["--permissions"]) {
412                cli.permissions = Some(value.to_string());
413                continue;
414            }
415            if let Some(value) = inline_value(&arg, &["--subject"]) {
416                cli.subject = Some(value.to_string());
417                continue;
418            }
419            if let Some(value) = inline_value(&arg, &["--tokens"]) {
420                cli.tokens = Some(value.to_string());
421                continue;
422            }
423            if let Some(value) = inline_value(&arg, &["--grant-token"]) {
424                cli.grant_token = Some(value.to_string());
425                continue;
426            }
427            if let Some(value) = inline_value(&arg, &["--revoke-token"]) {
428                cli.revoke_token = Some(value.to_string());
429                continue;
430            }
431            if let Some(value) = inline_value(&arg, &["--lock"]) {
432                cli.lock = Some(value.to_string());
433                continue;
434            }
435            if let Some(value) = inline_value(&arg, &["--lock-timeout"]) {
436                cli.lock_timeout = Some(value.to_string());
437                continue;
438            }
439            if let Some(value) = inline_value(&arg, &["--lock-status"]) {
440                cli.lock_status = parse_bool("--lock-status", value)?;
441                continue;
442            }
443            if let Some(value) = inline_value(&arg, &["--token"]) {
444                cli.token = Some(value.to_string());
445                continue;
446            }
447
448            match arg.as_str() {
449                "-h" | "--help" => return Ok(CliCommand::Help),
450                "-V" | "--version" => return Ok(CliCommand::Version),
451                "-d" | "--db" | "--data-source" | "--data" => {
452                    cli.db = next_value(&mut args, &arg)?;
453                }
454                "-q" | "--query" | "--apply" | "--do" => {
455                    cli.query = Some(next_value(&mut args, &arg)?);
456                }
457                "--indexed-lookups" => {
458                    cli.indexed_lookups = next_bool_value(&mut args, true)?;
459                }
460                "-t" | "--trace" => {
461                    cli.trace = next_bool_value(&mut args, true)?;
462                }
463                "--auto-create-missing-references" => {
464                    cli.auto_create_missing_references = next_bool_value(&mut args, true)?;
465                }
466                "-s" | "--structure" => {
467                    let value = next_value(&mut args, &arg)?;
468                    cli.structure = Some(parse_link_id(&arg, &value)?);
469                }
470                "-b" | "--before" => {
471                    cli.before = next_bool_value(&mut args, true)?;
472                }
473                "-c" | "--changes" => {
474                    cli.changes = next_bool_value(&mut args, true)?;
475                }
476                "-a" | "--after" | "--links" => {
477                    cli.after = next_bool_value(&mut args, true)?;
478                }
479                "--out" | "--lino-output" | "--export" => {
480                    cli.lino_output = Some(next_value(&mut args, &arg)?);
481                }
482                "--in" | "--lino-input" | "--import" => {
483                    cli.lino_input = Some(next_value(&mut args, &arg)?);
484                }
485                "--export-binary" | "--binary-output" | "--binary-out" => {
486                    cli.binary_output = Some(next_value(&mut args, &arg)?);
487                }
488                "--import-binary" | "--binary-input" | "--binary-in" => {
489                    cli.binary_input = Some(next_value(&mut args, &arg)?);
490                }
491                "--always" => {
492                    cli.always = next_bool_value(&mut args, true)?;
493                }
494                "--once" => {
495                    cli.once = next_bool_value(&mut args, true)?;
496                }
497                "--never" => {
498                    cli.never = next_bool_value(&mut args, true)?;
499                }
500                "--triggers" => {
501                    cli.triggers = next_bool_value(&mut args, true)?;
502                }
503                "--triggers-file" => {
504                    cli.triggers_file = Some(next_value(&mut args, &arg)?);
505                }
506                "--embed-triggers" => {
507                    cli.embed_triggers = next_bool_value(&mut args, true)?;
508                }
509                "--transactions" => {
510                    cli.transactions = next_bool_value(&mut args, true)?;
511                }
512                "--transactions-file" => {
513                    cli.transactions_file = Some(next_value(&mut args, &arg)?);
514                }
515                "--commit-mode" => {
516                    cli.commit_mode = Some(next_value(&mut args, &arg)?);
517                }
518                "--retention" => {
519                    cli.retention = Some(next_value(&mut args, &arg)?);
520                }
521                "--vc" => {
522                    cli.vc = next_bool_value(&mut args, true)?;
523                }
524                "--vc-file" => {
525                    cli.vc_file = Some(next_value(&mut args, &arg)?);
526                }
527                "--branch" => {
528                    cli.branch = Some(next_value(&mut args, &arg)?);
529                }
530                "--branch-from" => {
531                    let value = next_value(&mut args, &arg)?;
532                    cli.branch_from = Some(parse_seq(&arg, &value)?);
533                }
534                "--checkout" => {
535                    cli.checkout = Some(next_value(&mut args, &arg)?);
536                }
537                "--tag" => {
538                    cli.tag = Some(next_value(&mut args, &arg)?);
539                }
540                "--list-branches" => {
541                    cli.list_branches = next_bool_value(&mut args, true)?;
542                }
543                "--list-tags" => {
544                    cli.list_tags = next_bool_value(&mut args, true)?;
545                }
546                "--log" => {
547                    cli.show_log = next_bool_value(&mut args, true)?;
548                }
549                "--graphql" => {
550                    cli.graphql = next_bool_value(&mut args, true)?;
551                }
552                "--jwt-secret" => {
553                    cli.jwt_secret = Some(next_value(&mut args, &arg)?);
554                }
555                "--graphql-admin-secret" => {
556                    cli.graphql_admin_secret = Some(next_value(&mut args, &arg)?);
557                }
558                "--deep-package" => {
559                    cli.deep_packages.push(next_value(&mut args, &arg)?);
560                }
561                "--serve" => {
562                    let value = next_value(&mut args, &arg)?;
563                    cli.add_serve(value);
564                }
565                "--forward" => {
566                    cli.forward = Some(next_value(&mut args, &arg)?);
567                }
568                "--connect" => {
569                    cli.connect = Some(next_value(&mut args, &arg)?);
570                }
571                "--protocol" => {
572                    cli.protocol = Some(next_value(&mut args, &arg)?);
573                }
574                "--external-references" => {
575                    cli.external_references = next_bool_value(&mut args, true)?;
576                }
577                "--arity" => {
578                    cli.arity = parse_arity(&next_value(&mut args, &arg)?)?;
579                }
580                "--packed-widths" => {
581                    cli.packed_widths = next_bool_value(&mut args, true)?;
582                }
583                "--triplets" => {
584                    cli.triplets = next_bool_value(&mut args, true)?;
585                }
586                "--permissions" => {
587                    cli.permissions = Some(next_value(&mut args, &arg)?);
588                }
589                "--subject" => {
590                    cli.subject = Some(next_value(&mut args, &arg)?);
591                }
592                "--tokens" => {
593                    cli.tokens = Some(next_value(&mut args, &arg)?);
594                }
595                "--grant-token" => {
596                    cli.grant_token = Some(next_value(&mut args, &arg)?);
597                }
598                "--revoke-token" => {
599                    cli.revoke_token = Some(next_value(&mut args, &arg)?);
600                }
601                "--token" => {
602                    cli.token = Some(next_value(&mut args, &arg)?);
603                }
604                "--lock" => cli.lock = Some(next_value(&mut args, &arg)?),
605                "--no-lock" => cli.lock = Some("none".into()),
606                "--lock-timeout" => cli.lock_timeout = Some(next_value(&mut args, &arg)?),
607                "--lock-status" => cli.lock_status = next_bool_value(&mut args, true)?,
608                "--" => {
609                    for value in args.by_ref() {
610                        set_positional_query(&mut cli, value)?;
611                    }
612                    break;
613                }
614                value if value.starts_with('-') => {
615                    bail!("unknown option '{value}'");
616                }
617                value => {
618                    set_positional_query(&mut cli, value.to_string())?;
619                }
620            }
621        }
622
623        Ok(CliCommand::Run(Box::new(cli)))
624    }
625
626    pub fn print_help() {
627        print!("{}", Self::help_text());
628    }
629
630    pub fn help_text() -> &'static str {
631        concat!(
632            "LiNo CLI Tool for managing links data store\n\n",
633            "Usage: clink [OPTIONS] [QUERY]\n\n",
634            "Arguments:\n",
635            "  [QUERY]  LiNo query for CRUD operation\n\n",
636            "Options:\n",
637            "  -d, --db <DB>, --data-source <DB>, --data <DB>\n",
638            "          Path to the links database file [default: db.links]\n",
639            "  -q, --query <QUERY>, --apply <QUERY>, --do <QUERY>\n",
640            "          LiNo query for CRUD operation\n",
641            "      --indexed-lookups\n",
642            "          Use optional lookup-index decorators for local links and names (Rust only)\n",
643            "  -t, --trace\n",
644            "          Enable trace (verbose output), including each transport event of\n",
645            "          --serve, --connect and --forward (as CLINK_IPC_TRACE=1 does)\n",
646            "      --auto-create-missing-references\n",
647            "          Create missing numeric and named references as self-referential point links\n",
648            "  -s, --structure <STRUCTURE>\n",
649            "          ID of the link to format its structure\n",
650            "  -b, --before\n",
651            "          Print the state of the database before applying changes\n",
652            "  -c, --changes\n",
653            "          Print the changes applied by the query\n",
654            "  -a, --after, --links\n",
655            "          Print the state of the database after applying changes\n",
656            "      --in <IN>, --lino-input <IN>, --import <IN>\n",
657            "          Read and import a LiNo file into the database\n",
658            "      --out <OUT>, --lino-output <OUT>, --export <OUT>\n",
659            "          Write the complete database as a LiNo file\n",
660            "      --import-binary <PATH>, --binary-input <PATH>, --binary-in <PATH>\n",
661            "          Read and import a store archive in binary links notation\n",
662            "      --export-binary <PATH>, --binary-output <PATH>, --binary-out <PATH>\n",
663            "          Write the complete database, names included, as a store archive in\n",
664            "          binary links notation\n",
665            "      --always\n",
666            "          Store the query as an always-on persistent transformation trigger\n",
667            "      --once\n",
668            "          Store the query as a persistent transformation trigger that deletes\n",
669            "          itself after it fires\n",
670            "      --never\n",
671            "          Remove stored persistent transformation triggers matching the query\n",
672            "      --triggers\n",
673            "          Enable persistent transformation triggers for this command\n",
674            "      --triggers-file <FILE>\n",
675            "          Path to the persistent transformation trigger links database\n",
676            "          (default: <db>.triggers.links)\n",
677            "      --embed-triggers\n",
678            "          Store persistent transformation triggers directly in the main links\n",
679            "          database\n",
680            "      --transactions\n",
681            "          Enable the transactions layer (default log path: <db>.transitions.log)\n",
682            "      --transactions-file <FILE>\n",
683            "          Path to the transitions log store (implies --transactions)\n",
684            "      --commit-mode <MODE>\n",
685            "          Choose 'sync' or 'async' commits (default: sync, implies --transactions)\n",
686            "      --retention <SPEC>\n",
687            "          Log retention policy: 'infinite', 'sized:<n>', or 'chunked:<n>:<dir>'\n",
688            "          (implies --transactions)\n",
689            "      --vc\n",
690            "          Enable the version-control decorator (implies --transactions)\n",
691            "      --vc-file <FILE>\n",
692            "          Path to the version-control branches store\n",
693            "          (default: <db>.versioncontrol.links)\n",
694            "      --branch <NAME>\n",
695            "          Switch to a branch (creating it if --branch-from is also passed).\n",
696            "          Implies --vc.\n",
697            "      --branch-from <SEQ>\n",
698            "          When creating a branch with --branch, fork from this sequence point\n",
699            "      --checkout <POINT>\n",
700            "          Time-travel to a specific transition sequence or named tag.\n",
701            "          Implies --vc.\n",
702            "      --tag <NAME[=POINT]>\n",
703            "          Create a tag at current head or at a sequence/existing tag.\n",
704            "          Uses the first '=' whose complete suffix resolves.\n",
705            "          Implies --vc.\n",
706            "      --list-branches\n",
707            "          List version-control branches and exit\n",
708            "      --list-tags\n",
709            "          List version-control tags and exit\n",
710            "      --log\n",
711            "          Print the transitions log and exit (implies --transactions)\n",
712            "      --serve <ADDR>\n",
713            "          Serve the database on an endpoint until stopped: a TCP address\n",
714            "          (e.g. 127.0.0.1:7878) or KIND:ADDRESS for another transport, such as\n",
715            "          unix:/tmp/links.sock, pipe:NAME, fifo:DIR, shm:DIR, mmap:DIR, file:DIR,\n",
716            "          signal:DIR, mq:DIR, sysvmq:DIR, udp:HOST:PORT, stdio, mailslot:DIR,\n",
717            "          copydata:DIR or alpc:DIR (see docs/protocol/ipc-transports-v1.md);\n",
718            "          repeat it to serve one store on several endpoints at once. Each\n",
719            "          message may use the text or the binary LiNo protocol\n",
720            "      --forward <ADDR>\n",
721            "          With --serve: relay every connection, byte for byte, to this\n",
722            "          endpoint instead of serving a database (stacks transports)\n",
723            "      --graphql\n",
724            "          With --serve: speak Hasura's GraphQL over HTTP and WebSocket for Deep\n",
725            "      --jwt-secret <SECRET>\n",
726            "          Signs the tokens of --graphql (default: random for each run)\n",
727            "      --graphql-admin-secret <SECRET>\n",
728            "          The x-hasura-admin-secret that bypasses --permissions in --graphql\n",
729            "      --deep-package <FILE>\n",
730            "          Load a Deep package (JSON rows of links) before --graphql serves\n",
731            "      --connect <ADDR>\n",
732            "          Send the query to a clink server on a --serve endpoint (e.g.\n",
733            "          127.0.0.1:7878 or shm:/tmp/links) instead of opening a database;\n",
734            "          an empty query reads every link\n",
735            "      --protocol <PROTOCOL>\n",
736            "          'text' or 'binary' for --connect (default: text); 'text', 'binary'\n",
737            "          or 'any' for --serve (default: any)\n",
738            "      --external-references\n",
739            "          Binary protocol: send numbers and characters as external references\n",
740            "      --arity <RANGE>\n",
741            "          Binary protocol: link lengths to use, 'n', 'min..max' or 'min..'\n",
742            "          (default: 2, doublets only; e.g. 2..3 adds triplets, 1.. any length)\n",
743            "      --packed-widths\n",
744            "          Binary protocol: give each section of links the narrowest reference\n",
745            "          width it needs instead of one width for the whole packet\n",
746            "      --triplets\n",
747            "          With --serve: read every request as triplets, (create: (type from to)),\n",
748            "          (each: (index type from to)) and three-part substitutions, over this\n",
749            "          store of doublets; without it, every request is about doublets\n",
750            "      --permissions <RULES>\n",
751            "          Check every read and write against permission rules stored as links:\n",
752            "          'self' (rules in the data) or a links file of rules; without it,\n",
753            "          nothing is checked\n",
754            "      --subject <LINK>\n",
755            "          The subject (a link index or name) queries run as with --permissions,\n",
756            "          and the subject of --serve connections before (auth: token)\n",
757            "          (default: 0, a guest)\n",
758            "      --tokens <TOKENS>\n",
759            "          The token table of (auth: token) for --serve, --grant-token and\n",
760            "          --revoke-token: 'self' (tokens in the data) or a links file\n",
761            "      --grant-token <TOKEN>\n",
762            "          Let a token authenticate as --subject in the --tokens table, then exit\n",
763            "      --revoke-token <TOKEN>\n",
764            "          Forget a token of the --tokens table, then exit\n",
765            "      --token <TOKEN>\n",
766            "          With --connect: authenticate with (auth: token) before sending the query\n",
767            "      --lock <MODE>\n",
768            "          How concurrent invocations on one store are serialized: 'flock'\n",
769            "          (default; an OS lock on <db>.lock, released when the holder exits),\n",
770            "          'pid' (the directory <db>.lock.d, broken once its owner process is\n",
771            "          gone) or 'none'. Writers lock exclusively, read-only runs share it\n",
772            "      --no-lock\n",
773            "          Same as --lock none, for callers that serialize access themselves\n",
774            "      --lock-timeout <MS>\n",
775            "          How long to wait for a locked store before failing with the name of\n",
776            "          its owner (default: 30000; 0 fails at once)\n",
777            "      --lock-status\n",
778            "          Print who holds the locks of the store, then exit\n",
779            "  -h, --help\n",
780            "          Print help\n",
781            "  -V, --version\n",
782            "          Print version\n",
783        )
784    }
785
786    pub fn version_text() -> String {
787        format!("clink {}", env!("CARGO_PKG_VERSION"))
788    }
789}
790
791fn parse_arity(value: &str) -> Result<ArityRange> {
792    value
793        .trim()
794        .parse()
795        .map_err(|error| anyhow::anyhow!("invalid value for '--arity': {error}"))
796}
797
798fn inline_value<'a>(arg: &'a str, names: &[&str]) -> Option<&'a str> {
799    names.iter().find_map(|name| {
800        arg.strip_prefix(name)
801            .and_then(|rest| rest.strip_prefix('='))
802    })
803}
804
805fn next_value<I>(args: &mut I, option: &str) -> Result<String>
806where
807    I: Iterator<Item = String>,
808{
809    args.next()
810        .ok_or_else(|| anyhow::anyhow!("missing value for option '{option}'"))
811}
812
813fn next_bool_value<I>(args: &mut std::iter::Peekable<I>, default: bool) -> Result<bool>
814where
815    I: Iterator<Item = String>,
816{
817    if let Some(value) = args.peek().and_then(|value| bool_literal(value)) {
818        args.next();
819        Ok(value)
820    } else {
821        Ok(default)
822    }
823}
824
825fn parse_bool(option: &str, value: &str) -> Result<bool> {
826    bool_literal(value)
827        .ok_or_else(|| anyhow::anyhow!("invalid boolean value '{value}' for {option}"))
828}
829
830fn bool_literal(value: &str) -> Option<bool> {
831    match value.to_ascii_lowercase().as_str() {
832        "true" | "1" | "yes" | "on" => Some(true),
833        "false" | "0" | "no" | "off" => Some(false),
834        _ => None,
835    }
836}
837
838fn parse_link_id(option: &str, value: &str) -> Result<u32> {
839    value
840        .parse()
841        .map_err(|_| anyhow::anyhow!("invalid link id '{value}' for {option}"))
842}
843
844fn parse_seq(option: &str, value: &str) -> Result<i64> {
845    value
846        .parse()
847        .map_err(|_| anyhow::anyhow!("invalid sequence value '{value}' for {option}"))
848}
849
850fn set_positional_query(cli: &mut Cli, value: String) -> Result<()> {
851    if cli.query_arg.is_some() {
852        bail!("unexpected extra positional argument '{value}'");
853    }
854
855    cli.query_arg = Some(value);
856    Ok(())
857}