OILS / _gen / bin / text_files.cc View on Github | oils.pub

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