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

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