OILS / _gen / bin / text_files.cc View on Github | oilshell.org

1508 lines, 136 significant
1
2#include "cpp/embedded_file.h"
3
4namespace embedded_file {
5GLOBAL_STR(gStr0, R"zZXx(
6 Errors
7 <a class="group-link" href="chap-errors.html">errors</a>
8
9
10 [UTF8] err-utf8-encode err-utf8-decode
11 [J8 String] err-j8-str-encode err-j8-str-decode
12 [J8 Lines] err-j8-lines-encode err-j8-lines-decode
13 [JSON] err-json-encode err-json-decode
14 [JSON8] err-json8-encode err-json8-decode
15)zZXx");
16
17GLOBAL_STR(gStr1, R"zZXx(
18
19 Front End <a class="group-link" href="chap-front-end.html">front-end</a>
20
21
22 [Lexing] ascii-whitespace [ \t\r\n]
23 ascii-control-chars
24)zZXx");
25
26GLOBAL_STR(gStr2, R"zZXx(
27 J8 Notation
28 <a class="group-link" href="chap-j8.html">j8</a>
29
30
31 [J8 Strings] json-string "hi"
32 json-escape \" \\ \u1234
33 surrogate-pair \ud83e\udd26
34 j8-escape \' \u{1f926} \yff
35 u-prefix u'hi'
36 b-prefix b'hi'
37 no-prefix 'hi'
38 [J8 Lines] unquoted-line
39 [JSON8] json8-num json8-str
40 X json8-list X json8-dict
41 json8-comment
42 [TSV8] column-attrs column-types
43)zZXx");
44
45GLOBAL_STR(gStr3, R"zZXx(Usage: help TOPIC?
46
47Examples:
48
49 help # this help
50 help echo # help on the 'echo' builtin
51 help command-sub # help on command sub $(date)
52
53 help oils-usage # identical to oils-for-unix --help
54 help osh-usage # osh --help
55 help ysh-usage # ysh --help
56)zZXx");
57
58GLOBAL_STR(gStr4, R"zZXx(bin/oils-for-unix is an executable that contains OSH, YSH, and more.
59
60Usage: oils-for-unix MAIN_NAME ARG*
61 MAIN_NAME ARG*
62
63It behaves like busybox. The command name can be passed as the first argument:
64
65 oils-for-unix ysh -c 'echo hi'
66
67More commonly, it's invoked through a symlink like 'ysh', which causes it to
68behave like that command:
69
70 ysh -c 'echo hi'
71)zZXx");
72
73GLOBAL_STR(gStr5, R"zZXx(
74 Builtin Commands <a class="group-link" href="chap-builtin-cmd.html">builtin-cmd</a>
75
76
77 [I/O] read echo printf
78 readarray mapfile
79 [Run Code] source . eval trap
80 [Set Options] set shopt
81 [Working Dir] cd pwd pushd popd dirs
82 [Completion] complete compgen compopt compadjust compexport
83 [Shell Process] exec X logout
84 umask ulimit times
85 [Child Process] jobs wait
86 fg X bg X kill X disown
87 [External] test [ getopts
88 [Introspection] help hash cmd/type X caller
89 [Word Lookup] command builtin
90 [Interactive] alias unalias history X fc X bind
91X [Unsupported] enable
92)zZXx");
93
94GLOBAL_STR(gStr6, R"zZXx(The reference is divided in to "chapters", each of which has its own table of
95contents. Type:
96
97 help osh-$CHAPTER
98
99Where $CHAPTER is one of:
100
101 front-end
102 command-lang
103 osh-assign
104 word-lang
105 mini-lang
106 builtin-cmd
107 option
108 special-var
109 plugin
110
111Example:
112
113 help osh-word-lang
114)zZXx");
115
116GLOBAL_STR(gStr7, R"zZXx(
117 Command Language <a class="group-link" href="chap-cmd-lang.html">cmd-lang</a>
118
119
120 [Commands] simple-command semicolon ;
121 [Conditional] case if dbracket [[
122 true false colon :
123 bang ! and && or ||
124 [Iteration] while until for for-expr-sh ((
125 [Control Flow] break continue return exit
126 [Grouping] sh-func sh-block { subshell (
127 [Concurrency] pipe | X pipe-amp |& ampersand &
128 [Redirects] redir-file > >> >| < <> not impl: &>
129 redir-desc >& <&
130 here-doc << <<- <<<
131 [Other Command] dparen (( time X coproc X select
132)zZXx");
133
134GLOBAL_STR(gStr8, R"zZXx(
135 Front End <a class="group-link" href="chap-front-end.html">front-end</a>
136
137
138 [Usage] oils-usage osh-usage config
139 startup line-editing exit-codes
140 [Lexing] comment # line-continuation \ ascii-whitespace [ \t\r\n]
141)zZXx");
142
143GLOBAL_STR(gStr9, R"zZXx(
144 Other Mini Languages <a class="group-link" href="chap-mini-lang.html">mini-lang</a>
145
146
147 [Arithmetic] arith-context Where legacy arithmetic is allowed
148 sh-numbers 0xFF 0755 etc.
149 sh-arith 1 + 2*3 a *= 2
150 sh-logical !a && b
151 sh-bitwise ~a ^ b
152 [Boolean] bool-expr [[ ! $x && $y || $z ]]
153 test ! $x -a $y -o $z
154 bool-infix $a -nt $b $x == $y
155 bool-path -d /etc
156 bool-str -n foo -z ''
157 bool-other -o errexit -v name[index]
158 [Patterns] glob-pat *.py
159 extglob ,(*.py|*.sh)
160 regex [[ foo =~ [a-z]+ ]]
161 [Other Sublang] braces {alice,bob}@example.com
162 histsub !$ !! !n
163 char-escapes \t \c \x00 \u03bc
164)zZXx");
165
166GLOBAL_STR(gStr10, R"zZXx(
167 Global Shell Options <a class="group-link" href="chap-option.html">option</a>
168
169
170 [Errors] nounset -u errexit -e inherit_errexit pipefail
171 [Globbing] noglob -f nullglob failglob X dotglob
172 dashglob (true)
173 [Debugging] xtrace X verbose X extdebug
174 [Interactive] emacs vi
175 [Other POSIX] X noclobber
176 [Compat] eval_unsafe_arith ignore_flags_not_impl
177)zZXx");
178
179GLOBAL_STR(gStr11, R"zZXx(
180 Assignments and Expressions <a class="group-link" href="chap-osh-assign.html">osh-assign</a>
181
182
183 [Literals] sh-array array=(a b c) array[1]=B "${a[@]}"
184 sh-assoc assoc=(['a']=1 ['b']=2) assoc['x']=b
185 [Operators] sh-assign str='xyz'
186 sh-append str+='abc'
187 [Builtins] local readonly export unset shift
188 declare typeset X let
189)zZXx");
190
191GLOBAL_STR(gStr12, R"zZXx(
192 Plugins and Hooks <a class="group-link" href="chap-plugin.html">plugin</a>
193
194
195 [Signals] SIGTERM SIGINT SIGQUIT
196 SIGTTIN SIGTTOU SIGWINCH
197 [Traps] DEBUG ERR EXIT X RETURN
198 [Words] PS1 X PS2 X PS3 PS4
199 [Completion] complete
200 [Other Plugin] PROMPT_COMMAND X command_not_found
201)zZXx");
202
203GLOBAL_STR(gStr13, R"zZXx(
204 Special Variables <a class="group-link" href="chap-special-var.html">special-var</a>
205
206
207 [POSIX Special] $@ $* $# $? $- $$ $! $0 $9
208 [Shell Vars] IFS X LANG X GLOBIGNORE
209 [Shell Options] SHELLOPTS X BASHOPTS
210 [Other Env] HOME PATH
211 [Other Special] BASH_REMATCH @PIPESTATUS
212 [Platform] HOSTNAME OSTYPE
213 [Call Stack] @BASH_SOURCE @FUNCNAME @BASH_LINENO
214 X @BASH_ARGV X @BASH_ARGC
215 [Tracing] LINENO
216 [Process State] UID EUID PPID X BASHPID
217X [Process Stack] BASH_SUBSHELL SHLVL
218X [Shell State] BASH_CMDS @DIRSTACK
219 [Completion] @COMP_WORDS COMP_CWORD COMP_LINE COMP_POINT
220 COMP_WORDBREAKS @COMPREPLY X COMP_KEY
221 X COMP_TYPE COMP_ARGV
222 [History] HISTFILE
223 [cd] PWD OLDPWD X CDPATH
224 [getopts] OPTIND OPTARG X OPTERR
225 [read] REPLY
226 [Functions] X RANDOM SECONDS
227)zZXx");
228
229GLOBAL_STR(gStr14, R"zZXx(
230 OSH Types <a class="group-link" href="chap-type-method.html">type-method</a>
231
232
233 [OSH] BashArray BashAssoc
234)zZXx");
235
236GLOBAL_STR(gStr15, R"zZXx(bin/osh is compatible with POSIX shell, bash, and other shells.
237
238Usage: osh FLAG* SCRIPT ARG*
239 osh FLAG* -c COMMAND ARG*
240 osh FLAG*
241
242The command line accepted by `bin/osh` is compatible with /bin/sh and bash.
243
244 osh -c 'echo hi'
245 osh myscript.sh
246 echo 'echo hi' | osh
247
248It also has a few enhancements:
249
250 osh -n -c 'hello' # pretty-print the AST
251 osh --ast-format text -n -c 'hello' # print it full
252
253osh accepts POSIX sh flags, with these additions:
254
255 -n parse the program but don't execute it. Print the AST.
256 --ast-format what format the AST should be in
257)zZXx");
258
259GLOBAL_STR(gStr16, R"zZXx(
260 Word Language <a class="group-link" href="chap-word-lang.html">word-lang</a>
261
262
263 [Quotes] osh-string 'abc' $'line\n' "$var"
264 [Substitutions] command-sub $(command) `command`
265 var-sub ${var} $0 $9
266 arith-sub $((1 + 2))
267 tilde-sub ~/src
268 proc-sub diff <(sort L.txt) <(sort R.txt)
269 [Var Ops] op-test ${x:-default}
270 op-strip ${x%%suffix} etc.
271 op-replace ${x//y/z}
272 op-index ${a[i+1}
273 op-slice ${a[@]:0:1}
274 op-format ${x@P}
275)zZXx");
276
277GLOBAL_STR(gStr17, R"zZXx(
278 Builtin Commands <a class="group-link" href="chap-builtin-cmd.html">builtin-cmd</a>
279
280
281 [Memory] cmd/append Add elements to end of array
282 pp asdl cell X gc-stats line proc
283 [Handle Errors] error error 'failed' (status=2)
284 try Run with errexit, set _error
285 failed Test if _error.code !== 0
286 boolstatus Enforce 0 or 1 exit status
287 [Shell State] ysh-cd ysh-shopt compatible, and takes a block
288 shvar Temporary modify global settings
289 ctx Share and update a temporary "context"
290 push-registers Save registers like $?, PIPESTATUS
291 [Modules] runproc Run a proc; use as main entry point
292 module guard against duplicate 'source'
293 is-main false when sourcing a file
294 use change first word lookup
295 [I/O] ysh-read flags --all, -0
296 ysh-echo no -e -n with simple_echo
297 write Like echo, with --, --sep, --end
298 fork forkwait Replace & and (), and takes a block
299 fopen Open multiple streams, takes a block
300 X dbg Only thing that can be used in funcs
301 X log X die Common functions (polyfill)
302 [Hay Config] hay haynode For DSLs and config files
303 [Completion] compadjust compexport
304 [Data Formats] json read write
305 json8 read write
306X [Lines] slurp-by combine adjacent lines into cells
307X [Awk] each-line --j8 --max-jobs (Str, Template, Block) - xargs
308 each-row --max-jobs (Str, Template, Block) - xargs
309 split-by (str=\n, ifs=':', pattern=/s+/)
310 if-split-by
311 chop alias for split-by (pattern=/s+/)
312 must-match (/ <capture d+> </capture w+> /)
313 if-match
314X [Table Create] table --by-row --by-col (&place); construct/parse a table
315 table/cols cols name age - cols name:Str age:Int
316 types type Str Int
317 attr attr units - secs
318 row emit row
319 table cat concatenate TSV8
320 table align to ssv8
321 table tabify to tsv8
322 table header (cols = :|name age|, types = :|Str Int|, units = :|- secs|)
323 table slice e.g. slice (1, -1) slice (5, 7)
324 table to-tsv lose type info, and error on \t in cells
325X [Table Ops] where subset of rows; dplyr filter()
326 pick subset of columns ('select' taken by shell)
327 mutate transmute [average = count / sum] - drop the ones that are used?
328 rename (bytes='bytes', path='filename')
329 group-by add a column with a group ID [ext]
330 sort-by sort by columns; dplyr arrange() [ext]
331 summary count, sum, histogram, any, all, reduce(), etc. [ext]
332 [Args Parser] parser Parse command line arguments
333 flag
334 arg
335 rest
336 parseArgs()
337X [Testing] describe Test harness
338 assert takes an expression
339)zZXx");
340
341GLOBAL_STR(gStr18, R"zZXx(
342 Builtin Functions <a class="group-link" href="chap-builtin-func.html">builtin-func</a>
343
344
345 [Values] len() func/type() X repeat()
346 [Conversions] bool() int() float() str() list() dict()
347 X runes() X encodeRunes()
348 X bytes() X encodeBytes()
349 [Str] X strcmp() X split() shSplit()
350 [List] join() any() all()
351 [Collections] X copy() X deepCopy()
352 [Word] glob() maybe()
353 [Math] abs() max() min() X round() sum()
354 [Serialize] toJson() fromJson()
355 toJson8() fromJson8()
356X [J8 Decode] J8.Bool() J8.Int() ...
357 [Pattern] _group() _start() _end()
358 [Introspection] shvarGet() getVar() evalExpr()
359 [Hay Config] parseHay() evalHay()
360X [Hashing] sha1dc() sha256()
361)zZXx");
362
363GLOBAL_STR(gStr19, R"zZXx(The reference is divided in to "chapters", each of which has its own table of
364contents. Type:
365
366 help ysh-$CHAPTER
367
368Where $CHAPTER is one of:
369
370 front-end
371 command-lang
372 expr-lang
373 word-lang
374 builtin-cmd
375 option
376 special-var
377 type-method
378 builtin-func
379
380Example:
381
382 help ysh-expr-lang
383)zZXx");
384
385GLOBAL_STR(gStr20, R"zZXx(
386 Command Language <a class="group-link" href="chap-cmd-lang.html">cmd-lang</a>
387
388
389 [YSH Simple] typed-arg json write (x)
390 lazy-expr-arg assert [42 === x]
391 block-arg cd /tmp { echo $PWD }; cd /tmp (; ; blockexpr)
392 [YSH Cond] ysh-case case (x) { *.py { echo 'python' } }
393 ysh-if if (x > 0) { echo }
394 [YSH Iter] ysh-while while (x > 0) { echo }
395 ysh-for for i, item in (mylist) { echo }
396)zZXx");
397
398GLOBAL_STR(gStr21, R"zZXx(
399 Expression Language and Assignments <a class="group-link" href="chap-expr-lang.html">expr-lang</a>
400
401
402 [Assignment] assign =
403 aug-assign += -= *= /= **= //= %=
404 &= |= ^= <<= >>=
405 [Literals] atom-literal true false null
406 int-literal 42 65_536 0xFF 0o755 0b10
407 float-lit 3.14 1.5e-10
408 X num-suffix 42 K Ki M Mi G Gi T Ti / ms us
409 ysh-string "x is $x" $"x is $x" r'[a-z]\n'
410 u'line\n' b'byte \yff'
411 triple-quoted """ $""" r''' u''' b'''
412 str-template ^"$a and $b" for Str::replace()
413 list-literal ['one', 'two', 3] :| unquoted words |
414 dict-literal {name: 'bob'} {a, b}
415 range 1 .. n+1
416 block-expr ^(echo $PWD)
417 expr-literal ^[1 + 2*3]
418 X expr-sub $[myobj]
419 X expr-splice @[myobj]
420 [Operators] op-precedence Like Python
421 concat s1 ++ s2, L1 ++ L2
422 ysh-equals === !== ~== is, is not
423 ysh-in in, not in
424 ysh-compare < <= > >= (numbers only)
425 ysh-logical not and or
426 ysh-arith + - * / // % **
427 ysh-bitwise ~ & | ^ << >>
428 ysh-ternary '+' if x >= 0 else '-'
429 ysh-index s[0] mylist[3] mydict['key']
430 ysh-attr mydict.key
431 ysh-slice a[1:-1] s[1:-1]
432 func-call f(x, y; ...named)
433 thin-arrow mylist->pop()
434 fat-arrow mystr => startsWith('prefix')
435 match-ops ~ !~ ~~ !~~
436 [Eggex] re-literal / d+ ; re-flags ; ERE /
437 re-primitive %zero 'sq'
438 class-literal [c a-z 'abc' @str_var \\ \xFF \u0100]
439 named-class dot digit space word d s w
440 re-repeat d? d* d+ d{3} d{2,4}
441 re-compound seq1 seq2 alt1|alt2 (expr1 expr2)
442 re-capture <capture d+ as name: int>
443 re-splice Subpattern @subpattern
444 re-flags reg_icase reg_newline
445 X re-multiline ///
446)zZXx");
447
448GLOBAL_STR(gStr22, R"zZXx(
449 Front End <a class="group-link" href="chap-front-end.html">front-end</a>
450
451
452 [Usage] oils-usage ysh-usage
453 [Lexing] ascii-whitespace [ \t\r\n]
454 doc-comment ### multiline-command ...
455 [Tools] cat-em
456)zZXx");
457
458GLOBAL_STR(gStr23, R"zZXx(
459 Other Mini Languages <a class="group-link" href="chap-mini-lang.html">mini-lang</a>
460
461
462 [Patterns] glob-pat *.py
463 [Other Sublang] braces {alice,bob}@example.com
464)zZXx");
465
466GLOBAL_STR(gStr24, R"zZXx(
467 Global Shell Options <a class="group-link" href="chap-option.html">option</a>
468
469
470 [Groups] strict:all ysh:upgrade ysh:all
471 [YSH Details] opts-redefine opts-internal
472)zZXx");
473
474GLOBAL_STR(gStr25, R"zZXx(
475 Plugins and Hooks <a class="group-link" href="chap-plugin.html">plugin</a>
476
477
478 [YSH] renderPrompt()
479)zZXx");
480
481GLOBAL_STR(gStr26, R"zZXx(
482 Special Variables <a class="group-link" href="chap-special-var.html">special-var</a>
483
484
485 [YSH Vars] ARGV X ENV X _ESCAPE
486 _this_dir
487 [YSH Status] _error
488 _pipeline_status _process_sub_status
489 [YSH Tracing] SHX_indent SHX_punct SHX_pid_str
490 [YSH read] _reply
491 [History] YSH_HISTFILE
492 [Oils VM] OILS_VERSION
493 OILS_GC_THRESHOLD OILS_GC_ON_EXIT
494 OILS_GC_STATS OILS_GC_STATS_FD
495)zZXx");
496
497GLOBAL_STR(gStr27, R"zZXx(
498 Types and Methods <a class="group-link" href="chap-type-method.html">type-method</a>
499
500
501 [Atom Types] Null Bool
502 [Number Types] Int Float
503 [Str] X find() replace()
504 trim() trimStart() trimEnd()
505 startsWith() endsWith()
506 upper() lower()
507 search() leftMatch()
508 [List] List/append() pop() extend() indexOf()
509 X insert() X remove() reverse()
510 [Dict] keys() values() X get() X erase()
511 X inc() X accum()
512 [Range]
513 [Eggex]
514 [Match] group() start() end()
515 X groups() X groupDict()
516 [Place] setValue()
517 [Code Types] Expr Command
518 BuiltinFunc BoundFunc
519X [Func] name() location() toJson()
520X [Proc] name() location() toJson()
521X [Module] name() filename()
522 [IO] X eval() X captureStdout()
523 promptVal()
524 X time() X strftime()
525 X glob()
526X [Guts] heapId()
527)zZXx");
528
529GLOBAL_STR(gStr28, R"zZXx(bin/ysh is the shell with data tYpes, influenced by pYthon, JavaScript, ...
530
531Usage: ysh FLAG* SCRIPT ARG*
532 ysh FLAG* -c COMMAND ARG*
533 ysh FLAG*
534
535`bin/ysh` is the same as `bin/osh` with a the `ysh:all` option group set. So
536`bin/ysh` also accepts shell flags.
537
538 ysh -c 'echo hi'
539 ysh myscript.ysh
540 echo 'echo hi' | ysh
541)zZXx");
542
543GLOBAL_STR(gStr29, R"zZXx(
544 Word Language <a class="group-link" href="chap-word-lang.html">word-lang</a>
545
546
547 [Quotes] ysh-string "x is $x" $"x is $x" r'[a-z]\n'
548 u'line\n' b'byte \yff'
549 triple-quoted """ $""" r''' u''' b'''
550 X tagged-str "<span id=$x>"html
551 [Substitutions] expr-sub echo $[42 + a[i]]
552 expr-splice echo @[split(x)]
553 var-splice @myarray @ARGV
554 command-sub @(split command)
555 [Formatting] X ysh-printf ${x %.3f}
556 X ysh-format ${x|html}
557)zZXx");
558
559GLOBAL_STR(gStr30, R"zZXx(
560 YSH Command Language Keywords <a class="group-link" href="chap-ysh-cmd.html">ysh-cmd</a>
561
562
563 [Assignment] const var Declare variables
564 setvar setvar a[i] = 42
565 setglobal setglobal d.key = 'foo'
566 [Expression] equal = = 1 + 2*3
567 call call mylist->append(42)
568 [Definitions] proc proc p (s, ...rest) {
569 typed proc p (; typed, ...rest; n=0; b) {
570 func func f(x; opt1, opt2) { return (x + 1) }
571 ysh-return return (myexpr)
572)zZXx");
573
574GLOBAL_STR(gStr31, R"zZXx(# args.ysh
575#
576# Usage:
577# source --builtin args.sh
578#
579# parser (&spec) {
580# flag -v --verbose (help="Verbosely") # default is Bool, false
581#
582# flag -P --max-procs ('int', default=-1, doc='''
583# Run at most P processes at a time
584# ''')
585#
586# flag -i --invert ('bool', default=true, doc='''
587# Long multiline
588# Description
589# ''')
590#
591# arg src (help='Source')
592# arg dest (help='Dest')
593# arg times (help='Foo')
594#
595# rest files
596# }
597#
598# var args = parseArgs(spec, ARGV)
599#
600# echo "Verbose $[args.verbose]"
601
602# TODO: See list
603# - It would be nice to keep `flag` and `arg` private, injecting them into the
604# proc namespace only within `Args`
605# - We need "type object" to replace the strings 'int', 'bool', etc.
606# - flag builtin:
607# - handle only long flag or only short flag
608# - flag aliases
609
610proc parser (; place ; ; block_def) {
611 ## Create an args spec which can be passed to parseArgs.
612 ##
613 ## Example:
614 ##
615 ## # NOTE: &spec will create a variable named spec
616 ## parser (&spec) {
617 ## flag -v --verbose ('bool')
618 ## }
619 ##
620 ## var args = parseArgs(spec, ARGV)
621
622 var p = {flags: [], args: []}
623 ctx push (p; ; block_def)
624
625 # Validate that p.rest = [name] or null and reduce p.rest into name or null.
626 if ('rest' in p) {
627 if (len(p.rest) > 1) {
628 error '`rest` was called more than once' (code=3)
629 } else {
630 setvar p.rest = p.rest[0]
631 }
632 } else {
633 setvar p.rest = null
634 }
635
636 var names = {}
637 for items in ([p.flags, p.args]) {
638 for x in (items) {
639 if (x.name in names) {
640 error "Duplicate flag/arg name $[x.name] in spec" (code=3)
641 }
642
643 setvar names[x.name] = null
644 }
645 }
646
647 # TODO: what about `flag --name` and then `arg name`?
648
649 call place->setValue(p)
650}
651
652proc flag (short, long ; type='bool' ; default=null, help=null) {
653 ## Declare a flag within an `arg-parse`.
654 ##
655 ## Examples:
656 ##
657 ## arg-parse (&spec) {
658 ## flag -v --verbose
659 ## flag -n --count ('int', default=1)
660 ## flag -f --file ('str', help="File to process")
661 ## }
662
663 # bool has a default of false, not null
664 if (type === 'bool' and default === null) {
665 setvar default = false
666 }
667
668 # TODO: validate `type`
669
670 # TODO: Should use "trimPrefix"
671 var name = long[2:]
672
673 ctx emit flags ({short, long, name, type, default, help})
674}
675
676proc arg (name ; ; help=null) {
677 ## Declare a positional argument within an `arg-parse`.
678 ##
679 ## Examples:
680 ##
681 ## arg-parse (&spec) {
682 ## arg name
683 ## arg config (help="config file path")
684 ## }
685
686 ctx emit args ({name, help})
687}
688
689proc rest (name) {
690 ## Take the remaining positional arguments within an `arg-parse`.
691 ##
692 ## Examples:
693 ##
694 ## arg-parse (&grepSpec) {
695 ## arg query
696 ## rest files
697 ## }
698
699 # We emit instead of set to detect multiple invocations of "rest"
700 ctx emit rest (name)
701}
702
703func parseArgs(spec, argv) {
704 ## Given a spec created by `parser`. Parse an array of strings `argv` per
705 ## that spec.
706 ##
707 ## See `parser` for examples of use.
708
709 var i = 0
710 var positionalPos = 0
711 var argc = len(argv)
712 var args = {}
713 var rest = []
714
715 var value
716 var found
717 while (i < argc) {
718 var arg = argv[i]
719 if (arg->startsWith('-')) {
720 setvar found = false
721
722 for flag in (spec.flags) {
723 if ( (flag.short and flag.short === arg) or
724 (flag.long and flag.long === arg) ) {
725 case (flag.type) {
726 ('bool') | (null) { setvar value = true }
727 int {
728 setvar i += 1
729 if (i >= len(argv)) {
730 error "Expected integer after '$arg'" (code=2)
731 }
732
733 try { setvar value = int(argv[i]) }
734 if (_status !== 0) {
735 error "Expected integer after '$arg', got '$[argv[i]]'" (code=2)
736 }
737 }
738 }
739
740 setvar args[flag.name] = value
741 setvar found = true
742 break
743 }
744 }
745
746 if (not found) {
747 error "Unknown flag '$arg'" (code=2)
748 }
749 } elif (positionalPos >= len(spec.args)) {
750 if (not spec.rest) {
751 error "Too many arguments, unexpected '$arg'" (code=2)
752 }
753
754 call rest->append(arg)
755 } else {
756 var pos = spec.args[positionalPos]
757 setvar positionalPos += 1
758 setvar value = arg
759 setvar args[pos.name] = value
760 }
761
762 setvar i += 1
763 }
764
765 if (spec.rest) {
766 setvar args[spec.rest] = rest
767 }
768
769 # Set defaults for flags
770 for flag in (spec.flags) {
771 if (flag.name not in args) {
772 setvar args[flag.name] = flag.default
773 }
774 }
775
776 # Raise error on missing args
777 for arg in (spec.args) {
778 if (arg.name not in args) {
779 error "Usage Error: Missing required argument $[arg.name]" (code=2)
780 }
781 }
782
783 return (args)
784}
785)zZXx");
786
787GLOBAL_STR(gStr32, R"zZXx(# Library to turn a file into a "BYO test server"
788#
789# Usage:
790# source --builtin test/byo-server-lib.sh # from Oils
791# source test/byo-server-lib.sh # can be used with bash
792#
793# The client creates a clean process state and directory state for each tests.
794#
795# (It relies on compgen -A, and maybe declare -f, so it's not POSIX shell.)
796
797byo-maybe-main() {
798 if test -n "${BYO_LIST_TESTS:-}"; then
799 # bash extension that OSH also implements
800 compgen -A function | grep '^test-'
801 exit 0
802 fi
803
804 local test_name=${BYO_TEST_NAME:-}
805 if test -n "$test_name"; then
806 # Shell convention: we name functions test-*
807 $test_name
808
809 # Only run if not set -e. Either way it's equivalent
810 exit $?
811 fi
812
813 # Do nothing if none of those variables is set.
814 # The program continues to its "main".
815}
816)zZXx");
817
818GLOBAL_STR(gStr33, R"zZXx(func identity(x) {
819 ## The identity function. Returns its argument.
820
821 return (x)
822}
823)zZXx");
824
825GLOBAL_STR(gStr34, R"zZXx(func any(list) {
826 ## Returns true if any value in the list is truthy.
827 ##
828 ## If the list is empty, return false.
829
830 for item in (list) {
831 if (item) {
832 return (true)
833 }
834 }
835 return (false)
836}
837
838func all(list) {
839 ## Returns true if all values in the list are truthy.
840 ##
841 ## If the list is empty, return true.
842
843 for item in (list) {
844 if (not item) {
845 return (false)
846 }
847 }
848 return (true)
849}
850
851func sum(list; start=0) {
852 ## Computes the sum of all elements in the list.
853 ##
854 ## Returns 0 for an empty list.
855
856 var sum = start
857 for item in (list) {
858 setvar sum += item
859 }
860 return (sum)
861}
862)zZXx");
863
864GLOBAL_STR(gStr35, R"zZXx(func __math_select(list, cmp) {
865 ## Internal helper for `max` and `min`.
866 ##
867 ## NOTE: If `list` is empty, then an error is thrown.
868
869 if (len(list) === 0) {
870 error "Unexpected empty list" (code=3)
871 }
872
873 if (len(list) === 1) {
874 return (list[0])
875 }
876
877 var match = list[0]
878 for i in (1 .. len(list)) {
879 setvar match = cmp(list[i], match)
880 }
881 return (match)
882}
883
884func max(...args) {
885 ## Compute the maximum of 2 or more values.
886 ##
887 ## `max` takes two different signatures:
888 ## - `max(a, b)` to return the maximum of `a`, `b`
889 ## - `max(list)` to return the greatest item in the `list`
890 ##
891 ## So, for example:
892 ##
893 ## max(1, 2) # => 2
894 ## max([1, 2, 3]) # => 3
895
896 case (len(args)) {
897 (1) { return (__math_select(args[0], max)) }
898 (2) {
899 if (args[0] > args[1]) {
900 return (args[0])
901 } else {
902 return (args[1])
903 }
904 }
905 (else) { error "max expects 1 or 2 args" (code=3) }
906 }
907}
908
909func min(...args) {
910 ## Compute the minimum of 2 or more values.
911 ##
912 ## `min` takes two different signatures:
913 ## - `min(a, b)` to return the minimum of `a`, `b`
914 ## - `min(list)` to return the least item in the `list`
915 ##
916 ## So, for example:
917 ##
918 ## min(2, 3) # => 2
919 ## max([1, 2, 3]) # => 1
920
921 case (len(args)) {
922 (1) { return (__math_select(args[0], min)) }
923 (2) {
924 if (args[0] < args[1]) {
925 return (args[0])
926 } else {
927 return (args[1])
928 }
929 }
930 (else) { error "min expects 1 or 2 args" (code=3) }
931 }
932}
933
934func abs(x) {
935 ## Compute the absolute (positive) value of a number (float or int).
936
937 if (x < 0) {
938 return (-x)
939 } else {
940 return (x)
941 }
942}
943)zZXx");
944
945GLOBAL_STR(gStr36, R"zZXx(# Can we define methods in pure YSH?
946#
947# (mylist->find(42) !== -1)
948#
949# instead of
950#
951# ('42' in mylist)
952#
953# Because 'in' is for Dict
954
955func find (haystack List, needle) {
956 for i, x in (haystack) {
957 if (x === needle) {
958 return (i)
959 }
960 }
961 return (-1)
962}
963)zZXx");
964
965GLOBAL_STR(gStr37, R"zZXx(# oil-polyfill.sh
966#
967# Portable shell for some of Oil's builtins.
968#
969# Usage:
970# source oil-polyfill.sh
971
972sh-strict() {
973 ### Turn on "legacy" shell strict modes.
974
975 # bash has this option, which is similar.
976 # use || true in case
977 # Actually we don't need this because of static-word-eval subsumes it?
978 #shopt -s nullglob 2>/dev/null || true
979
980 # POSIX
981 set -o errexit -o nounset -o pipefail
982
983 # shopt
984}
985
986# Idea: from Soil, to fix Bernstein chaining.
987#
988# ssh $USER@$HOST "$(printf '%q ' "$@")"
989#
990# Also need one for scp.
991
992# Idea: from tea/run.sh, exit 255 for xargs
993# Does this need run --assign-status, or can it be POSIX shell?
994)zZXx");
995
996GLOBAL_STR(gStr38, R"zZXx(# These were helpful while implementing args.ysh
997# Maybe we will want to export them in a prelude so that others can use them too?
998#
999# Prior art: Rust has `todo!()` which is quite nice. Other languages allow
1000# users to `raise NotImplmentedError()`.
1001
1002# Andy comments:
1003# - 'pass' can be : or true in shell. It's a little obscure / confusing, but
1004# there is an argument for minimalism. Although I prefer words like 'true',
1005# and that already means something.
1006# - UPDATE: we once took 'pass' as a keyword, but users complained because
1007# there is a command 'pass'. So we probably can't have this by default.
1008# Need to discuss source --builtin.
1009
1010# - todo could be more static? Rust presumably does it at compile time
1011
1012proc todo () {
1013 ## Raises a not implemented error when run.
1014 error ("TODO: not implemented") # TODO: is error code 1 ok?
1015}
1016
1017proc pass () {
1018 ## Use when you want to temporarily leave a block empty.
1019 _ null
1020}
1021)zZXx");
1022
1023GLOBAL_STR(gStr39, R"zZXx(# stream.ysh
1024#
1025# Usage:
1026# source --builtin stream.ysh
1027#
1028# For reading lines, decoding, extracting, splitting
1029
1030# make this file a test server
1031source --builtin byo-server-lib.sh
1032
1033source --builtin args.ysh
1034
1035proc slurp-by (; num_lines) {
1036 # TODO: (stdin)
1037 for line in <> {
1038 echo TODO
1039 }
1040}
1041
1042# Note:
1043# - these are all the same algorithm
1044# - also word, block, etc. are all optional
1045
1046proc each-line (...words; template=null; ; block=null) {
1047 # TODO:
1048 # parse --j8 --max-jobs flag
1049
1050 # parse template_str as string
1051 # TODO: this is dangerous though ... because you can execute code
1052 # I think you need a SAFE version
1053
1054 # evaluate template string expression - I guess that allows $(echo hi) and so
1055 # forth
1056
1057 # evaluate block with _line binding
1058 # block: execute in parallel with --max-jobs
1059
1060 for line in <> {
1061 echo TODO
1062 }
1063}
1064
1065proc test-each-line {
1066 echo 'TODO: need basic test runner'
1067
1068 # ysh-tool test stream.ysh
1069 #
1070 # Col
1071
1072
1073}
1074
1075proc each-row (; ; block) {
1076 echo TODO
1077}
1078
1079proc split-by (; ifs=null; block) {
1080 echo TODO
1081}
1082
1083proc if-split-by (; ifs=null; block) {
1084 echo TODO
1085}
1086
1087proc chop () {
1088 ### alias for if-split-by
1089 echo TODO
1090}
1091
1092proc must-match (; pattern; block) {
1093 echo TODO
1094}
1095
1096proc if-match (; pattern; block) {
1097 echo TODO
1098}
1099
1100# Protocol:
1101#
1102# - The file lists its tests the "actions"
1103# - Then the test harness runs them
1104# - But should it be ENV vars
1105#
1106# - BYO_LIST_TESTS=1
1107# - BYO_RUN_TEST=foo
1108# - $PWD is a CLEAN temp dir, the process doesn't have to do anything
1109
1110# - silent on success, but prints file on output
1111# - OK this makes sense
1112#
1113# The trivial test in Python:
1114#
1115# from test import byo
1116# byo.maybe_main()
1117#
1118# bash library:
1119# source --builtin byo-server.sh
1120#
1121# byo-maybe-main # reads env variables, and then exits
1122#
1123# source --builtin assertions.ysh
1124#
1125# assert-ok 'echo hi'
1126# assert-stdout 'hi' 'echo -n hi'
1127#
1128# "$@"
1129#
1130# Run all tests
1131# util/byo-client.sh run-tests $YSH stdlib/table.ysh
1132# util/byo-client.sh run-tests -f x $YSH stdlib/table.ysh
1133
1134# Clean process
1135# Clean working dir
1136
1137#
1138# Stream Protocol:
1139# #.byo - is this she-dot, that's for a file
1140# Do we need metadata?
1141#
1142
1143# The harness
1144#
1145# It's process based testing.
1146#
1147# Test runner process: bash or OSH (unlike sharness!)
1148# Tested process: any language - bash,
1149#
1150# Key point: you don't have to quote shell code?
1151
1152list-byo-tests() {
1153 echo TODO
1154}
1155
1156run-byo-tests() {
1157 # source it
1158 echo TODO
1159}
1160
1161byo-maybe-main
1162)zZXx");
1163
1164GLOBAL_STR(gStr40, R"zZXx(# table.ysh - Library for tables.
1165#
1166# Usage:
1167# source --builtin table.ysh
1168
1169# make this file a test server
1170source --builtin byo-server-lib.sh
1171
1172proc table (...words; place; ; block) {
1173 var n = len(words)
1174
1175 # TODO: parse flags
1176 #
1177 # --by-row
1178 # --by-col
1179 #
1180 # Place is optional
1181
1182 if (n === 0) {
1183 echo TODO
1184 return
1185 }
1186
1187 var action = words[0]
1188
1189 # textual operations
1190 case (action) {
1191 cat {
1192 echo todo
1193 }
1194 align {
1195 echo todo
1196 }
1197 tabify {
1198 echo todo
1199 }
1200 tabify {
1201 echo todo
1202 }
1203 header {
1204 echo todo
1205 }
1206 slice {
1207 # this has typed args
1208 # do we do some sort of splat?
1209 echo todo
1210 }
1211 to-tsv {
1212 echo todo
1213 }
1214 }
1215
1216 echo TODO
1217}
1218
1219proc test-table {
1220 table (&files1) {
1221 cols num_bytes path
1222 type Int Str
1223
1224 row 10 README.md
1225 row 12 main.py
1226
1227 row (12, 'lib.py')
1228 row (num_bytes=12, path='util.py')
1229 }
1230
1231 # 2 columns - The default is by column?
1232 assert ['Dict' === type(files1)]
1233 assert [2 === len(files1)]
1234
1235 # Same table
1236 table --by-row (&files2) {
1237 cols num_bytes path
1238 type Int Str
1239
1240 row 10 README.md
1241 row 12 main.py
1242
1243 row (12, 'lib.py')
1244 row (num_bytes=12, path='util.py')
1245 }
1246
1247 # 4 rows
1248 assert ['List' === type(files2)]
1249 assert [4 === len(files2)]
1250}
1251
1252# "subcommands" of the dialect
1253
1254proc cols (...names) {
1255 # cols name age
1256 echo TODO
1257}
1258
1259proc types (...types) {
1260 # types - Int? Str?
1261 echo TODO
1262}
1263
1264proc attr (name; ...values) {
1265 # attr units ('-', 'secs')
1266 echo TODO
1267}
1268
1269# is this allowed outside table {} blocks too?
1270proc row {
1271 echo TODO
1272}
1273
1274#
1275# dplyr names
1276#
1277
1278# TODO: can we parse select?
1279
1280proc where {
1281 echo
1282}
1283
1284# TODO: should be able to test argv[0] or something
1285# Or pass to _mutate-transmute
1286
1287proc mutate {
1288 echo TODO
1289}
1290
1291proc transmute {
1292 echo TODO
1293}
1294
1295proc rename {
1296 echo TODO
1297}
1298
1299proc group-by {
1300 echo TODO
1301}
1302
1303proc sort-by {
1304 echo TODO
1305}
1306
1307proc summary {
1308 echo TODO
1309}
1310
1311byo-maybe-main
1312)zZXx");
1313
1314GLOBAL_STR(gStr41, R"zZXx(# testing.ysh
1315#
1316# Usage:
1317# source --builtin testing.sh
1318#
1319# func f(x) { return (x + 1) }
1320#
1321# describe foo {
1322# assert (43 === f(42))
1323# }
1324#
1325# if is-main {
1326# run-tests @ARGV # --filter
1327# }
1328
1329module stdlib/testing || return 0
1330
1331source --builtin args.ysh
1332
1333proc assert ( ; cond ; fail_message='default fail message') {
1334 echo 'hi from assert'
1335
1336 = cond
1337
1338 # I think this might be ready now?
1339
1340 var val = evalExpr(cond)
1341
1342 echo
1343 echo 'value'
1344 = val
1345 pp line (val)
1346
1347 = fail_message
1348
1349 if (val) {
1350 echo 'OK'
1351 } else {
1352 var m = evalExpr(fail_message)
1353 echo "FAIL - this is where we extract the string - $m"
1354 }
1355}
1356
1357proc test-assert {
1358 var x = 42
1359 assert [42 === x]
1360}
1361
1362proc test-expr ( ; expr ) {
1363 echo 'expr'
1364 pp line (expr)
1365}
1366
1367proc test-named ( ; ; n=^[99] ) {
1368 echo 'n'
1369 pp line (n)
1370}
1371
1372# What happens when there are duplicate test IDs?
1373#
1374# Also I think filter by "$test_id/$case_id"
1375
1376proc __it (case_id ; ; ; block) {
1377 # This uses a clean directory
1378 echo TODO
1379}
1380
1381# is this accessible to users?
1382# It can contain a global list of things to run
1383
1384# Naming convention: a proc named 'describe' mutates a global named _describe?
1385# Or maybe _describe_list ?
1386
1387var _describe_list = []
1388
1389proc describe (test_id ; ; ; block) {
1390 echo describe
1391 #= desc
1392
1393 # TODO:
1394 # - need append
1395 # - need ::
1396 # _ _describe->append(cmd)
1397 #
1398 # Need to clean this up
1399 # append (_describe, cmd) # does NOT work!
1400
1401 call _describe_list->append(block)
1402}
1403
1404proc Args {
1405 echo TODO
1406}
1407
1408# Problem: this creates a global variable?
1409Args (&spec) {
1410 flag --filter 'Regex of test descriptions'
1411}
1412
1413proc run-tests {
1414 var opt, i = parseArgs(spec, ARGV)
1415
1416 # TODO:
1417 # - parse --filter foo, which you can use eggex for!
1418
1419 for cmd in (_describe) {
1420 # TODO: print filename and 'describe' name?
1421 try {
1422 eval (cmd)
1423 }
1424 if (_status !== 0) {
1425 echo 'failed'
1426 }
1427 }
1428}
1429)zZXx");
1430
1431GLOBAL_STR(gStr42, R"zZXx(# Two functions I actually use, all the time.
1432#
1433# To keep depenedencies small, this library will NEVER grow other functions
1434# (and is named to imply that.)
1435#
1436# Usage:
1437# source --builtin two.sh
1438#
1439# Examples:
1440# log 'hi'
1441# die 'expected a number'
1442
1443log() {
1444 ### Write a message to stderr.
1445 echo "$@" >&2
1446}
1447
1448die() {
1449 ### Write an error message with the script name, and exit failure.
1450 log "$0: fatal: $@"
1451 exit 1
1452}
1453
1454)zZXx");
1455
1456
1457
1458TextFile array[] = {
1459 {.rel_path = "_devbuild/help/data-errors", .contents = gStr0},
1460 {.rel_path = "_devbuild/help/data-front-end", .contents = gStr1},
1461 {.rel_path = "_devbuild/help/data-j8-notation", .contents = gStr2},
1462 {.rel_path = "_devbuild/help/help", .contents = gStr3},
1463 {.rel_path = "_devbuild/help/oils-usage", .contents = gStr4},
1464 {.rel_path = "_devbuild/help/osh-builtin-cmd", .contents = gStr5},
1465 {.rel_path = "_devbuild/help/osh-chapters", .contents = gStr6},
1466 {.rel_path = "_devbuild/help/osh-cmd-lang", .contents = gStr7},
1467 {.rel_path = "_devbuild/help/osh-front-end", .contents = gStr8},
1468 {.rel_path = "_devbuild/help/osh-mini-lang", .contents = gStr9},
1469 {.rel_path = "_devbuild/help/osh-option", .contents = gStr10},
1470 {.rel_path = "_devbuild/help/osh-osh-assign", .contents = gStr11},
1471 {.rel_path = "_devbuild/help/osh-plugin", .contents = gStr12},
1472 {.rel_path = "_devbuild/help/osh-special-var", .contents = gStr13},
1473 {.rel_path = "_devbuild/help/osh-type-method", .contents = gStr14},
1474 {.rel_path = "_devbuild/help/osh-usage", .contents = gStr15},
1475 {.rel_path = "_devbuild/help/osh-word-lang", .contents = gStr16},
1476 {.rel_path = "_devbuild/help/ysh-builtin-cmd", .contents = gStr17},
1477 {.rel_path = "_devbuild/help/ysh-builtin-func", .contents = gStr18},
1478 {.rel_path = "_devbuild/help/ysh-chapters", .contents = gStr19},
1479 {.rel_path = "_devbuild/help/ysh-cmd-lang", .contents = gStr20},
1480 {.rel_path = "_devbuild/help/ysh-expr-lang", .contents = gStr21},
1481 {.rel_path = "_devbuild/help/ysh-front-end", .contents = gStr22},
1482 {.rel_path = "_devbuild/help/ysh-mini-lang", .contents = gStr23},
1483 {.rel_path = "_devbuild/help/ysh-option", .contents = gStr24},
1484 {.rel_path = "_devbuild/help/ysh-plugin", .contents = gStr25},
1485 {.rel_path = "_devbuild/help/ysh-special-var", .contents = gStr26},
1486 {.rel_path = "_devbuild/help/ysh-type-method", .contents = gStr27},
1487 {.rel_path = "_devbuild/help/ysh-usage", .contents = gStr28},
1488 {.rel_path = "_devbuild/help/ysh-word-lang", .contents = gStr29},
1489 {.rel_path = "_devbuild/help/ysh-ysh-cmd", .contents = gStr30},
1490 {.rel_path = "stdlib/args.ysh", .contents = gStr31},
1491 {.rel_path = "stdlib/byo-server-lib.sh", .contents = gStr32},
1492 {.rel_path = "stdlib/funcs.ysh", .contents = gStr33},
1493 {.rel_path = "stdlib/list.ysh", .contents = gStr34},
1494 {.rel_path = "stdlib/math.ysh", .contents = gStr35},
1495 {.rel_path = "stdlib/methods.ysh", .contents = gStr36},
1496 {.rel_path = "stdlib/oil-polyfill.sh", .contents = gStr37},
1497 {.rel_path = "stdlib/prelude.ysh", .contents = gStr38},
1498 {.rel_path = "stdlib/stream.ysh", .contents = gStr39},
1499 {.rel_path = "stdlib/table.ysh", .contents = gStr40},
1500 {.rel_path = "stdlib/testing.ysh", .contents = gStr41},
1501 {.rel_path = "stdlib/two.sh", .contents = gStr42},
1502
1503 {.rel_path = nullptr, .contents = nullptr},
1504};
1505
1506} // namespace embedded_file
1507
1508TextFile* gEmbeddedFiles = embedded_file::array; // turn array into pointer