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

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