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

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