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

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