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

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