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

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