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

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