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

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