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

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