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

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