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

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