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

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