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

1980 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 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 flag arg rest 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# - It would be nice to keep `flag` and `arg` private, injecting them into the
1046# proc namespace only within `Args`
1047# - flag builtin:
1048# - handle only long flag or only short flag
1049# - flag aliases
1050
1051proc parser (; place ; ; block_def) {
1052 ## Create an args spec which can be passed to parseArgs.
1053 ##
1054 ## Example:
1055 ##
1056 ## # NOTE: &spec will create a variable named spec
1057 ## parser (&spec) {
1058 ## flag -v --verbose (Bool)
1059 ## }
1060 ##
1061 ## var args = parseArgs(spec, ARGV)
1062
1063 var p = {flags: [], args: []}
1064 ctx push (p; ; block_def)
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, Int, Str]
1094const kValidTypeNames = []
1095for vt in (kValidTypes) {
1096 call kValidTypeNames->append(vt.name)
1097}
1098
1099func isValidType (type) {
1100 try {
1101 for valid in (kValidTypes) {
1102 if (type is valid) {
1103 return (true)
1104 }
1105 }
1106 }
1107 return (false)
1108}
1109
1110proc flag (short, long ; type=Bool ; default=null, help=null) {
1111 ## Declare a flag within an `arg-parse`.
1112 ##
1113 ## Examples:
1114 ##
1115 ## arg-parse (&spec) {
1116 ## flag -v --verbose
1117 ## flag -n --count (Int, default=1)
1118 ## flag -p --percent (Float, default=0.0)
1119 ## flag -f --file (Str, help="File to process")
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 Float) {
1199 setvar i += 1
1200 if (i >= len(argv)) {
1201 error "Expected Float after '$arg'" (code=2)
1202 }
1203
1204 try { setvar value = float(argv[i]) }
1205 if (_status !== 0) {
1206 error "Expected Float after '$arg', got '$[argv[i]]'" (code=2)
1207 }
1208 } elif (flag.type is Str) {
1209 setvar i += 1
1210 if (i >= len(argv)) {
1211 error "Expected Str after '$arg'" (code=2)
1212 }
1213
1214 setvar value = argv[i]
1215 }
1216
1217 setvar args[flag.name] = value
1218 setvar found = true
1219 break
1220 }
1221 }
1222
1223 if (not found) {
1224 error "Unknown flag '$arg'" (code=2)
1225 }
1226 } elif (positionalPos >= len(spec.args)) {
1227 if (not spec.rest) {
1228 error "Too many arguments, unexpected '$arg'" (code=2)
1229 }
1230
1231 call rest->append(arg)
1232 } else {
1233 var pos = spec.args[positionalPos]
1234 setvar positionalPos += 1
1235 setvar value = arg
1236 setvar args[pos.name] = value
1237 }
1238
1239 setvar i += 1
1240 }
1241
1242 if (spec.rest) {
1243 setvar args[spec.rest] = rest
1244 }
1245
1246 # Set defaults for flags
1247 for flag in (spec.flags) {
1248 if (flag.name not in args) {
1249 setvar args[flag.name] = flag.default
1250 }
1251 }
1252
1253 # Raise error on missing args
1254 for arg in (spec.args) {
1255 if (arg.name not in args) {
1256 error "Usage Error: Missing required argument $[arg.name]" (code=2)
1257 }
1258 }
1259
1260 return (args)
1261}
1262)zZXx");
1263
1264GLOBAL_STR(gStr41, R"zZXx(const __provide__ = :| Dict |
1265
1266proc Dict ( ; out; ; block) {
1267 var d = io->evalToDict(block)
1268 call out->setValue(d)
1269}
1270
1271)zZXx");
1272
1273GLOBAL_STR(gStr42, R"zZXx(const __provide__ = :| any all sum repeat |
1274
1275func any(list) {
1276 ### Returns true if any value in the list is truthy.
1277 # Empty list: returns false
1278
1279 for item in (list) {
1280 if (item) {
1281 return (true)
1282 }
1283 }
1284 return (false)
1285}
1286
1287func all(list) {
1288 ### Returns true if all values in the list are truthy.
1289 # Empty list: returns true
1290
1291 for item in (list) {
1292 if (not item) {
1293 return (false)
1294 }
1295 }
1296 return (true)
1297}
1298
1299func sum(list; start=0) {
1300 ### Returns the sum of all elements in the list.
1301 # Empty list: returns 0
1302
1303 var sum = start
1304 for item in (list) {
1305 setvar sum += item
1306 }
1307 return (sum)
1308}
1309
1310func repeat(x, n) {
1311 ### Returns a list with the given string or list repeated
1312
1313 # Like Python's 'foo'*3 or ['foo', 'bar']*3
1314 # negative numbers are like 0 in Python
1315
1316 var t = type(x)
1317 case (t) {
1318 Str {
1319 var parts = []
1320 for i in (0 ..< n) {
1321 call parts->append(x)
1322 }
1323 return (join(parts))
1324 }
1325 List {
1326 var result = []
1327 for i in (0 ..< n) {
1328 call result->extend(x)
1329 }
1330 return (result)
1331 }
1332 (else) {
1333 error "Expected Str or List, got $t"
1334 }
1335 }
1336}
1337)zZXx");
1338
1339GLOBAL_STR(gStr43, R"zZXx(const __provide__ = :| identity max min abs |
1340
1341func identity(x) {
1342 ### The identity function. Returns its argument.
1343
1344 return (x)
1345}
1346
1347func __math_select(list, cmp) {
1348 ## Internal helper for `max` and `min`.
1349 ##
1350 ## NOTE: If `list` is empty, then an error is thrown.
1351
1352 if (len(list) === 0) {
1353 error "Unexpected empty list" (code=3)
1354 }
1355
1356 if (len(list) === 1) {
1357 return (list[0])
1358 }
1359
1360 var match = list[0]
1361 for i in (1 ..< len(list)) {
1362 setvar match = cmp(list[i], match)
1363 }
1364 return (match)
1365}
1366
1367func max(...args) {
1368 ## Compute the maximum of 2 or more values.
1369 ##
1370 ## `max` takes two different signatures:
1371 ## - `max(a, b)` to return the maximum of `a`, `b`
1372 ## - `max(list)` to return the greatest item in the `list`
1373 ##
1374 ## So, for example:
1375 ##
1376 ## max(1, 2) # => 2
1377 ## max([1, 2, 3]) # => 3
1378
1379 case (len(args)) {
1380 (1) { return (__math_select(args[0], max)) }
1381 (2) {
1382 if (args[0] > args[1]) {
1383 return (args[0])
1384 } else {
1385 return (args[1])
1386 }
1387 }
1388 (else) { error "max expects 1 or 2 args" (code=3) }
1389 }
1390}
1391
1392func min(...args) {
1393 ## Compute the minimum of 2 or more values.
1394 ##
1395 ## `min` takes two different signatures:
1396 ## - `min(a, b)` to return the minimum of `a`, `b`
1397 ## - `min(list)` to return the least item in the `list`
1398 ##
1399 ## So, for example:
1400 ##
1401 ## min(2, 3) # => 2
1402 ## max([1, 2, 3]) # => 1
1403
1404 case (len(args)) {
1405 (1) { return (__math_select(args[0], min)) }
1406 (2) {
1407 if (args[0] < args[1]) {
1408 return (args[0])
1409 } else {
1410 return (args[1])
1411 }
1412 }
1413 (else) { error "min expects 1 or 2 args" (code=3) }
1414 }
1415}
1416
1417func abs(x) {
1418 ## Compute the absolute (positive) value of a number (float or int).
1419
1420 if (x < 0) {
1421 return (-x)
1422 } else {
1423 return (x)
1424 }
1425}
1426)zZXx");
1427
1428GLOBAL_STR(gStr44, R"zZXx(# stream.ysh
1429#
1430# Usage:
1431# source --builtin stream.ysh
1432#
1433# For reading lines, decoding, extracting, splitting
1434
1435# make this file a test server
1436source $LIB_OSH/byo-server.sh
1437
1438source $LIB_YSH/args.ysh
1439
1440proc slurp-by (; num_lines) {
1441 var buf = []
1442 for line in (io.stdin) {
1443 call buf->append(line)
1444 if (len(buf) === num_lines) {
1445 json write (buf, space=0)
1446
1447 # TODO:
1448 #call buf->clear()
1449 setvar buf = []
1450 }
1451 }
1452 if (buf) {
1453 json write (buf, space=0)
1454 }
1455}
1456
1457proc test-slurp-by {
1458 seq 8 | slurp-by (3)
1459}
1460
1461### Awk
1462
1463# Naming
1464#
1465# TEXT INPUT
1466# each-word # this doesn't go by lines, it does a global regex split or something?
1467#
1468# LINE INPUT
1469# each-line --j8 { echo "-- $_line" } # similar to @()
1470# each-line --j8 (^"-- $_line") # is this superfluous?
1471#
1472# each-split name1 name2
1473# (delim=' ')
1474# (ifs=' ')
1475# (pat=/d+/)
1476# # also assign names for each part?
1477#
1478# each-match # regex match
1479# must-match # assert that every line matches
1480#
1481# TABLE INPUT
1482# each-row # TSV and TSV8 input?
1483#
1484# They all take templates or blocks?
1485
1486proc each-line (...words; template=null; ; block=null) {
1487 # TODO:
1488 # parse --j8 --max-jobs flag
1489
1490 # parse template_str as string
1491 # TODO: this is dangerous though ... because you can execute code
1492 # I think you need a SAFE version
1493
1494 # evaluate template string expression - I guess that allows $(echo hi) and so
1495 # forth
1496
1497 # evaluate block with _line binding
1498 # block: execute in parallel with --max-jobs
1499
1500 for line in (stdin) {
1501 echo TODO
1502 }
1503}
1504
1505proc test-each-line {
1506 echo 'TODO: need basic test runner'
1507
1508 # ysh-tool test stream.ysh
1509 #
1510 # Col
1511}
1512
1513proc each-row (; ; block) {
1514 echo TODO
1515}
1516
1517proc split-by (; delim; ifs=null; block) {
1518
1519 # TODO: provide the option to bind names? Or is that a separate thing?
1520 # The output of this is "ragged"
1521
1522 for line in (io.stdin) {
1523 #pp (line)
1524 var parts = line.split(delim)
1525 pp (parts)
1526
1527 # variable number
1528 call io->eval(block, dollar0=line, pos_args=parts)
1529 }
1530}
1531
1532proc chop () {
1533 ### alias for split-by
1534 echo TODO
1535}
1536
1537proc test-split-by {
1538 var z = 'z' # test out scoping
1539 var count = 0 # test out mutation
1540
1541 # TODO: need split by space
1542 # Where the leading and trailing are split
1543 # if-split-by(' ') doesn't work well
1544
1545 line-data | split-by (/s+/) {
1546
1547 # how do we deal with nonexistent?
1548 # should we also bind _parts or _words?
1549
1550 echo "$z | $0 | $1 | $z"
1551
1552 setvar count += 1
1553 }
1554 echo "count = $count"
1555}
1556
1557proc must-split-by (; ; ifs=null; block) {
1558 ### like if-split-by
1559
1560 echo TODO
1561}
1562
1563# Naming: each-match, each-split?
1564
1565proc if-match (; pattern, template=null; ; block=null) {
1566 ### like 'grep' but with submatches
1567
1568 for line in (io.stdin) {
1569 var m = line.search(pattern)
1570 if (m) {
1571 #pp asdl_ (m)
1572 #var groups = m.groups()
1573
1574 # Should we also pass _line?
1575
1576 if (block) {
1577 call io->eval(block, dollar0=m.group(0))
1578 } elif (template) {
1579 echo TEMPLATE
1580 } else {
1581 echo TSV
1582 }
1583 }
1584 }
1585
1586 # always succeeds - I think must-match is the one that can fail
1587}
1588
1589proc must-match (; pattern; block) {
1590 ### like if-match
1591
1592 echo TODO
1593}
1594
1595proc line-data {
1596 # note: trailing ''' issue, I should probably get rid of the last line
1597
1598 write --end '' -- '''
1599 prefix 30 foo
1600 oils
1601 /// 42 bar
1602 '''
1603}
1604
1605const pat = /<capture d+> s+ <capture w+>/
1606
1607proc test-if-match {
1608 var z = 'z' # test out scoping
1609 var count = 0 # test out mutation
1610
1611 # Test cases should be like:
1612 # grep: print the matches, or just count them
1613 # sed: print a new line based on submatches
1614 # awk: re-arrange the cols, and also accumulate counters
1615
1616 line-data | if-match (pat) {
1617 echo "$z $0 $z"
1618 # TODO: need pos_args
1619
1620 #echo "-- $2 $1 --"
1621
1622 setvar count += 1
1623 }
1624 echo "count = $count"
1625}
1626
1627proc test-if-match-2 {
1628 # If there's no block or template, it should print out a TSV with:
1629 #
1630 # $0 ...
1631 # $1 $2
1632 # $_line maybe?
1633
1634 #line-data | if-match (pat)
1635
1636 var z = 'z' # scoping
1637 line-data | if-match (pat, ^"$z $0 $z")
1638 line-data | if-match (pat, ^"-- $0 --")
1639}
1640
1641# might be a nice way to write it, not sure if byo.sh can discover it
1642if false {
1643tests 'if-match' {
1644 proc case-block {
1645 echo TODO
1646 }
1647 proc case-template {
1648 echo TODO
1649 }
1650}
1651}
1652
1653# Protocol:
1654#
1655# - The file lists its tests the "actions"
1656# - Then the test harness runs them
1657# - But should it be ENV vars
1658#
1659# - BYO_LIST_TESTS=1
1660# - BYO_RUN_TEST=foo
1661# - $PWD is a CLEAN temp dir, the process doesn't have to do anything
1662
1663# - silent on success, but prints file on output
1664# - OK this makes sense
1665#
1666# The trivial test in Python:
1667#
1668# from test import byo
1669# byo.maybe_main()
1670#
1671# bash library:
1672# source --builtin byo-server.sh
1673#
1674# byo-maybe-main # reads env variables, and then exits
1675#
1676# source --builtin assertions.ysh
1677#
1678# assert-ok 'echo hi'
1679# assert-stdout 'hi' 'echo -n hi'
1680#
1681# "$@"
1682#
1683# Run all tests
1684# util/byo-client.sh run-tests $YSH stdlib/table.ysh
1685# util/byo-client.sh run-tests -f x $YSH stdlib/table.ysh
1686
1687# Clean process
1688# Clean working dir
1689
1690#
1691# Stream Protocol:
1692# #.byo - is this she-dot, that's for a file
1693# Do we need metadata?
1694#
1695
1696# The harness
1697#
1698# It's process based testing.
1699#
1700# Test runner process: bash or OSH (unlike sharness!)
1701# Tested process: any language - bash,
1702#
1703# Key point: you don't have to quote shell code?
1704
1705list-byo-tests() {
1706 echo TODO
1707}
1708
1709run-byo-tests() {
1710 # source it
1711 echo TODO
1712}
1713
1714byo-maybe-run
1715)zZXx");
1716
1717GLOBAL_STR(gStr45, R"zZXx(# table.ysh - Library for tables.
1718#
1719# Usage:
1720# source --builtin table.ysh
1721
1722# make this file a test server
1723source --builtin osh/byo-server.sh
1724
1725proc table (...words; place; ; block) {
1726 var n = len(words)
1727
1728 # TODO: parse flags
1729 #
1730 # --by-row
1731 # --by-col
1732 #
1733 # Place is optional
1734
1735 if (n === 0) {
1736 echo TODO
1737 return
1738 }
1739
1740 var action = words[0]
1741
1742 # textual operations
1743 case (action) {
1744 cat {
1745 echo todo
1746 }
1747 align {
1748 echo todo
1749 }
1750 tabify {
1751 echo todo
1752 }
1753 tabify {
1754 echo todo
1755 }
1756 header {
1757 echo todo
1758 }
1759 slice {
1760 # this has typed args
1761 # do we do some sort of splat?
1762 echo todo
1763 }
1764 to-tsv {
1765 echo todo
1766 }
1767 }
1768
1769 echo TODO
1770}
1771
1772proc test-table {
1773 return
1774
1775 table (&files1) {
1776 cols num_bytes path
1777 type Int Str
1778
1779 row 10 README.md
1780 row 12 main.py
1781
1782 row (12, 'lib.py')
1783 row (num_bytes=12, path='util.py')
1784 }
1785
1786 # 2 columns - The default is by column?
1787 assert ['Dict' === type(files1)]
1788 assert [2 === len(files1)]
1789
1790 # Same table
1791 table --by-row (&files2) {
1792 cols num_bytes path
1793 type Int Str
1794
1795 row 10 README.md
1796 row 12 main.py
1797
1798 row (12, 'lib.py')
1799 row (num_bytes=12, path='util.py')
1800 }
1801
1802 # 4 rows
1803 assert ['List' === type(files2)]
1804 assert [4 === len(files2)]
1805}
1806
1807# "subcommands" of the dialect
1808
1809proc cols (...names) {
1810 # cols name age
1811 echo TODO
1812}
1813
1814proc types (...types) {
1815 # types - Int? Str?
1816 echo TODO
1817}
1818
1819proc attr (name; ...values) {
1820 # attr units ('-', 'secs')
1821 echo TODO
1822}
1823
1824# is this allowed outside table {} blocks too?
1825proc row {
1826 echo TODO
1827}
1828
1829#
1830# dplyr names
1831#
1832
1833# TODO: can we parse select?
1834
1835proc where {
1836 echo
1837}
1838
1839# TODO: should be able to test argv[0] or something
1840# Or pass to _mutate-transmute
1841
1842proc mutate {
1843 echo TODO
1844}
1845
1846proc transmute {
1847 echo TODO
1848}
1849
1850proc rename {
1851 echo TODO
1852}
1853
1854proc group-by {
1855 echo TODO
1856}
1857
1858proc sort-by {
1859 echo TODO
1860}
1861
1862proc summary {
1863 echo TODO
1864}
1865
1866byo-maybe-run
1867)zZXx");
1868
1869GLOBAL_STR(gStr46, R"zZXx(#!/usr/bin/env bash
1870#
1871# Testing library for bash and OSH.
1872#
1873# Capture status/stdout/stderr, and nq-assert those values.
1874
1875const __provide__ = :| yb-capture yb-capture-2 |
1876
1877: ${LIB_OSH=stdlib/osh}
1878source $LIB_OSH/two.sh
1879
1880# There is no yb-run, because you can just use try { } and inspect _error.code
1881# There is no yb-redir, because you can just use try >$tmp { } and inspect _error.code
1882
1883proc yb-capture(; out; ; block) {
1884 ### capture status and stdout
1885
1886 var stdout = ''
1887 try {
1888 { call io->eval(block) } | read --all (&stdout)
1889
1890 # Note that this doesn't parse because of expression issue:
1891 # call io->eval(block) | read --all (&stdout)
1892 # used to be eval (block)
1893 }
1894 # TODO: if 'block' contains a pipeline, we lose this magic var
1895 var result = {status: _pipeline_status[0], stdout}
1896
1897 #echo 'result-1'
1898 #pp test_ (result)
1899
1900 call out->setValue(result)
1901}
1902
1903proc yb-capture-2(; out; ; block) {
1904 ### capture status and stderr
1905
1906 var stderr = ''
1907 try {
1908 redir 2>&1 { call io->eval(block); } | read --all (&stderr)
1909
1910 # Note that this doesn't parse because of expression issue:
1911 # call io->eval(block) 2>&1 | read --all (&stderr)
1912 # used to be eval (block) 2>&1
1913 }
1914 #pp test_ (_pipeline_status)
1915
1916 var result = {status: _pipeline_status[0], stderr}
1917 #echo 'result-2'
1918 #pp test_ (result)
1919
1920 call out->setValue(result)
1921}
1922)zZXx");
1923
1924
1925
1926TextFile array[] = {
1927 {.rel_path = "_devbuild/help/data-errors", .contents = gStr0},
1928 {.rel_path = "_devbuild/help/data-front-end", .contents = gStr1},
1929 {.rel_path = "_devbuild/help/data-j8-notation", .contents = gStr2},
1930 {.rel_path = "_devbuild/help/help", .contents = gStr3},
1931 {.rel_path = "_devbuild/help/oils-usage", .contents = gStr4},
1932 {.rel_path = "_devbuild/help/osh-builtin-cmd", .contents = gStr5},
1933 {.rel_path = "_devbuild/help/osh-chapters", .contents = gStr6},
1934 {.rel_path = "_devbuild/help/osh-cmd-lang", .contents = gStr7},
1935 {.rel_path = "_devbuild/help/osh-front-end", .contents = gStr8},
1936 {.rel_path = "_devbuild/help/osh-mini-lang", .contents = gStr9},
1937 {.rel_path = "_devbuild/help/osh-option", .contents = gStr10},
1938 {.rel_path = "_devbuild/help/osh-osh-assign", .contents = gStr11},
1939 {.rel_path = "_devbuild/help/osh-plugin", .contents = gStr12},
1940 {.rel_path = "_devbuild/help/osh-special-var", .contents = gStr13},
1941 {.rel_path = "_devbuild/help/osh-stdlib", .contents = gStr14},
1942 {.rel_path = "_devbuild/help/osh-type-method", .contents = gStr15},
1943 {.rel_path = "_devbuild/help/osh-usage", .contents = gStr16},
1944 {.rel_path = "_devbuild/help/osh-word-lang", .contents = gStr17},
1945 {.rel_path = "_devbuild/help/ysh-builtin-cmd", .contents = gStr18},
1946 {.rel_path = "_devbuild/help/ysh-builtin-func", .contents = gStr19},
1947 {.rel_path = "_devbuild/help/ysh-chapters", .contents = gStr20},
1948 {.rel_path = "_devbuild/help/ysh-cmd-lang", .contents = gStr21},
1949 {.rel_path = "_devbuild/help/ysh-expr-lang", .contents = gStr22},
1950 {.rel_path = "_devbuild/help/ysh-front-end", .contents = gStr23},
1951 {.rel_path = "_devbuild/help/ysh-mini-lang", .contents = gStr24},
1952 {.rel_path = "_devbuild/help/ysh-option", .contents = gStr25},
1953 {.rel_path = "_devbuild/help/ysh-plugin", .contents = gStr26},
1954 {.rel_path = "_devbuild/help/ysh-special-var", .contents = gStr27},
1955 {.rel_path = "_devbuild/help/ysh-stdlib", .contents = gStr28},
1956 {.rel_path = "_devbuild/help/ysh-type-method", .contents = gStr29},
1957 {.rel_path = "_devbuild/help/ysh-usage", .contents = gStr30},
1958 {.rel_path = "_devbuild/help/ysh-word-lang", .contents = gStr31},
1959 {.rel_path = "_devbuild/help/ysh-ysh-cmd", .contents = gStr32},
1960 {.rel_path = "stdlib/methods.ysh", .contents = gStr33},
1961 {.rel_path = "stdlib/osh/bash-strict.sh", .contents = gStr34},
1962 {.rel_path = "stdlib/osh/byo-server.sh", .contents = gStr35},
1963 {.rel_path = "stdlib/osh/no-quotes.sh", .contents = gStr36},
1964 {.rel_path = "stdlib/osh/task-five.sh", .contents = gStr37},
1965 {.rel_path = "stdlib/osh/two.sh", .contents = gStr38},
1966 {.rel_path = "stdlib/prelude.ysh", .contents = gStr39},
1967 {.rel_path = "stdlib/ysh/args.ysh", .contents = gStr40},
1968 {.rel_path = "stdlib/ysh/def.ysh", .contents = gStr41},
1969 {.rel_path = "stdlib/ysh/list.ysh", .contents = gStr42},
1970 {.rel_path = "stdlib/ysh/math.ysh", .contents = gStr43},
1971 {.rel_path = "stdlib/ysh/stream.ysh", .contents = gStr44},
1972 {.rel_path = "stdlib/ysh/table.ysh", .contents = gStr45},
1973 {.rel_path = "stdlib/ysh/yblocks.ysh", .contents = gStr46},
1974
1975 {.rel_path = nullptr, .contents = nullptr},
1976};
1977
1978} // namespace embedded_file
1979
1980TextFile* gEmbeddedFiles = embedded_file::array; // turn array into pointer