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

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