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

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