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

1858 lines, 151 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 [Oils VM] OILS_VERSION LIB_OSH
228)zZXx");
229
230GLOBAL_STR(gStr14, R"zZXx(
231 Standard Library <a class="group-link" href="chap-stdlib.html">stdlib</a>
232
233
234 [bash-strict]
235 [two] log die
236 [no-quotes] nq-capture nq-capture-2 nq-assert
237 [byo-server] byo-maybe-run byo-must-run
238 [task-five]
239)zZXx");
240
241GLOBAL_STR(gStr15, R"zZXx(
242 OSH Types <a class="group-link" href="chap-type-method.html">type-method</a>
243
244
245 [OSH] BashArray BashAssoc
246)zZXx");
247
248GLOBAL_STR(gStr16, R"zZXx(bin/osh is compatible with POSIX shell, bash, and other shells.
249
250Usage: osh FLAG* SCRIPT ARG*
251 osh FLAG* -c COMMAND ARG*
252 osh FLAG*
253
254The command line accepted by `bin/osh` is compatible with /bin/sh and bash.
255
256 osh -c 'echo hi'
257 osh myscript.sh
258 echo 'echo hi' | osh
259
260It also has a few enhancements:
261
262 osh -n -c 'hello' # pretty-print the AST
263 osh --ast-format text -n -c 'hello' # print it full
264
265osh accepts POSIX sh flags, with these additions:
266
267 -n parse the program but don't execute it. Print the AST.
268 --ast-format what format the AST should be in
269)zZXx");
270
271GLOBAL_STR(gStr17, R"zZXx(
272 Word Language <a class="group-link" href="chap-word-lang.html">word-lang</a>
273
274
275 [Quotes] osh-string 'abc' $'line\n' "$var"
276 [Substitutions] command-sub $(command) `command`
277 var-sub ${var} $0 $9
278 arith-sub $((1 + 2))
279 tilde-sub ~/src
280 proc-sub diff <(sort L.txt) <(sort R.txt)
281 [Var Ops] op-test ${x:-default}
282 op-strip ${x%%suffix} etc.
283 op-replace ${x//y/z}
284 op-index ${a[i+1}
285 op-slice ${a[@]:0:1}
286 op-format ${x@P}
287)zZXx");
288
289GLOBAL_STR(gStr18, R"zZXx(
290 Builtin Commands <a class="group-link" href="chap-builtin-cmd.html">builtin-cmd</a>
291
292
293 [Memory] cmd/append Add elements to end of array
294 pp asdl cell X gc-stats line proc
295 [Handle Errors] error error 'failed' (status=2)
296 try Run with errexit, set _error
297 failed Test if _error.code !== 0
298 boolstatus Enforce 0 or 1 exit status
299 [Shell State] ysh-cd ysh-shopt compatible, and takes a block
300 shvar Temporary modify global settings
301 ctx Share and update a temporary "context"
302 push-registers Save registers like $?, PIPESTATUS
303 [Modules] runproc Run a proc; use as main entry point
304 module guard against duplicate 'source'
305 is-main false when sourcing a file
306 use change first word lookup
307 [I/O] ysh-read flags --all, -0
308 ysh-echo no -e -n with simple_echo
309 write Like echo, with --, --sep, --end
310 fork forkwait Replace & and (), and takes a block
311 fopen Open multiple streams, takes a block
312 X dbg Only thing that can be used in funcs
313 [Hay Config] hay haynode For DSLs and config files
314 [Completion] compadjust compexport
315 [Data Formats] json read write
316 json8 read write
317X [Testing] assert takes an expression
318)zZXx");
319
320GLOBAL_STR(gStr19, R"zZXx(
321 Builtin Functions <a class="group-link" href="chap-builtin-func.html">builtin-func</a>
322
323
324 [Values] len() func/type() X repeat()
325 [Conversions] bool() int() float() str() list() dict()
326 X runes() X encodeRunes()
327 X bytes() X encodeBytes()
328 [Str] X strcmp() X split() shSplit()
329 [List] join() any() all()
330 [Collections] X copy() X deepCopy()
331 [Word] glob() maybe()
332 [Math] abs() max() min() X round() sum()
333 [Serialize] toJson() fromJson()
334 toJson8() fromJson8()
335X [J8 Decode] J8.Bool() J8.Int() ...
336 [Pattern] _group() _start() _end()
337 [Introspection] shvarGet() getVar() evalExpr()
338 [Hay Config] parseHay() evalHay()
339X [Hashing] sha1dc() sha256()
340)zZXx");
341
342GLOBAL_STR(gStr20, R"zZXx(The reference is divided in to "chapters", each of which has its own table of
343contents. Type:
344
345 help ysh-$CHAPTER
346
347Where $CHAPTER is one of:
348
349 front-end
350 command-lang
351 expr-lang
352 word-lang
353 builtin-cmd
354 option
355 special-var
356 type-method
357 builtin-func
358
359Example:
360
361 help ysh-expr-lang
362)zZXx");
363
364GLOBAL_STR(gStr21, R"zZXx(
365 Command Language <a class="group-link" href="chap-cmd-lang.html">cmd-lang</a>
366
367
368 [YSH Simple] typed-arg json write (x)
369 lazy-expr-arg assert [42 === x]
370 block-arg cd /tmp { echo $PWD }; cd /tmp (; ; blockexpr)
371 [YSH Cond] ysh-case case (x) { *.py { echo 'python' } }
372 ysh-if if (x > 0) { echo }
373 [YSH Iter] ysh-while while (x > 0) { echo }
374 ysh-for for i, item in (mylist) { echo }
375)zZXx");
376
377GLOBAL_STR(gStr22, R"zZXx(
378 Expression Language and Assignments <a class="group-link" href="chap-expr-lang.html">expr-lang</a>
379
380
381 [Assignment] assign =
382 aug-assign += -= *= /= **= //= %=
383 &= |= ^= <<= >>=
384 [Literals] atom-literal true false null
385 int-literal 42 65_536 0xFF 0o755 0b10
386 float-lit 3.14 1.5e-10
387 X num-suffix 42 K Ki M Mi G Gi T Ti / ms us
388 ysh-string "x is $x" $"x is $x" r'[a-z]\n'
389 u'line\n' b'byte \yff'
390 triple-quoted """ $""" r''' u''' b'''
391 str-template ^"$a and $b" for Str::replace()
392 list-literal ['one', 'two', 3] :| unquoted words |
393 dict-literal {name: 'bob'} {a, b}
394 range 1 .. n+1
395 block-expr ^(echo $PWD)
396 expr-literal ^[1 + 2*3]
397 X expr-sub $[myobj]
398 X expr-splice @[myobj]
399 [Operators] op-precedence Like Python
400 concat s1 ++ s2, L1 ++ L2
401 ysh-equals === !== ~== is, is not
402 ysh-in in, not in
403 ysh-compare < <= > >= (numbers only)
404 ysh-logical not and or
405 ysh-arith + - * / // % **
406 ysh-bitwise ~ & | ^ << >>
407 ysh-ternary '+' if x >= 0 else '-'
408 ysh-index s[0] mylist[3] mydict['key']
409 ysh-attr mydict.key
410 ysh-slice a[1:-1] s[1:-1]
411 func-call f(x, y; ...named)
412 thin-arrow mylist->pop()
413 fat-arrow mystr => startsWith('prefix')
414 match-ops ~ !~ ~~ !~~
415 [Eggex] re-literal / d+ ; re-flags ; ERE /
416 re-primitive %zero 'sq'
417 class-literal [c a-z 'abc' @str_var \\ \xFF \u0100]
418 named-class dot digit space word d s w
419 re-repeat d? d* d+ d{3} d{2,4}
420 re-compound seq1 seq2 alt1|alt2 (expr1 expr2)
421 re-capture <capture d+ as name: int>
422 re-splice Subpattern @subpattern
423 re-flags reg_icase reg_newline
424 X re-multiline ///
425)zZXx");
426
427GLOBAL_STR(gStr23, R"zZXx(
428 Front End <a class="group-link" href="chap-front-end.html">front-end</a>
429
430
431 [Usage] oils-usage ysh-usage
432 [Lexing] ascii-whitespace [ \t\r\n]
433 doc-comment ### multiline-command ...
434 [Tools] cat-em
435)zZXx");
436
437GLOBAL_STR(gStr24, R"zZXx(
438 Other Mini Languages <a class="group-link" href="chap-mini-lang.html">mini-lang</a>
439
440
441 [Patterns] glob-pat *.py
442 [Other Sublang] braces {alice,bob}@example.com
443)zZXx");
444
445GLOBAL_STR(gStr25, R"zZXx(
446 Global Shell Options <a class="group-link" href="chap-option.html">option</a>
447
448
449 [Groups] strict:all ysh:upgrade ysh:all
450 [YSH Details] opts-redefine opts-internal
451)zZXx");
452
453GLOBAL_STR(gStr26, R"zZXx(
454 Plugins and Hooks <a class="group-link" href="chap-plugin.html">plugin</a>
455
456
457 [YSH] renderPrompt()
458)zZXx");
459
460GLOBAL_STR(gStr27, R"zZXx(
461 Special Variables <a class="group-link" href="chap-special-var.html">special-var</a>
462
463
464 [YSH Vars] ARGV X ENV X _ESCAPE
465 _this_dir
466 [YSH Status] _error
467 _pipeline_status _process_sub_status
468 [YSH Tracing] SHX_indent SHX_punct SHX_pid_str
469 [YSH read] _reply
470 [History] YSH_HISTFILE
471 [Oils VM] OILS_VERSION
472 OILS_GC_THRESHOLD OILS_GC_ON_EXIT
473 OILS_GC_STATS OILS_GC_STATS_FD
474)zZXx");
475
476GLOBAL_STR(gStr28, R"zZXx(
477 Standard Library<a class="group-link" href="chap-stdlib.html">stdlib</a>
478
479
480 [Args Parser] parser Parse command line arguments
481 flag
482 arg
483 rest
484 parseArgs()
485X [Testing] describe Test harness
486X [Lines] slurp-by combine adjacent lines into cells
487X [Awk] each-line --j8 --max-jobs (Str, Template, Block) - xargs
488 each-row --max-jobs (Str, Template, Block) - xargs
489 each-word xargs-like splitting, similar to IFS too
490 split-by (str=\n, ifs=':', pattern=/s+/)
491 if-split-by
492 chop alias for split-by (pattern=/s+/)
493 must-match (/ <capture d+> </capture w+> /)
494 if-match
495X [Table Create] table --by-row --by-col (&place); construct/parse a table
496 table/cols cols name age - cols name:Str age:Int
497 types type Str Int
498 attr attr units - secs
499 row emit row
500 table cat concatenate TSV8
501 table align to ssv8
502 table tabify to tsv8
503 table header (cols = :|name age|, types = :|Str Int|, units = :|- secs|)
504 table slice e.g. slice (1, -1) slice (5, 7)
505 table to-tsv lose type info, and error on \t in cells
506X [Table Ops] where subset of rows; dplyr filter()
507 pick subset of columns ('select' taken by shell)
508 mutate transmute [average = count / sum] - drop the ones that are used?
509 rename (bytes='bytes', path='filename')
510 group-by add a column with a group ID [ext]
511 sort-by sort by columns; dplyr arrange() [ext]
512 summary count, sum, histogram, any, all, reduce(), etc. [ext]
513)zZXx");
514
515GLOBAL_STR(gStr29, R"zZXx(
516 Types and Methods <a class="group-link" href="chap-type-method.html">type-method</a>
517
518
519 [Atom Types] Null Bool
520 [Number Types] Int Float
521 [Str] X find() replace()
522 trim() trimStart() trimEnd()
523 startsWith() endsWith()
524 upper() lower()
525 search() leftMatch()
526 [List] List/append() pop() extend() indexOf()
527 X insert() X remove() reverse()
528 [Dict] keys() values() X get() X erase()
529 X inc() X accum()
530 [Range]
531 [Eggex]
532 [Match] group() start() end()
533 X groups() X groupDict()
534 [Place] setValue()
535 [Code Types] Expr Command
536 BuiltinFunc BoundFunc
537X [Func] name() location() toJson()
538X [Proc] name() location() toJson()
539X [Module] name() filename()
540 [IO] X eval() X captureStdout()
541 promptVal()
542 X time() X strftime()
543 X glob()
544X [Guts] heapId()
545)zZXx");
546
547GLOBAL_STR(gStr30, R"zZXx(bin/ysh is the shell with data tYpes, influenced by pYthon, JavaScript, ...
548
549Usage: ysh FLAG* SCRIPT ARG*
550 ysh FLAG* -c COMMAND ARG*
551 ysh FLAG*
552
553`bin/ysh` is the same as `bin/osh` with a the `ysh:all` option group set. So
554`bin/ysh` also accepts shell flags.
555
556 ysh -c 'echo hi'
557 ysh myscript.ysh
558 echo 'echo hi' | ysh
559)zZXx");
560
561GLOBAL_STR(gStr31, R"zZXx(
562 Word Language <a class="group-link" href="chap-word-lang.html">word-lang</a>
563
564
565 [Quotes] ysh-string "x is $x" $"x is $x" r'[a-z]\n'
566 u'line\n' b'byte \yff'
567 triple-quoted """ $""" r''' u''' b'''
568 X tagged-str "<span id=$x>"html
569 [Substitutions] expr-sub echo $[42 + a[i]]
570 expr-splice echo @[split(x)]
571 var-splice @myarray @ARGV
572 command-sub @(split command)
573 [Formatting] X ysh-printf ${x %.3f}
574 X ysh-format ${x|html}
575)zZXx");
576
577GLOBAL_STR(gStr32, R"zZXx(
578 YSH Command Language Keywords <a class="group-link" href="chap-ysh-cmd.html">ysh-cmd</a>
579
580
581 [Assignment] const var Declare variables
582 setvar setvar a[i] = 42
583 setglobal setglobal d.key = 'foo'
584 [Expression] equal = = 1 + 2*3
585 call call mylist->append(42)
586 [Definitions] proc proc p (s, ...rest) {
587 typed proc p (; typed, ...rest; n=0; b) {
588 func func f(x; opt1, opt2) { return (x + 1) }
589 ysh-return return (myexpr)
590)zZXx");
591
592GLOBAL_STR(gStr33, R"zZXx(# args.ysh
593#
594# Usage:
595# source --builtin args.sh
596#
597# parser (&spec) {
598# flag -v --verbose (help="Verbosely") # default is Bool, false
599#
600# flag -P --max-procs ('int', default=-1, doc='''
601# Run at most P processes at a time
602# ''')
603#
604# flag -i --invert ('bool', default=true, doc='''
605# Long multiline
606# Description
607# ''')
608#
609# arg src (help='Source')
610# arg dest (help='Dest')
611# arg times (help='Foo')
612#
613# rest files
614# }
615#
616# var args = parseArgs(spec, ARGV)
617#
618# echo "Verbose $[args.verbose]"
619
620# TODO: See list
621# - It would be nice to keep `flag` and `arg` private, injecting them into the
622# proc namespace only within `Args`
623# - We need "type object" to replace the strings 'int', 'bool', etc.
624# - flag builtin:
625# - handle only long flag or only short flag
626# - flag aliases
627
628proc parser (; place ; ; block_def) {
629 ## Create an args spec which can be passed to parseArgs.
630 ##
631 ## Example:
632 ##
633 ## # NOTE: &spec will create a variable named spec
634 ## parser (&spec) {
635 ## flag -v --verbose ('bool')
636 ## }
637 ##
638 ## var args = parseArgs(spec, ARGV)
639
640 var p = {flags: [], args: []}
641 ctx push (p; ; block_def)
642
643 # Validate that p.rest = [name] or null and reduce p.rest into name or null.
644 if ('rest' in p) {
645 if (len(p.rest) > 1) {
646 error '`rest` was called more than once' (code=3)
647 } else {
648 setvar p.rest = p.rest[0]
649 }
650 } else {
651 setvar p.rest = null
652 }
653
654 var names = {}
655 for items in ([p.flags, p.args]) {
656 for x in (items) {
657 if (x.name in names) {
658 error "Duplicate flag/arg name $[x.name] in spec" (code=3)
659 }
660
661 setvar names[x.name] = null
662 }
663 }
664
665 # TODO: what about `flag --name` and then `arg name`?
666
667 call place->setValue(p)
668}
669
670proc flag (short, long ; type='bool' ; default=null, help=null) {
671 ## Declare a flag within an `arg-parse`.
672 ##
673 ## Examples:
674 ##
675 ## arg-parse (&spec) {
676 ## flag -v --verbose
677 ## flag -n --count ('int', default=1)
678 ## flag -f --file ('str', help="File to process")
679 ## }
680
681 # bool has a default of false, not null
682 if (type === 'bool' and default === null) {
683 setvar default = false
684 }
685
686 # TODO: validate `type`
687
688 # TODO: Should use "trimPrefix"
689 var name = long[2:]
690
691 ctx emit flags ({short, long, name, type, default, help})
692}
693
694proc arg (name ; ; help=null) {
695 ## Declare a positional argument within an `arg-parse`.
696 ##
697 ## Examples:
698 ##
699 ## arg-parse (&spec) {
700 ## arg name
701 ## arg config (help="config file path")
702 ## }
703
704 ctx emit args ({name, help})
705}
706
707proc rest (name) {
708 ## Take the remaining positional arguments within an `arg-parse`.
709 ##
710 ## Examples:
711 ##
712 ## arg-parse (&grepSpec) {
713 ## arg query
714 ## rest files
715 ## }
716
717 # We emit instead of set to detect multiple invocations of "rest"
718 ctx emit rest (name)
719}
720
721func parseArgs(spec, argv) {
722 ## Given a spec created by `parser`. Parse an array of strings `argv` per
723 ## that spec.
724 ##
725 ## See `parser` for examples of use.
726
727 var i = 0
728 var positionalPos = 0
729 var argc = len(argv)
730 var args = {}
731 var rest = []
732
733 var value
734 var found
735 while (i < argc) {
736 var arg = argv[i]
737 if (arg->startsWith('-')) {
738 setvar found = false
739
740 for flag in (spec.flags) {
741 if ( (flag.short and flag.short === arg) or
742 (flag.long and flag.long === arg) ) {
743 case (flag.type) {
744 ('bool') | (null) { setvar value = true }
745 int {
746 setvar i += 1
747 if (i >= len(argv)) {
748 error "Expected integer after '$arg'" (code=2)
749 }
750
751 try { setvar value = int(argv[i]) }
752 if (_status !== 0) {
753 error "Expected integer after '$arg', got '$[argv[i]]'" (code=2)
754 }
755 }
756 }
757
758 setvar args[flag.name] = value
759 setvar found = true
760 break
761 }
762 }
763
764 if (not found) {
765 error "Unknown flag '$arg'" (code=2)
766 }
767 } elif (positionalPos >= len(spec.args)) {
768 if (not spec.rest) {
769 error "Too many arguments, unexpected '$arg'" (code=2)
770 }
771
772 call rest->append(arg)
773 } else {
774 var pos = spec.args[positionalPos]
775 setvar positionalPos += 1
776 setvar value = arg
777 setvar args[pos.name] = value
778 }
779
780 setvar i += 1
781 }
782
783 if (spec.rest) {
784 setvar args[spec.rest] = rest
785 }
786
787 # Set defaults for flags
788 for flag in (spec.flags) {
789 if (flag.name not in args) {
790 setvar args[flag.name] = flag.default
791 }
792 }
793
794 # Raise error on missing args
795 for arg in (spec.args) {
796 if (arg.name not in args) {
797 error "Usage Error: Missing required argument $[arg.name]" (code=2)
798 }
799 }
800
801 return (args)
802}
803)zZXx");
804
805GLOBAL_STR(gStr34, R"zZXx(func identity(x) {
806 ## The identity function. Returns its argument.
807
808 return (x)
809}
810)zZXx");
811
812GLOBAL_STR(gStr35, R"zZXx(func any(list) {
813 ## Returns true if any value in the list is truthy.
814 ##
815 ## If the list is empty, return false.
816
817 for item in (list) {
818 if (item) {
819 return (true)
820 }
821 }
822 return (false)
823}
824
825func all(list) {
826 ## Returns true if all values in the list are truthy.
827 ##
828 ## If the list is empty, return true.
829
830 for item in (list) {
831 if (not item) {
832 return (false)
833 }
834 }
835 return (true)
836}
837
838func sum(list; start=0) {
839 ## Computes the sum of all elements in the list.
840 ##
841 ## Returns 0 for an empty list.
842
843 var sum = start
844 for item in (list) {
845 setvar sum += item
846 }
847 return (sum)
848}
849)zZXx");
850
851GLOBAL_STR(gStr36, R"zZXx(func __math_select(list, cmp) {
852 ## Internal helper for `max` and `min`.
853 ##
854 ## NOTE: If `list` is empty, then an error is thrown.
855
856 if (len(list) === 0) {
857 error "Unexpected empty list" (code=3)
858 }
859
860 if (len(list) === 1) {
861 return (list[0])
862 }
863
864 var match = list[0]
865 for i in (1 .. len(list)) {
866 setvar match = cmp(list[i], match)
867 }
868 return (match)
869}
870
871func max(...args) {
872 ## Compute the maximum of 2 or more values.
873 ##
874 ## `max` takes two different signatures:
875 ## - `max(a, b)` to return the maximum of `a`, `b`
876 ## - `max(list)` to return the greatest item in the `list`
877 ##
878 ## So, for example:
879 ##
880 ## max(1, 2) # => 2
881 ## max([1, 2, 3]) # => 3
882
883 case (len(args)) {
884 (1) { return (__math_select(args[0], max)) }
885 (2) {
886 if (args[0] > args[1]) {
887 return (args[0])
888 } else {
889 return (args[1])
890 }
891 }
892 (else) { error "max expects 1 or 2 args" (code=3) }
893 }
894}
895
896func min(...args) {
897 ## Compute the minimum of 2 or more values.
898 ##
899 ## `min` takes two different signatures:
900 ## - `min(a, b)` to return the minimum of `a`, `b`
901 ## - `min(list)` to return the least item in the `list`
902 ##
903 ## So, for example:
904 ##
905 ## min(2, 3) # => 2
906 ## max([1, 2, 3]) # => 1
907
908 case (len(args)) {
909 (1) { return (__math_select(args[0], min)) }
910 (2) {
911 if (args[0] < args[1]) {
912 return (args[0])
913 } else {
914 return (args[1])
915 }
916 }
917 (else) { error "min expects 1 or 2 args" (code=3) }
918 }
919}
920
921func abs(x) {
922 ## Compute the absolute (positive) value of a number (float or int).
923
924 if (x < 0) {
925 return (-x)
926 } else {
927 return (x)
928 }
929}
930)zZXx");
931
932GLOBAL_STR(gStr37, R"zZXx(# Can we define methods in pure YSH?
933#
934# (mylist->find(42) !== -1)
935#
936# instead of
937#
938# ('42' in mylist)
939#
940# Because 'in' is for Dict
941
942func find (haystack List, needle) {
943 for i, x in (haystack) {
944 if (x === needle) {
945 return (i)
946 }
947 }
948 return (-1)
949}
950)zZXx");
951
952GLOBAL_STR(gStr38, R"zZXx(# Bash strict mode, updated for 2024
953
954set -o nounset
955set -o pipefail
956set -o errexit
957shopt -s inherit_errexit
958shopt -s strict:all 2>/dev/null || true # dogfood for OSH
959
960)zZXx");
961
962GLOBAL_STR(gStr39, R"zZXx(# Library to turn a shell file into a "BYO test server"
963#
964# Usage:
965#
966# # from both bash and OSH
967# if test -z "$LIB_OSH"; then LIB_OSH=stdlib/osh; fi
968# source $LIB_OSH/byo-server-lib.sh
969#
970# The client creates a clean process state and directory state for each tests.
971#
972# (This file requires compgen -A, and maybe declare -f, so it's not POSIX
973# shell.)
974
975# TODO: How do I get stdlib/two.sh
976log() {
977 echo "$@" >& 2
978}
979
980die() {
981 log "$0: fatal: $@"
982 exit 1
983}
984
985byo-maybe-run() {
986 local command=${BYO_COMMAND:-}
987
988 case $command in
989 '')
990 # Do nothing if it's not specified
991 return
992 ;;
993
994 detect)
995 # all the commands supported, except 'detect'
996 echo list-tests
997 echo run-test
998
999 exit 66 # ASCII code for 'B' - what the protocol specifies
1000 ;;
1001
1002 list-tests)
1003 # bash extension that OSH also implements
1004 compgen -A function | grep '^test-'
1005 exit 0
1006 ;;
1007
1008 run-test)
1009 local test_name=${BYO_ARG:-}
1010 if test -z "$test_name"; then
1011 die "BYO run-test: Expected BYO_ARG"
1012 fi
1013
1014 # Shell convention: we name functions test-*
1015 $test_name
1016
1017 # Only run if not set -e. Either way it's equivalent
1018 exit $?
1019 ;;
1020
1021 *)
1022 die "Invalid BYO command '$command'"
1023 ;;
1024 esac
1025
1026 # Do nothing if BYO_COMMAND is not set.
1027 # The program continues to its "main".
1028}
1029
1030byo-must-run() {
1031 local command=${BYO_COMMAND:-}
1032 if test -z "$command"; then
1033 die "Expected BYO_COMMAND= in environment"
1034 fi
1035
1036 byo-maybe-run
1037}
1038)zZXx");
1039
1040GLOBAL_STR(gStr40, R"zZXx(#!/usr/bin/env bash
1041#
1042# Testing library for bash and OSH.
1043#
1044# Capture status/stdout/stderr, and nq-assert those values.
1045
1046: ${LIB_OSH=stdlib/osh}
1047source $LIB_OSH/two.sh
1048
1049nq-assert() {
1050 ### Assertion with same syntax as shell 'test'
1051
1052 if ! test "$@"; then
1053 die "line ${BASH_LINENO[0]}: nq-assert $(printf '%q ' "$@") failed"
1054 fi
1055}
1056
1057# Problem: we want to capture status and stdout at the same time
1058#
1059# We use:
1060#
1061# __stdout=$(set -o errexit; "$@")
1062# __status=$?
1063#
1064# However, we lose the trailing \n, since that's how command subs work.
1065
1066# Here is another possibility:
1067#
1068# shopt -s lastpipe # need this too
1069# ( set -o errexit; "$@" ) | read -r -d __stdout
1070# __status=${PIPESTATUS[0]}
1071# shopt -u lastpipe
1072#
1073# But this feels complex for just the \n issue, which can be easily worked
1074# around.
1075
1076nq-capture() {
1077 ### capture status and stdout
1078
1079 local -n out_status=$1
1080 local -n out_stdout=$2
1081 shift 2
1082
1083 local __status
1084 local __stdout
1085
1086 # Tricky: turn errexit off so we can capture it, but turn it on against
1087 set +o errexit
1088 __stdout=$(set -o errexit; "$@")
1089 __status=$?
1090 set -o errexit
1091
1092 out_status=$__status
1093 out_stdout=$__stdout
1094}
1095
1096nq-capture-2() {
1097 ### capture status and stderr
1098
1099 # This is almost identical to the above
1100
1101 local -n out_status=$1
1102 local -n out_stderr=$2
1103 shift 2
1104
1105 local __status
1106 local __stderr
1107
1108 # Tricky: turn errexit off so we can capture it, but turn it on against
1109 set +o errexit
1110 __stderr=$(set -o errexit; "$@" 2>&1)
1111 __status=$?
1112 set -o errexit
1113
1114 out_status=$__status
1115 out_stderr=$__stderr
1116}
1117
1118_demo-stderr() {
1119 echo zzz "$@" >& 2
1120 return 99
1121}
1122
1123test-nq-capture() {
1124 local status stdout
1125 nq-capture status stdout \
1126 echo -n hi
1127 nq-assert 0 = "$status"
1128 nq-assert 'hi' = "$stdout"
1129
1130 nq-capture status stdout \
1131 echo hi
1132 nq-assert 0 = "$status"
1133 # Note that we LOSE the last newline!
1134 #nq-assert $'hi\n' = "$stdout"
1135
1136 local stderr
1137 nq-capture-2 status stderr \
1138 _demo-stderr yyy
1139
1140 #echo "stderr: [$stderr]"
1141
1142 nq-assert 99 = "$status"
1143 nq-assert 'zzz yyy' = "$stderr"
1144
1145 nq-capture status stdout \
1146 _demo-stderr aaa
1147
1148 #echo "stderr: [$stderr]"
1149
1150 nq-assert 99 = "$status"
1151 nq-assert '' = "$stdout"
1152}
1153
1154name=$(basename $0)
1155if test "$name" = 'no-quotes.sh'; then
1156 "$@"
1157fi
1158)zZXx");
1159
1160GLOBAL_STR(gStr41, R"zZXx(#!/usr/bin/env bash
1161#
1162# Common shell functions for task scripts.
1163#
1164# Usage:
1165# source $LIB_OSH/task-five.sh
1166#
1167# test-foo() { # define task functions
1168# echo foo
1169# }
1170# task-five "$@"
1171
1172# Definition of a "task"
1173#
1174# - File invokes task-five "$@"
1175# - or maybe you can look at its source
1176# - It's a shell function
1177# - Has ### docstring
1178# - Doesn't start with _
1179
1180# List all functions defined in this file (and not in sourced files).
1181_bash-print-funcs() {
1182 ### Print shell functions in this file that don't start with _ (bash reflection)
1183
1184 local funcs=($(compgen -A function))
1185 # extdebug makes `declare -F` print the file path, but, annoyingly, only
1186 # if you pass the function names as arguments.
1187 shopt -s extdebug
1188 declare -F "${funcs[@]}" | grep --fixed-strings " $0" | awk '{print $1}'
1189 shopt -u extdebug
1190}
1191
1192_awk-print-funcs() {
1193 ### Print shell functions in this file that don't start with _ (awk parsing)
1194
1195 # Using gawk because it has match()
1196 # - doesn't start with _
1197
1198 # space = / ' '* /
1199 # shfunc = / %begin
1200 # <capture !['_' ' '] ![' ']*>
1201 # '()' space '{' space
1202 # %end /
1203 # docstring = / %begin
1204 # space '###' ' '+
1205 # <capture dot*>
1206 # %end /
1207 awk '
1208 match($0, /^([^_ ][^ ]*)\(\)[ ]*{[ ]*$/, m) {
1209 print NR " shfunc " m[1]
1210 #print m[0]
1211 }
1212
1213 match($0, /^[ ]*###[ ]+(.*)$/, m) {
1214 print NR " docstring " m[1]
1215 }
1216' $0
1217}
1218
1219_show-help() {
1220 # TODO:
1221 # - Use awk to find comments at the top of the file?
1222 # - Use OSH to extract docstrings
1223
1224 echo "Usage: $0 TASK_NAME ARGS..."
1225 echo
1226 echo "To complete tasks, run:"
1227 echo " source devtools/completion.bash"
1228 echo
1229 echo "Tasks:"
1230
1231 if command -v column >/dev/null; then
1232 _bash-print-funcs | column
1233 else
1234 _bash-print-funcs
1235 fi
1236}
1237
1238task-five() {
1239 if [[ $# -eq 0 || $1 =~ ^(--help|-h)$ ]]; then
1240 _show-help
1241 exit
1242 fi
1243
1244 if ! declare -f "$1" >/dev/null; then
1245 echo "$0: '$1' isn't an action in this task file. Try '$0 --help'"
1246 exit 1
1247 fi
1248
1249 "$@"
1250}
1251)zZXx");
1252
1253GLOBAL_STR(gStr42, R"zZXx(# Two functions I actually use, all the time.
1254#
1255# To keep depenedencies small, this library will NEVER grow other functions
1256# (and is named to imply that.)
1257#
1258# Usage:
1259# source --builtin two.sh
1260#
1261# Examples:
1262# log 'hi'
1263# die 'expected a number'
1264
1265log() {
1266 ### Write a message to stderr.
1267 echo "$@" >&2
1268}
1269
1270die() {
1271 ### Write an error message with the script name, and exit with status 1.
1272 log "$0: fatal: $@"
1273 exit 1
1274}
1275
1276)zZXx");
1277
1278GLOBAL_STR(gStr43, R"zZXx(# These were helpful while implementing args.ysh
1279# Maybe we will want to export them in a prelude so that others can use them too?
1280#
1281# Prior art: Rust has `todo!()` which is quite nice. Other languages allow
1282# users to `raise NotImplmentedError()`.
1283
1284# Andy comments:
1285# - 'pass' can be : or true in shell. It's a little obscure / confusing, but
1286# there is an argument for minimalism. Although I prefer words like 'true',
1287# and that already means something.
1288# - UPDATE: we once took 'pass' as a keyword, but users complained because
1289# there is a command 'pass'. So we probably can't have this by default.
1290# Need to discuss source --builtin.
1291
1292# - todo could be more static? Rust presumably does it at compile time
1293
1294proc todo () {
1295 ## Raises a not implemented error when run.
1296 error ("TODO: not implemented") # TODO: is error code 1 ok?
1297}
1298
1299proc pass () {
1300 ## Use when you want to temporarily leave a block empty.
1301 _ null
1302}
1303)zZXx");
1304
1305GLOBAL_STR(gStr44, R"zZXx(# stream.ysh
1306#
1307# Usage:
1308# source --builtin stream.ysh
1309#
1310# For reading lines, decoding, extracting, splitting
1311
1312# make this file a test server
1313source --builtin osh/byo-server.sh
1314
1315source --builtin args.ysh
1316
1317proc slurp-by (; num_lines) {
1318 # TODO: (stdin)
1319 for line in <> {
1320 echo TODO
1321 }
1322}
1323
1324# Note:
1325# - these are all the same algorithm
1326# - also word, block, etc. are all optional
1327
1328proc each-line (...words; template=null; ; block=null) {
1329 # TODO:
1330 # parse --j8 --max-jobs flag
1331
1332 # parse template_str as string
1333 # TODO: this is dangerous though ... because you can execute code
1334 # I think you need a SAFE version
1335
1336 # evaluate template string expression - I guess that allows $(echo hi) and so
1337 # forth
1338
1339 # evaluate block with _line binding
1340 # block: execute in parallel with --max-jobs
1341
1342 for line in <> {
1343 echo TODO
1344 }
1345}
1346
1347proc test-each-line {
1348 echo 'TODO: need basic test runner'
1349
1350 # ysh-tool test stream.ysh
1351 #
1352 # Col
1353
1354
1355}
1356
1357proc each-row (; ; block) {
1358 echo TODO
1359}
1360
1361proc split-by (; ifs=null; block) {
1362 echo TODO
1363}
1364
1365proc if-split-by (; ifs=null; block) {
1366 echo TODO
1367}
1368
1369proc chop () {
1370 ### alias for if-split-by
1371 echo TODO
1372}
1373
1374proc must-match (; pattern; block) {
1375 echo TODO
1376}
1377
1378proc if-match (; pattern; block) {
1379 echo TODO
1380}
1381
1382# Protocol:
1383#
1384# - The file lists its tests the "actions"
1385# - Then the test harness runs them
1386# - But should it be ENV vars
1387#
1388# - BYO_LIST_TESTS=1
1389# - BYO_RUN_TEST=foo
1390# - $PWD is a CLEAN temp dir, the process doesn't have to do anything
1391
1392# - silent on success, but prints file on output
1393# - OK this makes sense
1394#
1395# The trivial test in Python:
1396#
1397# from test import byo
1398# byo.maybe_main()
1399#
1400# bash library:
1401# source --builtin byo-server.sh
1402#
1403# byo-maybe-main # reads env variables, and then exits
1404#
1405# source --builtin assertions.ysh
1406#
1407# assert-ok 'echo hi'
1408# assert-stdout 'hi' 'echo -n hi'
1409#
1410# "$@"
1411#
1412# Run all tests
1413# util/byo-client.sh run-tests $YSH stdlib/table.ysh
1414# util/byo-client.sh run-tests -f x $YSH stdlib/table.ysh
1415
1416# Clean process
1417# Clean working dir
1418
1419#
1420# Stream Protocol:
1421# #.byo - is this she-dot, that's for a file
1422# Do we need metadata?
1423#
1424
1425# The harness
1426#
1427# It's process based testing.
1428#
1429# Test runner process: bash or OSH (unlike sharness!)
1430# Tested process: any language - bash,
1431#
1432# Key point: you don't have to quote shell code?
1433
1434list-byo-tests() {
1435 echo TODO
1436}
1437
1438run-byo-tests() {
1439 # source it
1440 echo TODO
1441}
1442
1443byo-maybe-run
1444)zZXx");
1445
1446GLOBAL_STR(gStr45, R"zZXx(# table.ysh - Library for tables.
1447#
1448# Usage:
1449# source --builtin table.ysh
1450
1451# make this file a test server
1452source --builtin osh/byo-server.sh
1453
1454proc table (...words; place; ; block) {
1455 var n = len(words)
1456
1457 # TODO: parse flags
1458 #
1459 # --by-row
1460 # --by-col
1461 #
1462 # Place is optional
1463
1464 if (n === 0) {
1465 echo TODO
1466 return
1467 }
1468
1469 var action = words[0]
1470
1471 # textual operations
1472 case (action) {
1473 cat {
1474 echo todo
1475 }
1476 align {
1477 echo todo
1478 }
1479 tabify {
1480 echo todo
1481 }
1482 tabify {
1483 echo todo
1484 }
1485 header {
1486 echo todo
1487 }
1488 slice {
1489 # this has typed args
1490 # do we do some sort of splat?
1491 echo todo
1492 }
1493 to-tsv {
1494 echo todo
1495 }
1496 }
1497
1498 echo TODO
1499}
1500
1501proc test-table {
1502 return
1503
1504 table (&files1) {
1505 cols num_bytes path
1506 type Int Str
1507
1508 row 10 README.md
1509 row 12 main.py
1510
1511 row (12, 'lib.py')
1512 row (num_bytes=12, path='util.py')
1513 }
1514
1515 # 2 columns - The default is by column?
1516 assert ['Dict' === type(files1)]
1517 assert [2 === len(files1)]
1518
1519 # Same table
1520 table --by-row (&files2) {
1521 cols num_bytes path
1522 type Int Str
1523
1524 row 10 README.md
1525 row 12 main.py
1526
1527 row (12, 'lib.py')
1528 row (num_bytes=12, path='util.py')
1529 }
1530
1531 # 4 rows
1532 assert ['List' === type(files2)]
1533 assert [4 === len(files2)]
1534}
1535
1536# "subcommands" of the dialect
1537
1538proc cols (...names) {
1539 # cols name age
1540 echo TODO
1541}
1542
1543proc types (...types) {
1544 # types - Int? Str?
1545 echo TODO
1546}
1547
1548proc attr (name; ...values) {
1549 # attr units ('-', 'secs')
1550 echo TODO
1551}
1552
1553# is this allowed outside table {} blocks too?
1554proc row {
1555 echo TODO
1556}
1557
1558#
1559# dplyr names
1560#
1561
1562# TODO: can we parse select?
1563
1564proc where {
1565 echo
1566}
1567
1568# TODO: should be able to test argv[0] or something
1569# Or pass to _mutate-transmute
1570
1571proc mutate {
1572 echo TODO
1573}
1574
1575proc transmute {
1576 echo TODO
1577}
1578
1579proc rename {
1580 echo TODO
1581}
1582
1583proc group-by {
1584 echo TODO
1585}
1586
1587proc sort-by {
1588 echo TODO
1589}
1590
1591proc summary {
1592 echo TODO
1593}
1594
1595byo-maybe-run
1596)zZXx");
1597
1598GLOBAL_STR(gStr46, R"zZXx(# TODO:
1599# - [x] Renaming a bit for "privacy"
1600# - [x] Renaming for public interface: test-case, test-suite, assert (subject to change)
1601# - [x] Rename to use "-"s for procs.
1602# - [x] Make test-case and test-suite take a word arg so they don't need parens
1603# - [x] error if you try to re-enter run-tests
1604# - [x] testing testing: assert fail, exn in assert, exn outside of assert
1605# - [-] check for both kinds of exceptions (_status and _error)
1606# - [x] tests for tests
1607# - [ ] question: naming for variables?
1608# - [ ] --tool test support (& spec test case for it)
1609# - [ ] Turn the assert expression into a string, to print if it fails
1610# - [ ] Use ctx instead of globals, wherever possible
1611# - [ ] Merge _status and _error. Every exception should set _error, with the
1612# status stored on _error.status. Use _error instead of the icky global
1613# _assertion_result
1614
1615##########
1616# Colors #
1617##########
1618
1619const _BOLD = $'\e[1m'
1620const _RED = $'\e[31m'
1621const _GREEN = $'\e[32m'
1622const _YELLOW = $'\e[33m'
1623const _PURPLE = $'\e[35m'
1624const _CYAN = $'\e[36m'
1625const _RESET = $'\e[0;0m'
1626
1627func _red(text) {
1628 if (_test_use_color) {
1629 return ("${_BOLD}${_RED}${text}${_RESET}")
1630 } else {
1631 return (text)
1632 }
1633}
1634func _yellow(text) {
1635 if (_test_use_color) {
1636 return ("${_YELLOW}${text}${_RESET}")
1637 } else {
1638 return (text)
1639 }
1640}
1641func _green(text) {
1642 if (_test_use_color) {
1643 return ("${_YELLOW}${text}${_RESET}")
1644 } else {
1645 return (text)
1646 }
1647}
1648func _cyan(text) {
1649 if (_test_use_color) {
1650 return ("${_YELLOW}${text}${_RESET}")
1651 } else {
1652 return (text)
1653 }
1654}
1655
1656############
1657# Internal #
1658############
1659
1660var _testing_in_progress = false
1661var _test_suite_depth = 0
1662var _test_suite_stack = []
1663var _tests = {}
1664
1665var _num_test_fail = 0
1666var _num_test_succ = 0
1667var _test_use_color = true
1668
1669var _assertion_result = 0 # 0: no assert, 1: failed, 2: errored
1670
1671proc _start-test-suite (; name) {
1672 call _test_suite_stack->append(name)
1673}
1674
1675proc _end-test-suite {
1676 call _test_suite_stack->pop()
1677}
1678
1679proc _test-print-indented (msg) {
1680 for _ in (0 .. _test_suite_depth) {
1681 printf " "
1682 }
1683 echo "$msg"
1684}
1685
1686proc _run-test-suite (; suite) {
1687 for name, elem in (suite) {
1688 if (type (elem) === "Dict") {
1689 # It's another suite.
1690 var begin = _cyan("begin")
1691 _test-print-indented "$begin $name"
1692 setglobal _test_suite_depth += 1;
1693 _run-test-suite (elem)
1694 setglobal _test_suite_depth -= 1;
1695 var end = _cyan("end")
1696 _test-print-indented "$end"
1697 } else {
1698 # It's a test case.
1699 _run-test-case (name, elem)
1700 }
1701 }
1702}
1703
1704proc _run-test-case (; name, block) {
1705 var test = _yellow("test")
1706 for _ in (0 .. _test_suite_depth) {
1707 printf " "
1708 }
1709 printf "$test $name ..."
1710 setglobal _assertion_result = 0
1711 try {
1712 eval (block)
1713 }
1714 if (_status === 0) {
1715 setglobal _num_test_succ += 1
1716 var ok = _green(" ok")
1717 printf "$ok"
1718 printf '\n'
1719 } else {
1720 setglobal _num_test_fail += 1
1721 printf '\n'
1722 if (_assertion_result === 1) {
1723 # An assertion failed.
1724 var fail = _red("assertion FAILED")
1725 _test-print-indented " $fail"
1726 } elif (_assertion_result === 2) {
1727 # There was an exception while evaluating an assertion.
1728 var exn_in_assert = _red("assertion ERRORED:")
1729 _test-print-indented " $exn_in_assert $_status"
1730 } else {
1731 # There was an exception in the test case outside of any `assert`.
1732 var exn = _red("ERROR:")
1733 _test-print-indented " $exn $_status"
1734 }
1735 }
1736}
1737
1738##########
1739# Public #
1740##########
1741
1742proc test-suite (name ; ; ; block) {
1743 _start-test-suite (name)
1744 eval (block)
1745 _end-test-suite
1746}
1747
1748proc test-case (name ; ; ; block) {
1749 var test_suite = _tests
1750 for suite_name in (_test_suite_stack) {
1751 if (not (suite_name in test_suite)) {
1752 setvar test_suite[suite_name] = {}
1753 }
1754 setvar test_suite = test_suite[suite_name]
1755 }
1756 setvar test_suite[name] = block
1757}
1758
1759proc assert ( ; cond LAZY ) {
1760 var success
1761 try {
1762 setvar success = evalExpr(cond)
1763 }
1764 if (_status !== 0) {
1765 setglobal _assertion_result = 2
1766 error "exception in assertion"
1767 } elif (not success) {
1768 setglobal _assertion_result = 1
1769 error "assertion failed"
1770 }
1771}
1772
1773proc run-tests {
1774 if (_testing_in_progress) {
1775 error "Cannot run tests while testing is already in progress"
1776 }
1777 setglobal _testing_in_progress = true
1778 setglobal _num_test_fail = 0
1779 setglobal _num_test_succ = 0
1780
1781 _run-test-suite (_tests)
1782 setglobal _tests = {}
1783 setglobal _testing_in_progress = false
1784
1785 var total = _num_test_fail + _num_test_succ
1786 if (total === 0) {
1787 var na = _yellow("0 tests ran")
1788 printf "$na"
1789 printf '\n'
1790 } elif (_num_test_fail === 0) {
1791 var success = _green("$total tests succeeded")
1792 printf "$success"
1793 printf '\n'
1794 } else {
1795 var failure = _red("$_num_test_fail / $total tests failed")
1796 printf "$failure"
1797 printf '\n'
1798 }
1799}
1800)zZXx");
1801
1802
1803
1804TextFile array[] = {
1805 {.rel_path = "_devbuild/help/data-errors", .contents = gStr0},
1806 {.rel_path = "_devbuild/help/data-front-end", .contents = gStr1},
1807 {.rel_path = "_devbuild/help/data-j8-notation", .contents = gStr2},
1808 {.rel_path = "_devbuild/help/help", .contents = gStr3},
1809 {.rel_path = "_devbuild/help/oils-usage", .contents = gStr4},
1810 {.rel_path = "_devbuild/help/osh-builtin-cmd", .contents = gStr5},
1811 {.rel_path = "_devbuild/help/osh-chapters", .contents = gStr6},
1812 {.rel_path = "_devbuild/help/osh-cmd-lang", .contents = gStr7},
1813 {.rel_path = "_devbuild/help/osh-front-end", .contents = gStr8},
1814 {.rel_path = "_devbuild/help/osh-mini-lang", .contents = gStr9},
1815 {.rel_path = "_devbuild/help/osh-option", .contents = gStr10},
1816 {.rel_path = "_devbuild/help/osh-osh-assign", .contents = gStr11},
1817 {.rel_path = "_devbuild/help/osh-plugin", .contents = gStr12},
1818 {.rel_path = "_devbuild/help/osh-special-var", .contents = gStr13},
1819 {.rel_path = "_devbuild/help/osh-stdlib", .contents = gStr14},
1820 {.rel_path = "_devbuild/help/osh-type-method", .contents = gStr15},
1821 {.rel_path = "_devbuild/help/osh-usage", .contents = gStr16},
1822 {.rel_path = "_devbuild/help/osh-word-lang", .contents = gStr17},
1823 {.rel_path = "_devbuild/help/ysh-builtin-cmd", .contents = gStr18},
1824 {.rel_path = "_devbuild/help/ysh-builtin-func", .contents = gStr19},
1825 {.rel_path = "_devbuild/help/ysh-chapters", .contents = gStr20},
1826 {.rel_path = "_devbuild/help/ysh-cmd-lang", .contents = gStr21},
1827 {.rel_path = "_devbuild/help/ysh-expr-lang", .contents = gStr22},
1828 {.rel_path = "_devbuild/help/ysh-front-end", .contents = gStr23},
1829 {.rel_path = "_devbuild/help/ysh-mini-lang", .contents = gStr24},
1830 {.rel_path = "_devbuild/help/ysh-option", .contents = gStr25},
1831 {.rel_path = "_devbuild/help/ysh-plugin", .contents = gStr26},
1832 {.rel_path = "_devbuild/help/ysh-special-var", .contents = gStr27},
1833 {.rel_path = "_devbuild/help/ysh-stdlib", .contents = gStr28},
1834 {.rel_path = "_devbuild/help/ysh-type-method", .contents = gStr29},
1835 {.rel_path = "_devbuild/help/ysh-usage", .contents = gStr30},
1836 {.rel_path = "_devbuild/help/ysh-word-lang", .contents = gStr31},
1837 {.rel_path = "_devbuild/help/ysh-ysh-cmd", .contents = gStr32},
1838 {.rel_path = "stdlib/args.ysh", .contents = gStr33},
1839 {.rel_path = "stdlib/funcs.ysh", .contents = gStr34},
1840 {.rel_path = "stdlib/list.ysh", .contents = gStr35},
1841 {.rel_path = "stdlib/math.ysh", .contents = gStr36},
1842 {.rel_path = "stdlib/methods.ysh", .contents = gStr37},
1843 {.rel_path = "stdlib/osh/bash-strict.sh", .contents = gStr38},
1844 {.rel_path = "stdlib/osh/byo-server.sh", .contents = gStr39},
1845 {.rel_path = "stdlib/osh/no-quotes.sh", .contents = gStr40},
1846 {.rel_path = "stdlib/osh/task-five.sh", .contents = gStr41},
1847 {.rel_path = "stdlib/osh/two.sh", .contents = gStr42},
1848 {.rel_path = "stdlib/prelude.ysh", .contents = gStr43},
1849 {.rel_path = "stdlib/stream.ysh", .contents = gStr44},
1850 {.rel_path = "stdlib/table.ysh", .contents = gStr45},
1851 {.rel_path = "stdlib/testing.ysh", .contents = gStr46},
1852
1853 {.rel_path = nullptr, .contents = nullptr},
1854};
1855
1856} // namespace embedded_file
1857
1858TextFile* gEmbeddedFiles = embedded_file::array; // turn array into pointer