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

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