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