profflag.bend

cswap-bend-cli@0.1.0.0 · 76 lines · 13 definitions

1import Base
2
3# `--profile NAME` (or `--profile=NAME`) taken off a command line, for
4# `cswap switch` (src/main.bend) and `cswap auto` (src/daemon/entry.bend).
5
6# What is left of the words after `switch` once `--profile NAME` (or
7# `--profile=NAME`) is taken off, the name, and a usage error if the flag had
8# no value. `pending`: the last word was `--profile`.
9type Split is Data:
10  Split{rest: List<&2, String>, over: Maybe<&2, String>, err: String, pending: Bool}
11
12def split.with_over(+h: String, +s: Split) -> Split:
13  match s:
14    case Split{rest, over, err, p}:
15      Split{rest, Some{h}, err, False{}}
16
17def split.set_pending(+s: Split) -> Split:
18  match s:
19    case Split{rest, over, err, p}:
20      Split{rest, over, err, True{}}
21
22def split.keep(+h: String, +s: Split) -> Split:
23  match s:
24    case Split{rest, over, err, p}:
25      Split{h <> rest, over, err, False{}}
26
27def split.eq_form(+is_eq: Bool, +h: String, +s: Split) -> Split:
28  match is_eq:
29    case True{}:
30      split.with_over(String.drop(h, 10n), s)
31    case False{}:
32      split.keep(h, s)
33
34def split.flag(+is_flag: Bool, +is_eq: Bool, +h: String, +s: Split) -> Split:
35  match is_flag:
36    case True{}:
37      split.set_pending(s)
38    case False{}:
39      split.eq_form(is_eq, h, s)
40
41def split.step2(+pending: Bool, +is_flag: Bool, +is_eq: Bool, +h: String, +s: Split) -> Split:
42  match pending:
43    case True{}:
44      split.with_over(h, s)
45    case False{}:
46      split.flag(is_flag, is_eq, h, s)
47
48def split.pending(+s: Split) -> Bool:
49  match s:
50    case Split{rest, over, err, pending}:
51      pending
52
53def split.step(+h: String, +s: Split) -> Split:
54  split.step2(split.pending(s), String.eq(h, "--profile"), String.starts_with(h, "--profile="), h, s)
55
56def split.go(+args: List<&2, String>, +s: Split) -> Split:
57  match args:
58    case Nil{}:
59      s
60    case Con{h, t}:
61      split.go(t, split.step(h, s))
62
63def split.end2(+pending: Bool, +rest: List<&2, String>, +over: Maybe<&2, String>, +err: String) -> Split:
64  match pending:
65    case True{}:
66      Split{List.reverse(&2, String, rest), over, "argument --profile: expected one argument", False{}}
67    case False{}:
68      Split{List.reverse(&2, String, rest), over, err, False{}}
69
70def split.end(+s: Split) -> Split:
71  match s:
72    case Split{rest, over, err, pending}:
73      split.end2(pending, rest, over, err)
74
75def split(+args: List<&2, String>) -> Split:
76  split.end(split.go(args, Split{[], None{}, "", False{}}))