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

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