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

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