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

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