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

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