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

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