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

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