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

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