Skip to main content

link_cli/
cli.rs

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