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

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