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

1570 lines, 135 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(#!/usr/bin/env bash
575#
576# Run tests in this directory.
577#
578# Usage:
579# stdlib/TEST.sh <function name>
580
581set -o nounset
582set -o pipefail
583set -o errexit
584
585YSH=bin/ysh
586
587test-byo-protocol() {
588 return
589
590 # Usually the "BYO" command does this
591 BYO_COMMAND=detect $YSH stdlib/table.ysh
592
593 # TODO: need assertions here
594 # assert status
595
596 # assert-ok 'echo hi'
597 # assert-stdout 'echo hi'
598 # assert-fail 2 '(exit 2)'
599
600 # I think we usually don't need this
601 # assert-fail-stdout 2 '(exit 2)'
602
603 BYO_COMMAND=z $YSH stdlib/table.ysh
604
605 # missing
606 BYO_COMMAND=run-test $YSH stdlib/table.ysh
607
608 # TODO: test file with no tests
609}
610
611soil-run() {
612 test-byo-protocol
613
614 test/byo-client.sh run-tests $YSH stdlib/stream.ysh
615
616 test/byo-client.sh run-tests $YSH stdlib/table.ysh
617
618 # I guess this needs tests, with an assertion library for stdout?
619
620 # TODO: if there are no tests, it should fail
621 # test/byo-client.sh run-tests $SH stdlib/two.sh
622}
623
624
625
626"$@"
627)zZXx");
628
629GLOBAL_STR(gStr32, R"zZXx(# args.ysh
630#
631# Usage:
632# source --builtin args.sh
633#
634# parser (&spec) {
635# flag -v --verbose (help="Verbosely") # default is Bool, false
636#
637# flag -P --max-procs ('int', default=-1, doc='''
638# Run at most P processes at a time
639# ''')
640#
641# flag -i --invert ('bool', default=true, doc='''
642# Long multiline
643# Description
644# ''')
645#
646# arg src (help='Source')
647# arg dest (help='Dest')
648# arg times (help='Foo')
649#
650# rest files
651# }
652#
653# var args = parseArgs(spec, ARGV)
654#
655# echo "Verbose $[args.verbose]"
656
657# TODO: See list
658# - It would be nice to keep `flag` and `arg` private, injecting them into the
659# proc namespace only within `Args`
660# - We need "type object" to replace the strings 'int', 'bool', etc.
661# - flag builtin:
662# - handle only long flag or only short flag
663# - flag aliases
664
665proc parser (; place ; ; block_def) {
666 ## Create an args spec which can be passed to parseArgs.
667 ##
668 ## Example:
669 ##
670 ## # NOTE: &spec will create a variable named spec
671 ## parser (&spec) {
672 ## flag -v --verbose ('bool')
673 ## }
674 ##
675 ## var args = parseArgs(spec, ARGV)
676
677 var p = {flags: [], args: []}
678 ctx push (p; ; block_def)
679
680 # Validate that p.rest = [name] or null and reduce p.rest into name or null.
681 if ('rest' in p) {
682 if (len(p.rest) > 1) {
683 error '`rest` was called more than once' (code=3)
684 } else {
685 setvar p.rest = p.rest[0]
686 }
687 } else {
688 setvar p.rest = null
689 }
690
691 var names = {}
692 for items in ([p.flags, p.args]) {
693 for x in (items) {
694 if (x.name in names) {
695 error "Duplicate flag/arg name $[x.name] in spec" (code=3)
696 }
697
698 setvar names[x.name] = null
699 }
700 }
701
702 # TODO: what about `flag --name` and then `arg name`?
703
704 call place->setValue(p)
705}
706
707proc flag (short, long ; type='bool' ; default=null, help=null) {
708 ## Declare a flag within an `arg-parse`.
709 ##
710 ## Examples:
711 ##
712 ## arg-parse (&spec) {
713 ## flag -v --verbose
714 ## flag -n --count ('int', default=1)
715 ## flag -f --file ('str', help="File to process")
716 ## }
717
718 # bool has a default of false, not null
719 if (type === 'bool' and default === null) {
720 setvar default = false
721 }
722
723 # TODO: validate `type`
724
725 # TODO: Should use "trimPrefix"
726 var name = long[2:]
727
728 ctx emit flags ({short, long, name, type, default, help})
729}
730
731proc arg (name ; ; help=null) {
732 ## Declare a positional argument within an `arg-parse`.
733 ##
734 ## Examples:
735 ##
736 ## arg-parse (&spec) {
737 ## arg name
738 ## arg config (help="config file path")
739 ## }
740
741 ctx emit args ({name, help})
742}
743
744proc rest (name) {
745 ## Take the remaining positional arguments within an `arg-parse`.
746 ##
747 ## Examples:
748 ##
749 ## arg-parse (&grepSpec) {
750 ## arg query
751 ## rest files
752 ## }
753
754 # We emit instead of set to detect multiple invocations of "rest"
755 ctx emit rest (name)
756}
757
758func parseArgs(spec, argv) {
759 ## Given a spec created by `parser`. Parse an array of strings `argv` per
760 ## that spec.
761 ##
762 ## See `parser` for examples of use.
763
764 var i = 0
765 var positionalPos = 0
766 var argc = len(argv)
767 var args = {}
768 var rest = []
769
770 var value
771 var found
772 while (i < argc) {
773 var arg = argv[i]
774 if (arg->startsWith('-')) {
775 setvar found = false
776
777 for flag in (spec.flags) {
778 if ( (flag.short and flag.short === arg) or
779 (flag.long and flag.long === arg) ) {
780 case (flag.type) {
781 ('bool') | (null) { setvar value = true }
782 int {
783 setvar i += 1
784 if (i >= len(argv)) {
785 error "Expected integer after '$arg'" (code=2)
786 }
787
788 try { setvar value = int(argv[i]) }
789 if (_status !== 0) {
790 error "Expected integer after '$arg', got '$[argv[i]]'" (code=2)
791 }
792 }
793 }
794
795 setvar args[flag.name] = value
796 setvar found = true
797 break
798 }
799 }
800
801 if (not found) {
802 error "Unknown flag '$arg'" (code=2)
803 }
804 } elif (positionalPos >= len(spec.args)) {
805 if (not spec.rest) {
806 error "Too many arguments, unexpected '$arg'" (code=2)
807 }
808
809 call rest->append(arg)
810 } else {
811 var pos = spec.args[positionalPos]
812 setvar positionalPos += 1
813 setvar value = arg
814 setvar args[pos.name] = value
815 }
816
817 setvar i += 1
818 }
819
820 if (spec.rest) {
821 setvar args[spec.rest] = rest
822 }
823
824 # Set defaults for flags
825 for flag in (spec.flags) {
826 if (flag.name not in args) {
827 setvar args[flag.name] = flag.default
828 }
829 }
830
831 # Raise error on missing args
832 for arg in (spec.args) {
833 if (arg.name not in args) {
834 error "Usage Error: Missing required argument $[arg.name]" (code=2)
835 }
836 }
837
838 return (args)
839}
840)zZXx");
841
842GLOBAL_STR(gStr33, R"zZXx(# Library to turn a file into a "BYO test server"
843#
844# Usage:
845# source --builtin test/byo-server-lib.sh # from Oils
846# source test/byo-server-lib.sh # can be used with bash
847#
848# The client creates a clean process state and directory state for each tests.
849#
850# (It relies on compgen -A, and maybe declare -f, so it's not POSIX shell.)
851
852# TODO: How do I get stdlib/two.sh
853log() {
854 echo "$@" >& 2
855}
856
857die() {
858 log "$0: fatal: $@"
859 exit 1
860}
861
862
863byo-maybe-main() {
864 local command=${BYO_COMMAND:-}
865
866 case $command in
867 '')
868 # Do nothing if it's not specified
869 return
870 ;;
871
872 detect)
873 # all the commands supported, except 'detect'
874 echo list-tests
875 echo run-test
876
877 exit 66 # ASCII code for 'B' - what the protocol specifies
878 ;;
879
880 list-tests)
881 # bash extension that OSH also implements
882 compgen -A function | grep '^test-'
883 exit 0
884 ;;
885
886 run-test)
887 local test_name=${BYO_ARG:-}
888 if test -z "$test_name"; then
889 die "BYO run-test: Expected BYO_ARG"
890 fi
891
892 # Shell convention: we name functions test-*
893 $test_name
894
895 # Only run if not set -e. Either way it's equivalent
896 exit $?
897 ;;
898
899 *)
900 die "Invalid BYO command '$command'"
901 ;;
902 esac
903
904 # Do nothing if BYO_COMMAND is not set.
905 # The program continues to its "main".
906}
907)zZXx");
908
909GLOBAL_STR(gStr34, R"zZXx(func identity(x) {
910 ## The identity function. Returns its argument.
911
912 return (x)
913}
914)zZXx");
915
916GLOBAL_STR(gStr35, R"zZXx(func any(list) {
917 ## Returns true if any value in the list is truthy.
918 ##
919 ## If the list is empty, return false.
920
921 for item in (list) {
922 if (item) {
923 return (true)
924 }
925 }
926 return (false)
927}
928
929func all(list) {
930 ## Returns true if all values in the list are truthy.
931 ##
932 ## If the list is empty, return true.
933
934 for item in (list) {
935 if (not item) {
936 return (false)
937 }
938 }
939 return (true)
940}
941
942func sum(list; start=0) {
943 ## Computes the sum of all elements in the list.
944 ##
945 ## Returns 0 for an empty list.
946
947 var sum = start
948 for item in (list) {
949 setvar sum += item
950 }
951 return (sum)
952}
953)zZXx");
954
955GLOBAL_STR(gStr36, R"zZXx(func __math_select(list, cmp) {
956 ## Internal helper for `max` and `min`.
957 ##
958 ## NOTE: If `list` is empty, then an error is thrown.
959
960 if (len(list) === 0) {
961 error "Unexpected empty list" (code=3)
962 }
963
964 if (len(list) === 1) {
965 return (list[0])
966 }
967
968 var match = list[0]
969 for i in (1 .. len(list)) {
970 setvar match = cmp(list[i], match)
971 }
972 return (match)
973}
974
975func max(...args) {
976 ## Compute the maximum of 2 or more values.
977 ##
978 ## `max` takes two different signatures:
979 ## - `max(a, b)` to return the maximum of `a`, `b`
980 ## - `max(list)` to return the greatest item in the `list`
981 ##
982 ## So, for example:
983 ##
984 ## max(1, 2) # => 2
985 ## max([1, 2, 3]) # => 3
986
987 case (len(args)) {
988 (1) { return (__math_select(args[0], max)) }
989 (2) {
990 if (args[0] > args[1]) {
991 return (args[0])
992 } else {
993 return (args[1])
994 }
995 }
996 (else) { error "max expects 1 or 2 args" (code=3) }
997 }
998}
999
1000func min(...args) {
1001 ## Compute the minimum of 2 or more values.
1002 ##
1003 ## `min` takes two different signatures:
1004 ## - `min(a, b)` to return the minimum of `a`, `b`
1005 ## - `min(list)` to return the least item in the `list`
1006 ##
1007 ## So, for example:
1008 ##
1009 ## min(2, 3) # => 2
1010 ## max([1, 2, 3]) # => 1
1011
1012 case (len(args)) {
1013 (1) { return (__math_select(args[0], min)) }
1014 (2) {
1015 if (args[0] < args[1]) {
1016 return (args[0])
1017 } else {
1018 return (args[1])
1019 }
1020 }
1021 (else) { error "min expects 1 or 2 args" (code=3) }
1022 }
1023}
1024
1025func abs(x) {
1026 ## Compute the absolute (positive) value of a number (float or int).
1027
1028 if (x < 0) {
1029 return (-x)
1030 } else {
1031 return (x)
1032 }
1033}
1034)zZXx");
1035
1036GLOBAL_STR(gStr37, R"zZXx(# Can we define methods in pure YSH?
1037#
1038# (mylist->find(42) !== -1)
1039#
1040# instead of
1041#
1042# ('42' in mylist)
1043#
1044# Because 'in' is for Dict
1045
1046func find (haystack List, needle) {
1047 for i, x in (haystack) {
1048 if (x === needle) {
1049 return (i)
1050 }
1051 }
1052 return (-1)
1053}
1054)zZXx");
1055
1056GLOBAL_STR(gStr38, R"zZXx(# These were helpful while implementing args.ysh
1057# Maybe we will want to export them in a prelude so that others can use them too?
1058#
1059# Prior art: Rust has `todo!()` which is quite nice. Other languages allow
1060# users to `raise NotImplmentedError()`.
1061
1062# Andy comments:
1063# - 'pass' can be : or true in shell. It's a little obscure / confusing, but
1064# there is an argument for minimalism. Although I prefer words like 'true',
1065# and that already means something.
1066# - UPDATE: we once took 'pass' as a keyword, but users complained because
1067# there is a command 'pass'. So we probably can't have this by default.
1068# Need to discuss source --builtin.
1069
1070# - todo could be more static? Rust presumably does it at compile time
1071
1072proc todo () {
1073 ## Raises a not implemented error when run.
1074 error ("TODO: not implemented") # TODO: is error code 1 ok?
1075}
1076
1077proc pass () {
1078 ## Use when you want to temporarily leave a block empty.
1079 _ null
1080}
1081)zZXx");
1082
1083GLOBAL_STR(gStr39, R"zZXx(# stream.ysh
1084#
1085# Usage:
1086# source --builtin stream.ysh
1087#
1088# For reading lines, decoding, extracting, splitting
1089
1090# make this file a test server
1091source --builtin byo-server-lib.sh
1092
1093source --builtin args.ysh
1094
1095proc slurp-by (; num_lines) {
1096 # TODO: (stdin)
1097 for line in <> {
1098 echo TODO
1099 }
1100}
1101
1102# Note:
1103# - these are all the same algorithm
1104# - also word, block, etc. are all optional
1105
1106proc each-line (...words; template=null; ; block=null) {
1107 # TODO:
1108 # parse --j8 --max-jobs flag
1109
1110 # parse template_str as string
1111 # TODO: this is dangerous though ... because you can execute code
1112 # I think you need a SAFE version
1113
1114 # evaluate template string expression - I guess that allows $(echo hi) and so
1115 # forth
1116
1117 # evaluate block with _line binding
1118 # block: execute in parallel with --max-jobs
1119
1120 for line in <> {
1121 echo TODO
1122 }
1123}
1124
1125proc test-each-line {
1126 echo 'TODO: need basic test runner'
1127
1128 # ysh-tool test stream.ysh
1129 #
1130 # Col
1131
1132
1133}
1134
1135proc each-row (; ; block) {
1136 echo TODO
1137}
1138
1139proc split-by (; ifs=null; block) {
1140 echo TODO
1141}
1142
1143proc if-split-by (; ifs=null; block) {
1144 echo TODO
1145}
1146
1147proc chop () {
1148 ### alias for if-split-by
1149 echo TODO
1150}
1151
1152proc must-match (; pattern; block) {
1153 echo TODO
1154}
1155
1156proc if-match (; pattern; block) {
1157 echo TODO
1158}
1159
1160# Protocol:
1161#
1162# - The file lists its tests the "actions"
1163# - Then the test harness runs them
1164# - But should it be ENV vars
1165#
1166# - BYO_LIST_TESTS=1
1167# - BYO_RUN_TEST=foo
1168# - $PWD is a CLEAN temp dir, the process doesn't have to do anything
1169
1170# - silent on success, but prints file on output
1171# - OK this makes sense
1172#
1173# The trivial test in Python:
1174#
1175# from test import byo
1176# byo.maybe_main()
1177#
1178# bash library:
1179# source --builtin byo-server.sh
1180#
1181# byo-maybe-main # reads env variables, and then exits
1182#
1183# source --builtin assertions.ysh
1184#
1185# assert-ok 'echo hi'
1186# assert-stdout 'hi' 'echo -n hi'
1187#
1188# "$@"
1189#
1190# Run all tests
1191# util/byo-client.sh run-tests $YSH stdlib/table.ysh
1192# util/byo-client.sh run-tests -f x $YSH stdlib/table.ysh
1193
1194# Clean process
1195# Clean working dir
1196
1197#
1198# Stream Protocol:
1199# #.byo - is this she-dot, that's for a file
1200# Do we need metadata?
1201#
1202
1203# The harness
1204#
1205# It's process based testing.
1206#
1207# Test runner process: bash or OSH (unlike sharness!)
1208# Tested process: any language - bash,
1209#
1210# Key point: you don't have to quote shell code?
1211
1212list-byo-tests() {
1213 echo TODO
1214}
1215
1216run-byo-tests() {
1217 # source it
1218 echo TODO
1219}
1220
1221byo-maybe-main
1222)zZXx");
1223
1224GLOBAL_STR(gStr40, R"zZXx(# table.ysh - Library for tables.
1225#
1226# Usage:
1227# source --builtin table.ysh
1228
1229# make this file a test server
1230source --builtin byo-server-lib.sh
1231
1232proc table (...words; place; ; block) {
1233 var n = len(words)
1234
1235 # TODO: parse flags
1236 #
1237 # --by-row
1238 # --by-col
1239 #
1240 # Place is optional
1241
1242 if (n === 0) {
1243 echo TODO
1244 return
1245 }
1246
1247 var action = words[0]
1248
1249 # textual operations
1250 case (action) {
1251 cat {
1252 echo todo
1253 }
1254 align {
1255 echo todo
1256 }
1257 tabify {
1258 echo todo
1259 }
1260 tabify {
1261 echo todo
1262 }
1263 header {
1264 echo todo
1265 }
1266 slice {
1267 # this has typed args
1268 # do we do some sort of splat?
1269 echo todo
1270 }
1271 to-tsv {
1272 echo todo
1273 }
1274 }
1275
1276 echo TODO
1277}
1278
1279proc test-table {
1280 return
1281
1282 table (&files1) {
1283 cols num_bytes path
1284 type Int Str
1285
1286 row 10 README.md
1287 row 12 main.py
1288
1289 row (12, 'lib.py')
1290 row (num_bytes=12, path='util.py')
1291 }
1292
1293 # 2 columns - The default is by column?
1294 assert ['Dict' === type(files1)]
1295 assert [2 === len(files1)]
1296
1297 # Same table
1298 table --by-row (&files2) {
1299 cols num_bytes path
1300 type Int Str
1301
1302 row 10 README.md
1303 row 12 main.py
1304
1305 row (12, 'lib.py')
1306 row (num_bytes=12, path='util.py')
1307 }
1308
1309 # 4 rows
1310 assert ['List' === type(files2)]
1311 assert [4 === len(files2)]
1312}
1313
1314# "subcommands" of the dialect
1315
1316proc cols (...names) {
1317 # cols name age
1318 echo TODO
1319}
1320
1321proc types (...types) {
1322 # types - Int? Str?
1323 echo TODO
1324}
1325
1326proc attr (name; ...values) {
1327 # attr units ('-', 'secs')
1328 echo TODO
1329}
1330
1331# is this allowed outside table {} blocks too?
1332proc row {
1333 echo TODO
1334}
1335
1336#
1337# dplyr names
1338#
1339
1340# TODO: can we parse select?
1341
1342proc where {
1343 echo
1344}
1345
1346# TODO: should be able to test argv[0] or something
1347# Or pass to _mutate-transmute
1348
1349proc mutate {
1350 echo TODO
1351}
1352
1353proc transmute {
1354 echo TODO
1355}
1356
1357proc rename {
1358 echo TODO
1359}
1360
1361proc group-by {
1362 echo TODO
1363}
1364
1365proc sort-by {
1366 echo TODO
1367}
1368
1369proc summary {
1370 echo TODO
1371}
1372
1373byo-maybe-main
1374)zZXx");
1375
1376GLOBAL_STR(gStr41, R"zZXx(# testing.ysh
1377#
1378# Usage:
1379# source --builtin testing.sh
1380#
1381# func f(x) { return (x + 1) }
1382#
1383# describe foo {
1384# assert (43 === f(42))
1385# }
1386#
1387# if is-main {
1388# run-tests @ARGV # --filter
1389# }
1390
1391module stdlib/testing || return 0
1392
1393source --builtin args.ysh
1394
1395proc assert ( ; cond ; fail_message='default fail message') {
1396 echo 'hi from assert'
1397
1398 = cond
1399
1400 # I think this might be ready now?
1401
1402 var val = evalExpr(cond)
1403
1404 echo
1405 echo 'value'
1406 = val
1407 pp line (val)
1408
1409 = fail_message
1410
1411 if (val) {
1412 echo 'OK'
1413 } else {
1414 var m = evalExpr(fail_message)
1415 echo "FAIL - this is where we extract the string - $m"
1416 }
1417}
1418
1419proc test-assert {
1420 var x = 42
1421 assert [42 === x]
1422}
1423
1424proc test-expr ( ; expr ) {
1425 echo 'expr'
1426 pp line (expr)
1427}
1428
1429proc test-named ( ; ; n=^[99] ) {
1430 echo 'n'
1431 pp line (n)
1432}
1433
1434# What happens when there are duplicate test IDs?
1435#
1436# Also I think filter by "$test_id/$case_id"
1437
1438proc __it (case_id ; ; ; block) {
1439 # This uses a clean directory
1440 echo TODO
1441}
1442
1443# is this accessible to users?
1444# It can contain a global list of things to run
1445
1446# Naming convention: a proc named 'describe' mutates a global named _describe?
1447# Or maybe _describe_list ?
1448
1449var _describe_list = []
1450
1451proc describe (test_id ; ; ; block) {
1452 echo describe
1453 #= desc
1454
1455 # TODO:
1456 # - need append
1457 # - need ::
1458 # _ _describe->append(cmd)
1459 #
1460 # Need to clean this up
1461 # append (_describe, cmd) # does NOT work!
1462
1463 call _describe_list->append(block)
1464}
1465
1466proc Args {
1467 echo TODO
1468}
1469
1470# Problem: this creates a global variable?
1471Args (&spec) {
1472 flag --filter 'Regex of test descriptions'
1473}
1474
1475proc run-tests {
1476 var opt, i = parseArgs(spec, ARGV)
1477
1478 # TODO:
1479 # - parse --filter foo, which you can use eggex for!
1480
1481 for cmd in (_describe) {
1482 # TODO: print filename and 'describe' name?
1483 try {
1484 eval (cmd)
1485 }
1486 if (_status !== 0) {
1487 echo 'failed'
1488 }
1489 }
1490}
1491)zZXx");
1492
1493GLOBAL_STR(gStr42, R"zZXx(# Two functions I actually use, all the time.
1494#
1495# To keep depenedencies small, this library will NEVER grow other functions
1496# (and is named to imply that.)
1497#
1498# Usage:
1499# source --builtin two.sh
1500#
1501# Examples:
1502# log 'hi'
1503# die 'expected a number'
1504
1505log() {
1506 ### Write a message to stderr.
1507 echo "$@" >&2
1508}
1509
1510die() {
1511 ### Write an error message with the script name, and exit failure.
1512 log "$0: fatal: $@"
1513 exit 1
1514}
1515
1516)zZXx");
1517
1518
1519
1520TextFile array[] = {
1521 {.rel_path = "_devbuild/help/data-errors", .contents = gStr0},
1522 {.rel_path = "_devbuild/help/data-front-end", .contents = gStr1},
1523 {.rel_path = "_devbuild/help/data-j8-notation", .contents = gStr2},
1524 {.rel_path = "_devbuild/help/help", .contents = gStr3},
1525 {.rel_path = "_devbuild/help/oils-usage", .contents = gStr4},
1526 {.rel_path = "_devbuild/help/osh-builtin-cmd", .contents = gStr5},
1527 {.rel_path = "_devbuild/help/osh-chapters", .contents = gStr6},
1528 {.rel_path = "_devbuild/help/osh-cmd-lang", .contents = gStr7},
1529 {.rel_path = "_devbuild/help/osh-front-end", .contents = gStr8},
1530 {.rel_path = "_devbuild/help/osh-mini-lang", .contents = gStr9},
1531 {.rel_path = "_devbuild/help/osh-option", .contents = gStr10},
1532 {.rel_path = "_devbuild/help/osh-osh-assign", .contents = gStr11},
1533 {.rel_path = "_devbuild/help/osh-plugin", .contents = gStr12},
1534 {.rel_path = "_devbuild/help/osh-special-var", .contents = gStr13},
1535 {.rel_path = "_devbuild/help/osh-type-method", .contents = gStr14},
1536 {.rel_path = "_devbuild/help/osh-usage", .contents = gStr15},
1537 {.rel_path = "_devbuild/help/osh-word-lang", .contents = gStr16},
1538 {.rel_path = "_devbuild/help/ysh-builtin-cmd", .contents = gStr17},
1539 {.rel_path = "_devbuild/help/ysh-builtin-func", .contents = gStr18},
1540 {.rel_path = "_devbuild/help/ysh-chapters", .contents = gStr19},
1541 {.rel_path = "_devbuild/help/ysh-cmd-lang", .contents = gStr20},
1542 {.rel_path = "_devbuild/help/ysh-expr-lang", .contents = gStr21},
1543 {.rel_path = "_devbuild/help/ysh-front-end", .contents = gStr22},
1544 {.rel_path = "_devbuild/help/ysh-mini-lang", .contents = gStr23},
1545 {.rel_path = "_devbuild/help/ysh-option", .contents = gStr24},
1546 {.rel_path = "_devbuild/help/ysh-plugin", .contents = gStr25},
1547 {.rel_path = "_devbuild/help/ysh-special-var", .contents = gStr26},
1548 {.rel_path = "_devbuild/help/ysh-type-method", .contents = gStr27},
1549 {.rel_path = "_devbuild/help/ysh-usage", .contents = gStr28},
1550 {.rel_path = "_devbuild/help/ysh-word-lang", .contents = gStr29},
1551 {.rel_path = "_devbuild/help/ysh-ysh-cmd", .contents = gStr30},
1552 {.rel_path = "stdlib/TEST.sh", .contents = gStr31},
1553 {.rel_path = "stdlib/args.ysh", .contents = gStr32},
1554 {.rel_path = "stdlib/byo-server-lib.sh", .contents = gStr33},
1555 {.rel_path = "stdlib/funcs.ysh", .contents = gStr34},
1556 {.rel_path = "stdlib/list.ysh", .contents = gStr35},
1557 {.rel_path = "stdlib/math.ysh", .contents = gStr36},
1558 {.rel_path = "stdlib/methods.ysh", .contents = gStr37},
1559 {.rel_path = "stdlib/prelude.ysh", .contents = gStr38},
1560 {.rel_path = "stdlib/stream.ysh", .contents = gStr39},
1561 {.rel_path = "stdlib/table.ysh", .contents = gStr40},
1562 {.rel_path = "stdlib/testing.ysh", .contents = gStr41},
1563 {.rel_path = "stdlib/two.sh", .contents = gStr42},
1564
1565 {.rel_path = nullptr, .contents = nullptr},
1566};
1567
1568} // namespace embedded_file
1569
1570TextFile* gEmbeddedFiles = embedded_file::array; // turn array into pointer