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

1584 lines, 141 significant
1
2#include "cpp/embedded_file.h"
3
4namespace embedded_file {
5GLOBAL_STR(gStr0, R"zZXx(
6 Errors
7 <a class="group-link" href="chap-errors.html">errors</a>
8
9
10 [UTF8] err-utf8-encode err-utf8-decode
11 [J8 String] err-j8-str-encode err-j8-str-decode
12 [J8 Lines] err-j8-lines-encode err-j8-lines-decode
13 [JSON] err-json-encode err-json-decode
14 [JSON8] err-json8-encode err-json8-decode
15)zZXx");
16
17GLOBAL_STR(gStr1, R"zZXx(
18
19 Front End <a class="group-link" href="chap-front-end.html">front-end</a>
20
21
22 [Lexing] ascii-whitespace [ \t\r\n]
23 ascii-control-chars
24)zZXx");
25
26GLOBAL_STR(gStr2, R"zZXx(
27 J8 Notation
28 <a class="group-link" href="chap-j8.html">j8</a>
29
30
31 [J8 Strings] json-string "hi"
32 json-escape \" \\ \u1234
33 surrogate-pair \ud83e\udd26
34 j8-escape \' \u{1f926} \yff
35 u-prefix u'hi'
36 b-prefix b'hi'
37 no-prefix 'hi'
38 [J8 Lines] unquoted-line
39 [JSON8] json8-num json8-str
40 X json8-list X json8-dict
41 json8-comment
42 [TSV8] column-attrs column-types
43)zZXx");
44
45GLOBAL_STR(gStr3, R"zZXx(Usage: help TOPIC?
46
47Examples:
48
49 help # this help
50 help echo # help on the 'echo' builtin
51 help command-sub # help on command sub $(date)
52
53 help oils-usage # identical to oils-for-unix --help
54 help osh-usage # osh --help
55 help ysh-usage # ysh --help
56)zZXx");
57
58GLOBAL_STR(gStr4, R"zZXx(bin/oils-for-unix is an executable that contains OSH, YSH, and more.
59
60Usage: oils-for-unix MAIN_NAME ARG*
61 MAIN_NAME ARG*
62
63It behaves like busybox. The command name can be passed as the first argument:
64
65 oils-for-unix ysh -c 'echo hi'
66
67More commonly, it's invoked through a symlink like 'ysh', which causes it to
68behave like that command:
69
70 ysh -c 'echo hi'
71)zZXx");
72
73GLOBAL_STR(gStr5, R"zZXx(
74 Builtin Commands <a class="group-link" href="chap-builtin-cmd.html">builtin-cmd</a>
75
76
77 [I/O] read echo printf
78 readarray mapfile
79 [Run Code] source . eval trap
80 [Set Options] set shopt
81 [Working Dir] cd pwd pushd popd dirs
82 [Completion] complete compgen compopt compadjust compexport
83 [Shell Process] exec X logout
84 umask ulimit times
85 [Child Process] jobs wait
86 fg X bg X kill X disown
87 [External] test [ getopts
88 [Introspection] help hash cmd/type X caller
89 [Word Lookup] command builtin
90 [Interactive] alias unalias history X fc X bind
91X [Unsupported] enable
92)zZXx");
93
94GLOBAL_STR(gStr6, R"zZXx(The reference is divided in to "chapters", each of which has its own table of
95contents. Type:
96
97 help osh-$CHAPTER
98
99Where $CHAPTER is one of:
100
101 front-end
102 command-lang
103 osh-assign
104 word-lang
105 mini-lang
106 builtin-cmd
107 option
108 special-var
109 plugin
110
111Example:
112
113 help osh-word-lang
114)zZXx");
115
116GLOBAL_STR(gStr7, R"zZXx(
117 Command Language <a class="group-link" href="chap-cmd-lang.html">cmd-lang</a>
118
119
120 [Commands] simple-command semicolon ;
121 [Conditional] case if dbracket [[
122 true false colon :
123 bang ! and && or ||
124 [Iteration] while until for for-expr-sh ((
125 [Control Flow] break continue return exit
126 [Grouping] sh-func sh-block { subshell (
127 [Concurrency] pipe | X pipe-amp |& ampersand &
128 [Redirects] redir-file > >> >| < <> not impl: &>
129 redir-desc >& <&
130 here-doc << <<- <<<
131 [Other Command] dparen (( time X coproc X select
132)zZXx");
133
134GLOBAL_STR(gStr8, R"zZXx(
135 Front End <a class="group-link" href="chap-front-end.html">front-end</a>
136
137
138 [Usage] oils-usage osh-usage config
139 startup line-editing exit-codes
140 [Lexing] comment # line-continuation \ ascii-whitespace [ \t\r\n]
141)zZXx");
142
143GLOBAL_STR(gStr9, R"zZXx(
144 Other Mini Languages <a class="group-link" href="chap-mini-lang.html">mini-lang</a>
145
146
147 [Arithmetic] arith-context Where legacy arithmetic is allowed
148 sh-numbers 0xFF 0755 etc.
149 sh-arith 1 + 2*3 a *= 2
150 sh-logical !a && b
151 sh-bitwise ~a ^ b
152 [Boolean] bool-expr [[ ! $x && $y || $z ]]
153 test ! $x -a $y -o $z
154 bool-infix $a -nt $b $x == $y
155 bool-path -d /etc
156 bool-str -n foo -z ''
157 bool-other -o errexit -v name[index]
158 [Patterns] glob-pat *.py
159 extglob ,(*.py|*.sh)
160 regex [[ foo =~ [a-z]+ ]]
161 [Other Sublang] braces {alice,bob}@example.com
162 histsub !$ !! !n
163 char-escapes \t \c \x00 \u03bc
164)zZXx");
165
166GLOBAL_STR(gStr10, R"zZXx(
167 Global Shell Options <a class="group-link" href="chap-option.html">option</a>
168
169
170 [Errors] nounset -u errexit -e inherit_errexit pipefail
171 [Globbing] noglob -f nullglob failglob X dotglob
172 dashglob (true)
173 [Debugging] xtrace X verbose X extdebug
174 [Interactive] emacs vi
175 [Other POSIX] X noclobber
176 [Compat] eval_unsafe_arith ignore_flags_not_impl
177)zZXx");
178
179GLOBAL_STR(gStr11, R"zZXx(
180 Assignments and Expressions <a class="group-link" href="chap-osh-assign.html">osh-assign</a>
181
182
183 [Literals] sh-array array=(a b c) array[1]=B "${a[@]}"
184 sh-assoc assoc=(['a']=1 ['b']=2) assoc['x']=b
185 [Operators] sh-assign str='xyz'
186 sh-append str+='abc'
187 [Builtins] local readonly export unset shift
188 declare typeset X let
189)zZXx");
190
191GLOBAL_STR(gStr12, R"zZXx(
192 Plugins and Hooks <a class="group-link" href="chap-plugin.html">plugin</a>
193
194
195 [Signals] SIGTERM SIGINT SIGQUIT
196 SIGTTIN SIGTTOU SIGWINCH
197 [Traps] DEBUG ERR EXIT X RETURN
198 [Words] PS1 X PS2 X PS3 PS4
199 [Completion] complete
200 [Other Plugin] PROMPT_COMMAND X command_not_found
201)zZXx");
202
203GLOBAL_STR(gStr13, R"zZXx(
204 Special Variables <a class="group-link" href="chap-special-var.html">special-var</a>
205
206
207 [POSIX Special] $@ $* $# $? $- $$ $! $0 $9
208 [Shell Vars] IFS X LANG X GLOBIGNORE
209 [Shell Options] SHELLOPTS X BASHOPTS
210 [Other Env] HOME PATH
211 [Other Special] BASH_REMATCH @PIPESTATUS
212 [Platform] HOSTNAME OSTYPE
213 [Call Stack] @BASH_SOURCE @FUNCNAME @BASH_LINENO
214 X @BASH_ARGV X @BASH_ARGC
215 [Tracing] LINENO
216 [Process State] UID EUID PPID X BASHPID
217X [Process Stack] BASH_SUBSHELL SHLVL
218X [Shell State] BASH_CMDS @DIRSTACK
219 [Completion] @COMP_WORDS COMP_CWORD COMP_LINE COMP_POINT
220 COMP_WORDBREAKS @COMPREPLY X COMP_KEY
221 X COMP_TYPE COMP_ARGV
222 [History] HISTFILE
223 [cd] PWD OLDPWD X CDPATH
224 [getopts] OPTIND OPTARG X OPTERR
225 [read] REPLY
226 [Functions] X RANDOM SECONDS
227)zZXx");
228
229GLOBAL_STR(gStr14, R"zZXx(
230 Standard Library <a class="group-link" href="chap-stdlib.html">stdlib</a>
231
232
233 [two] log die
234)zZXx");
235
236GLOBAL_STR(gStr15, R"zZXx(
237 OSH Types <a class="group-link" href="chap-type-method.html">type-method</a>
238
239
240 [OSH] BashArray BashAssoc
241)zZXx");
242
243GLOBAL_STR(gStr16, R"zZXx(bin/osh is compatible with POSIX shell, bash, and other shells.
244
245Usage: osh FLAG* SCRIPT ARG*
246 osh FLAG* -c COMMAND ARG*
247 osh FLAG*
248
249The command line accepted by `bin/osh` is compatible with /bin/sh and bash.
250
251 osh -c 'echo hi'
252 osh myscript.sh
253 echo 'echo hi' | osh
254
255It also has a few enhancements:
256
257 osh -n -c 'hello' # pretty-print the AST
258 osh --ast-format text -n -c 'hello' # print it full
259
260osh accepts POSIX sh flags, with these additions:
261
262 -n parse the program but don't execute it. Print the AST.
263 --ast-format what format the AST should be in
264)zZXx");
265
266GLOBAL_STR(gStr17, R"zZXx(
267 Word Language <a class="group-link" href="chap-word-lang.html">word-lang</a>
268
269
270 [Quotes] osh-string 'abc' $'line\n' "$var"
271 [Substitutions] command-sub $(command) `command`
272 var-sub ${var} $0 $9
273 arith-sub $((1 + 2))
274 tilde-sub ~/src
275 proc-sub diff <(sort L.txt) <(sort R.txt)
276 [Var Ops] op-test ${x:-default}
277 op-strip ${x%%suffix} etc.
278 op-replace ${x//y/z}
279 op-index ${a[i+1}
280 op-slice ${a[@]:0:1}
281 op-format ${x@P}
282)zZXx");
283
284GLOBAL_STR(gStr18, R"zZXx(
285 Builtin Commands <a class="group-link" href="chap-builtin-cmd.html">builtin-cmd</a>
286
287
288 [Memory] cmd/append Add elements to end of array
289 pp asdl cell X gc-stats line proc
290 [Handle Errors] error error 'failed' (status=2)
291 try Run with errexit, set _error
292 failed Test if _error.code !== 0
293 boolstatus Enforce 0 or 1 exit status
294 [Shell State] ysh-cd ysh-shopt compatible, and takes a block
295 shvar Temporary modify global settings
296 ctx Share and update a temporary "context"
297 push-registers Save registers like $?, PIPESTATUS
298 [Modules] runproc Run a proc; use as main entry point
299 module guard against duplicate 'source'
300 is-main false when sourcing a file
301 use change first word lookup
302 [I/O] ysh-read flags --all, -0
303 ysh-echo no -e -n with simple_echo
304 write Like echo, with --, --sep, --end
305 fork forkwait Replace & and (), and takes a block
306 fopen Open multiple streams, takes a block
307 X dbg Only thing that can be used in funcs
308 [Hay Config] hay haynode For DSLs and config files
309 [Completion] compadjust compexport
310 [Data Formats] json read write
311 json8 read write
312X [Testing] assert takes an expression
313)zZXx");
314
315GLOBAL_STR(gStr19, R"zZXx(
316 Builtin Functions <a class="group-link" href="chap-builtin-func.html">builtin-func</a>
317
318
319 [Values] len() func/type() X repeat()
320 [Conversions] bool() int() float() str() list() dict()
321 X runes() X encodeRunes()
322 X bytes() X encodeBytes()
323 [Str] X strcmp() X split() shSplit()
324 [List] join() any() all()
325 [Collections] X copy() X deepCopy()
326 [Word] glob() maybe()
327 [Math] abs() max() min() X round() sum()
328 [Serialize] toJson() fromJson()
329 toJson8() fromJson8()
330X [J8 Decode] J8.Bool() J8.Int() ...
331 [Pattern] _group() _start() _end()
332 [Introspection] shvarGet() getVar() evalExpr()
333 [Hay Config] parseHay() evalHay()
334X [Hashing] sha1dc() sha256()
335)zZXx");
336
337GLOBAL_STR(gStr20, R"zZXx(The reference is divided in to "chapters", each of which has its own table of
338contents. Type:
339
340 help ysh-$CHAPTER
341
342Where $CHAPTER is one of:
343
344 front-end
345 command-lang
346 expr-lang
347 word-lang
348 builtin-cmd
349 option
350 special-var
351 type-method
352 builtin-func
353
354Example:
355
356 help ysh-expr-lang
357)zZXx");
358
359GLOBAL_STR(gStr21, R"zZXx(
360 Command Language <a class="group-link" href="chap-cmd-lang.html">cmd-lang</a>
361
362
363 [YSH Simple] typed-arg json write (x)
364 lazy-expr-arg assert [42 === x]
365 block-arg cd /tmp { echo $PWD }; cd /tmp (; ; blockexpr)
366 [YSH Cond] ysh-case case (x) { *.py { echo 'python' } }
367 ysh-if if (x > 0) { echo }
368 [YSH Iter] ysh-while while (x > 0) { echo }
369 ysh-for for i, item in (mylist) { echo }
370)zZXx");
371
372GLOBAL_STR(gStr22, R"zZXx(
373 Expression Language and Assignments <a class="group-link" href="chap-expr-lang.html">expr-lang</a>
374
375
376 [Assignment] assign =
377 aug-assign += -= *= /= **= //= %=
378 &= |= ^= <<= >>=
379 [Literals] atom-literal true false null
380 int-literal 42 65_536 0xFF 0o755 0b10
381 float-lit 3.14 1.5e-10
382 X num-suffix 42 K Ki M Mi G Gi T Ti / ms us
383 ysh-string "x is $x" $"x is $x" r'[a-z]\n'
384 u'line\n' b'byte \yff'
385 triple-quoted """ $""" r''' u''' b'''
386 str-template ^"$a and $b" for Str::replace()
387 list-literal ['one', 'two', 3] :| unquoted words |
388 dict-literal {name: 'bob'} {a, b}
389 range 1 .. n+1
390 block-expr ^(echo $PWD)
391 expr-literal ^[1 + 2*3]
392 X expr-sub $[myobj]
393 X expr-splice @[myobj]
394 [Operators] op-precedence Like Python
395 concat s1 ++ s2, L1 ++ L2
396 ysh-equals === !== ~== is, is not
397 ysh-in in, not in
398 ysh-compare < <= > >= (numbers only)
399 ysh-logical not and or
400 ysh-arith + - * / // % **
401 ysh-bitwise ~ & | ^ << >>
402 ysh-ternary '+' if x >= 0 else '-'
403 ysh-index s[0] mylist[3] mydict['key']
404 ysh-attr mydict.key
405 ysh-slice a[1:-1] s[1:-1]
406 func-call f(x, y; ...named)
407 thin-arrow mylist->pop()
408 fat-arrow mystr => startsWith('prefix')
409 match-ops ~ !~ ~~ !~~
410 [Eggex] re-literal / d+ ; re-flags ; ERE /
411 re-primitive %zero 'sq'
412 class-literal [c a-z 'abc' @str_var \\ \xFF \u0100]
413 named-class dot digit space word d s w
414 re-repeat d? d* d+ d{3} d{2,4}
415 re-compound seq1 seq2 alt1|alt2 (expr1 expr2)
416 re-capture <capture d+ as name: int>
417 re-splice Subpattern @subpattern
418 re-flags reg_icase reg_newline
419 X re-multiline ///
420)zZXx");
421
422GLOBAL_STR(gStr23, R"zZXx(
423 Front End <a class="group-link" href="chap-front-end.html">front-end</a>
424
425
426 [Usage] oils-usage ysh-usage
427 [Lexing] ascii-whitespace [ \t\r\n]
428 doc-comment ### multiline-command ...
429 [Tools] cat-em
430)zZXx");
431
432GLOBAL_STR(gStr24, R"zZXx(
433 Other Mini Languages <a class="group-link" href="chap-mini-lang.html">mini-lang</a>
434
435
436 [Patterns] glob-pat *.py
437 [Other Sublang] braces {alice,bob}@example.com
438)zZXx");
439
440GLOBAL_STR(gStr25, R"zZXx(
441 Global Shell Options <a class="group-link" href="chap-option.html">option</a>
442
443
444 [Groups] strict:all ysh:upgrade ysh:all
445 [YSH Details] opts-redefine opts-internal
446)zZXx");
447
448GLOBAL_STR(gStr26, R"zZXx(
449 Plugins and Hooks <a class="group-link" href="chap-plugin.html">plugin</a>
450
451
452 [YSH] renderPrompt()
453)zZXx");
454
455GLOBAL_STR(gStr27, R"zZXx(
456 Special Variables <a class="group-link" href="chap-special-var.html">special-var</a>
457
458
459 [YSH Vars] ARGV X ENV X _ESCAPE
460 _this_dir
461 [YSH Status] _error
462 _pipeline_status _process_sub_status
463 [YSH Tracing] SHX_indent SHX_punct SHX_pid_str
464 [YSH read] _reply
465 [History] YSH_HISTFILE
466 [Oils VM] OILS_VERSION
467 OILS_GC_THRESHOLD OILS_GC_ON_EXIT
468 OILS_GC_STATS OILS_GC_STATS_FD
469)zZXx");
470
471GLOBAL_STR(gStr28, R"zZXx(
472 Standard Library<a class="group-link" href="chap-stdlib.html">stdlib</a>
473
474
475 [Args Parser] parser Parse command line arguments
476 flag
477 arg
478 rest
479 parseArgs()
480X [Testing] describe Test harness
481X [Lines] slurp-by combine adjacent lines into cells
482X [Awk] each-line --j8 --max-jobs (Str, Template, Block) - xargs
483 each-row --max-jobs (Str, Template, Block) - xargs
484 split-by (str=\n, ifs=':', pattern=/s+/)
485 if-split-by
486 chop alias for split-by (pattern=/s+/)
487 must-match (/ <capture d+> </capture w+> /)
488 if-match
489X [Table Create] table --by-row --by-col (&place); construct/parse a table
490 table/cols cols name age - cols name:Str age:Int
491 types type Str Int
492 attr attr units - secs
493 row emit row
494 table cat concatenate TSV8
495 table align to ssv8
496 table tabify to tsv8
497 table header (cols = :|name age|, types = :|Str Int|, units = :|- secs|)
498 table slice e.g. slice (1, -1) slice (5, 7)
499 table to-tsv lose type info, and error on \t in cells
500X [Table Ops] where subset of rows; dplyr filter()
501 pick subset of columns ('select' taken by shell)
502 mutate transmute [average = count / sum] - drop the ones that are used?
503 rename (bytes='bytes', path='filename')
504 group-by add a column with a group ID [ext]
505 sort-by sort by columns; dplyr arrange() [ext]
506 summary count, sum, histogram, any, all, reduce(), etc. [ext]
507)zZXx");
508
509GLOBAL_STR(gStr29, R"zZXx(
510 Types and Methods <a class="group-link" href="chap-type-method.html">type-method</a>
511
512
513 [Atom Types] Null Bool
514 [Number Types] Int Float
515 [Str] X find() replace()
516 trim() trimStart() trimEnd()
517 startsWith() endsWith()
518 upper() lower()
519 search() leftMatch()
520 [List] List/append() pop() extend() indexOf()
521 X insert() X remove() reverse()
522 [Dict] keys() values() X get() X erase()
523 X inc() X accum()
524 [Range]
525 [Eggex]
526 [Match] group() start() end()
527 X groups() X groupDict()
528 [Place] setValue()
529 [Code Types] Expr Command
530 BuiltinFunc BoundFunc
531X [Func] name() location() toJson()
532X [Proc] name() location() toJson()
533X [Module] name() filename()
534 [IO] X eval() X captureStdout()
535 promptVal()
536 X time() X strftime()
537 X glob()
538X [Guts] heapId()
539)zZXx");
540
541GLOBAL_STR(gStr30, R"zZXx(bin/ysh is the shell with data tYpes, influenced by pYthon, JavaScript, ...
542
543Usage: ysh FLAG* SCRIPT ARG*
544 ysh FLAG* -c COMMAND ARG*
545 ysh FLAG*
546
547`bin/ysh` is the same as `bin/osh` with a the `ysh:all` option group set. So
548`bin/ysh` also accepts shell flags.
549
550 ysh -c 'echo hi'
551 ysh myscript.ysh
552 echo 'echo hi' | ysh
553)zZXx");
554
555GLOBAL_STR(gStr31, R"zZXx(
556 Word Language <a class="group-link" href="chap-word-lang.html">word-lang</a>
557
558
559 [Quotes] ysh-string "x is $x" $"x is $x" r'[a-z]\n'
560 u'line\n' b'byte \yff'
561 triple-quoted """ $""" r''' u''' b'''
562 X tagged-str "<span id=$x>"html
563 [Substitutions] expr-sub echo $[42 + a[i]]
564 expr-splice echo @[split(x)]
565 var-splice @myarray @ARGV
566 command-sub @(split command)
567 [Formatting] X ysh-printf ${x %.3f}
568 X ysh-format ${x|html}
569)zZXx");
570
571GLOBAL_STR(gStr32, R"zZXx(
572 YSH Command Language Keywords <a class="group-link" href="chap-ysh-cmd.html">ysh-cmd</a>
573
574
575 [Assignment] const var Declare variables
576 setvar setvar a[i] = 42
577 setglobal setglobal d.key = 'foo'
578 [Expression] equal = = 1 + 2*3
579 call call mylist->append(42)
580 [Definitions] proc proc p (s, ...rest) {
581 typed proc p (; typed, ...rest; n=0; b) {
582 func func f(x; opt1, opt2) { return (x + 1) }
583 ysh-return return (myexpr)
584)zZXx");
585
586GLOBAL_STR(gStr33, R"zZXx(#!/usr/bin/env bash
587#
588# Run tests in this directory.
589#
590# Usage:
591# stdlib/TEST.sh <function name>
592
593set -o nounset
594set -o pipefail
595set -o errexit
596
597YSH=bin/ysh
598
599test-byo-protocol() {
600 return
601
602 # Usually the "BYO" command does this
603 BYO_COMMAND=detect $YSH stdlib/table.ysh
604
605 # TODO: need assertions here
606 # assert status
607
608 # assert-ok 'echo hi'
609 # assert-stdout 'echo hi'
610 # assert-fail 2 '(exit 2)'
611
612 # I think we usually don't need this
613 # assert-fail-stdout 2 '(exit 2)'
614
615 BYO_COMMAND=z $YSH stdlib/table.ysh
616
617 # missing
618 BYO_COMMAND=run-test $YSH stdlib/table.ysh
619
620 # TODO: test file with no tests
621}
622
623soil-run() {
624 test-byo-protocol
625
626 test/byo-client.sh run-tests $YSH stdlib/stream.ysh
627
628 test/byo-client.sh run-tests $YSH stdlib/table.ysh
629
630 # I guess this needs tests, with an assertion library for stdout?
631
632 # TODO: if there are no tests, it should fail
633 # test/byo-client.sh run-tests $SH stdlib/two.sh
634}
635
636
637
638"$@"
639)zZXx");
640
641GLOBAL_STR(gStr34, R"zZXx(# args.ysh
642#
643# Usage:
644# source --builtin args.sh
645#
646# parser (&spec) {
647# flag -v --verbose (help="Verbosely") # default is Bool, false
648#
649# flag -P --max-procs ('int', default=-1, doc='''
650# Run at most P processes at a time
651# ''')
652#
653# flag -i --invert ('bool', default=true, doc='''
654# Long multiline
655# Description
656# ''')
657#
658# arg src (help='Source')
659# arg dest (help='Dest')
660# arg times (help='Foo')
661#
662# rest files
663# }
664#
665# var args = parseArgs(spec, ARGV)
666#
667# echo "Verbose $[args.verbose]"
668
669# TODO: See list
670# - It would be nice to keep `flag` and `arg` private, injecting them into the
671# proc namespace only within `Args`
672# - We need "type object" to replace the strings 'int', 'bool', etc.
673# - flag builtin:
674# - handle only long flag or only short flag
675# - flag aliases
676
677proc parser (; place ; ; block_def) {
678 ## Create an args spec which can be passed to parseArgs.
679 ##
680 ## Example:
681 ##
682 ## # NOTE: &spec will create a variable named spec
683 ## parser (&spec) {
684 ## flag -v --verbose ('bool')
685 ## }
686 ##
687 ## var args = parseArgs(spec, ARGV)
688
689 var p = {flags: [], args: []}
690 ctx push (p; ; block_def)
691
692 # Validate that p.rest = [name] or null and reduce p.rest into name or null.
693 if ('rest' in p) {
694 if (len(p.rest) > 1) {
695 error '`rest` was called more than once' (code=3)
696 } else {
697 setvar p.rest = p.rest[0]
698 }
699 } else {
700 setvar p.rest = null
701 }
702
703 var names = {}
704 for items in ([p.flags, p.args]) {
705 for x in (items) {
706 if (x.name in names) {
707 error "Duplicate flag/arg name $[x.name] in spec" (code=3)
708 }
709
710 setvar names[x.name] = null
711 }
712 }
713
714 # TODO: what about `flag --name` and then `arg name`?
715
716 call place->setValue(p)
717}
718
719proc flag (short, long ; type='bool' ; default=null, help=null) {
720 ## Declare a flag within an `arg-parse`.
721 ##
722 ## Examples:
723 ##
724 ## arg-parse (&spec) {
725 ## flag -v --verbose
726 ## flag -n --count ('int', default=1)
727 ## flag -f --file ('str', help="File to process")
728 ## }
729
730 # bool has a default of false, not null
731 if (type === 'bool' and default === null) {
732 setvar default = false
733 }
734
735 # TODO: validate `type`
736
737 # TODO: Should use "trimPrefix"
738 var name = long[2:]
739
740 ctx emit flags ({short, long, name, type, default, help})
741}
742
743proc arg (name ; ; help=null) {
744 ## Declare a positional argument within an `arg-parse`.
745 ##
746 ## Examples:
747 ##
748 ## arg-parse (&spec) {
749 ## arg name
750 ## arg config (help="config file path")
751 ## }
752
753 ctx emit args ({name, help})
754}
755
756proc rest (name) {
757 ## Take the remaining positional arguments within an `arg-parse`.
758 ##
759 ## Examples:
760 ##
761 ## arg-parse (&grepSpec) {
762 ## arg query
763 ## rest files
764 ## }
765
766 # We emit instead of set to detect multiple invocations of "rest"
767 ctx emit rest (name)
768}
769
770func parseArgs(spec, argv) {
771 ## Given a spec created by `parser`. Parse an array of strings `argv` per
772 ## that spec.
773 ##
774 ## See `parser` for examples of use.
775
776 var i = 0
777 var positionalPos = 0
778 var argc = len(argv)
779 var args = {}
780 var rest = []
781
782 var value
783 var found
784 while (i < argc) {
785 var arg = argv[i]
786 if (arg->startsWith('-')) {
787 setvar found = false
788
789 for flag in (spec.flags) {
790 if ( (flag.short and flag.short === arg) or
791 (flag.long and flag.long === arg) ) {
792 case (flag.type) {
793 ('bool') | (null) { setvar value = true }
794 int {
795 setvar i += 1
796 if (i >= len(argv)) {
797 error "Expected integer after '$arg'" (code=2)
798 }
799
800 try { setvar value = int(argv[i]) }
801 if (_status !== 0) {
802 error "Expected integer after '$arg', got '$[argv[i]]'" (code=2)
803 }
804 }
805 }
806
807 setvar args[flag.name] = value
808 setvar found = true
809 break
810 }
811 }
812
813 if (not found) {
814 error "Unknown flag '$arg'" (code=2)
815 }
816 } elif (positionalPos >= len(spec.args)) {
817 if (not spec.rest) {
818 error "Too many arguments, unexpected '$arg'" (code=2)
819 }
820
821 call rest->append(arg)
822 } else {
823 var pos = spec.args[positionalPos]
824 setvar positionalPos += 1
825 setvar value = arg
826 setvar args[pos.name] = value
827 }
828
829 setvar i += 1
830 }
831
832 if (spec.rest) {
833 setvar args[spec.rest] = rest
834 }
835
836 # Set defaults for flags
837 for flag in (spec.flags) {
838 if (flag.name not in args) {
839 setvar args[flag.name] = flag.default
840 }
841 }
842
843 # Raise error on missing args
844 for arg in (spec.args) {
845 if (arg.name not in args) {
846 error "Usage Error: Missing required argument $[arg.name]" (code=2)
847 }
848 }
849
850 return (args)
851}
852)zZXx");
853
854GLOBAL_STR(gStr35, R"zZXx(# Library to turn a file into a "BYO test server"
855#
856# Usage:
857# source --builtin test/byo-server-lib.sh # from Oils
858# source test/byo-server-lib.sh # can be used with bash
859#
860# The client creates a clean process state and directory state for each tests.
861#
862# (It relies on compgen -A, and maybe declare -f, so it's not POSIX shell.)
863
864# TODO: How do I get stdlib/two.sh
865log() {
866 echo "$@" >& 2
867}
868
869die() {
870 log "$0: fatal: $@"
871 exit 1
872}
873
874
875byo-maybe-main() {
876 local command=${BYO_COMMAND:-}
877
878 case $command in
879 '')
880 # Do nothing if it's not specified
881 return
882 ;;
883
884 detect)
885 # all the commands supported, except 'detect'
886 echo list-tests
887 echo run-test
888
889 exit 66 # ASCII code for 'B' - what the protocol specifies
890 ;;
891
892 list-tests)
893 # bash extension that OSH also implements
894 compgen -A function | grep '^test-'
895 exit 0
896 ;;
897
898 run-test)
899 local test_name=${BYO_ARG:-}
900 if test -z "$test_name"; then
901 die "BYO run-test: Expected BYO_ARG"
902 fi
903
904 # Shell convention: we name functions test-*
905 $test_name
906
907 # Only run if not set -e. Either way it's equivalent
908 exit $?
909 ;;
910
911 *)
912 die "Invalid BYO command '$command'"
913 ;;
914 esac
915
916 # Do nothing if BYO_COMMAND is not set.
917 # The program continues to its "main".
918}
919)zZXx");
920
921GLOBAL_STR(gStr36, R"zZXx(func identity(x) {
922 ## The identity function. Returns its argument.
923
924 return (x)
925}
926)zZXx");
927
928GLOBAL_STR(gStr37, R"zZXx(func any(list) {
929 ## Returns true if any value in the list is truthy.
930 ##
931 ## If the list is empty, return false.
932
933 for item in (list) {
934 if (item) {
935 return (true)
936 }
937 }
938 return (false)
939}
940
941func all(list) {
942 ## Returns true if all values in the list are truthy.
943 ##
944 ## If the list is empty, return true.
945
946 for item in (list) {
947 if (not item) {
948 return (false)
949 }
950 }
951 return (true)
952}
953
954func sum(list; start=0) {
955 ## Computes the sum of all elements in the list.
956 ##
957 ## Returns 0 for an empty list.
958
959 var sum = start
960 for item in (list) {
961 setvar sum += item
962 }
963 return (sum)
964}
965)zZXx");
966
967GLOBAL_STR(gStr38, R"zZXx(func __math_select(list, cmp) {
968 ## Internal helper for `max` and `min`.
969 ##
970 ## NOTE: If `list` is empty, then an error is thrown.
971
972 if (len(list) === 0) {
973 error "Unexpected empty list" (code=3)
974 }
975
976 if (len(list) === 1) {
977 return (list[0])
978 }
979
980 var match = list[0]
981 for i in (1 .. len(list)) {
982 setvar match = cmp(list[i], match)
983 }
984 return (match)
985}
986
987func max(...args) {
988 ## Compute the maximum of 2 or more values.
989 ##
990 ## `max` takes two different signatures:
991 ## - `max(a, b)` to return the maximum of `a`, `b`
992 ## - `max(list)` to return the greatest item in the `list`
993 ##
994 ## So, for example:
995 ##
996 ## max(1, 2) # => 2
997 ## max([1, 2, 3]) # => 3
998
999 case (len(args)) {
1000 (1) { return (__math_select(args[0], max)) }
1001 (2) {
1002 if (args[0] > args[1]) {
1003 return (args[0])
1004 } else {
1005 return (args[1])
1006 }
1007 }
1008 (else) { error "max expects 1 or 2 args" (code=3) }
1009 }
1010}
1011
1012func min(...args) {
1013 ## Compute the minimum of 2 or more values.
1014 ##
1015 ## `min` takes two different signatures:
1016 ## - `min(a, b)` to return the minimum of `a`, `b`
1017 ## - `min(list)` to return the least item in the `list`
1018 ##
1019 ## So, for example:
1020 ##
1021 ## min(2, 3) # => 2
1022 ## max([1, 2, 3]) # => 1
1023
1024 case (len(args)) {
1025 (1) { return (__math_select(args[0], min)) }
1026 (2) {
1027 if (args[0] < args[1]) {
1028 return (args[0])
1029 } else {
1030 return (args[1])
1031 }
1032 }
1033 (else) { error "min expects 1 or 2 args" (code=3) }
1034 }
1035}
1036
1037func abs(x) {
1038 ## Compute the absolute (positive) value of a number (float or int).
1039
1040 if (x < 0) {
1041 return (-x)
1042 } else {
1043 return (x)
1044 }
1045}
1046)zZXx");
1047
1048GLOBAL_STR(gStr39, R"zZXx(# Can we define methods in pure YSH?
1049#
1050# (mylist->find(42) !== -1)
1051#
1052# instead of
1053#
1054# ('42' in mylist)
1055#
1056# Because 'in' is for Dict
1057
1058func find (haystack List, needle) {
1059 for i, x in (haystack) {
1060 if (x === needle) {
1061 return (i)
1062 }
1063 }
1064 return (-1)
1065}
1066)zZXx");
1067
1068GLOBAL_STR(gStr40, R"zZXx(# These were helpful while implementing args.ysh
1069# Maybe we will want to export them in a prelude so that others can use them too?
1070#
1071# Prior art: Rust has `todo!()` which is quite nice. Other languages allow
1072# users to `raise NotImplmentedError()`.
1073
1074# Andy comments:
1075# - 'pass' can be : or true in shell. It's a little obscure / confusing, but
1076# there is an argument for minimalism. Although I prefer words like 'true',
1077# and that already means something.
1078# - UPDATE: we once took 'pass' as a keyword, but users complained because
1079# there is a command 'pass'. So we probably can't have this by default.
1080# Need to discuss source --builtin.
1081
1082# - todo could be more static? Rust presumably does it at compile time
1083
1084proc todo () {
1085 ## Raises a not implemented error when run.
1086 error ("TODO: not implemented") # TODO: is error code 1 ok?
1087}
1088
1089proc pass () {
1090 ## Use when you want to temporarily leave a block empty.
1091 _ null
1092}
1093)zZXx");
1094
1095GLOBAL_STR(gStr41, R"zZXx(# stream.ysh
1096#
1097# Usage:
1098# source --builtin stream.ysh
1099#
1100# For reading lines, decoding, extracting, splitting
1101
1102# make this file a test server
1103source --builtin byo-server-lib.sh
1104
1105source --builtin args.ysh
1106
1107proc slurp-by (; num_lines) {
1108 # TODO: (stdin)
1109 for line in <> {
1110 echo TODO
1111 }
1112}
1113
1114# Note:
1115# - these are all the same algorithm
1116# - also word, block, etc. are all optional
1117
1118proc each-line (...words; template=null; ; block=null) {
1119 # TODO:
1120 # parse --j8 --max-jobs flag
1121
1122 # parse template_str as string
1123 # TODO: this is dangerous though ... because you can execute code
1124 # I think you need a SAFE version
1125
1126 # evaluate template string expression - I guess that allows $(echo hi) and so
1127 # forth
1128
1129 # evaluate block with _line binding
1130 # block: execute in parallel with --max-jobs
1131
1132 for line in <> {
1133 echo TODO
1134 }
1135}
1136
1137proc test-each-line {
1138 echo 'TODO: need basic test runner'
1139
1140 # ysh-tool test stream.ysh
1141 #
1142 # Col
1143
1144
1145}
1146
1147proc each-row (; ; block) {
1148 echo TODO
1149}
1150
1151proc split-by (; ifs=null; block) {
1152 echo TODO
1153}
1154
1155proc if-split-by (; ifs=null; block) {
1156 echo TODO
1157}
1158
1159proc chop () {
1160 ### alias for if-split-by
1161 echo TODO
1162}
1163
1164proc must-match (; pattern; block) {
1165 echo TODO
1166}
1167
1168proc if-match (; pattern; block) {
1169 echo TODO
1170}
1171
1172# Protocol:
1173#
1174# - The file lists its tests the "actions"
1175# - Then the test harness runs them
1176# - But should it be ENV vars
1177#
1178# - BYO_LIST_TESTS=1
1179# - BYO_RUN_TEST=foo
1180# - $PWD is a CLEAN temp dir, the process doesn't have to do anything
1181
1182# - silent on success, but prints file on output
1183# - OK this makes sense
1184#
1185# The trivial test in Python:
1186#
1187# from test import byo
1188# byo.maybe_main()
1189#
1190# bash library:
1191# source --builtin byo-server.sh
1192#
1193# byo-maybe-main # reads env variables, and then exits
1194#
1195# source --builtin assertions.ysh
1196#
1197# assert-ok 'echo hi'
1198# assert-stdout 'hi' 'echo -n hi'
1199#
1200# "$@"
1201#
1202# Run all tests
1203# util/byo-client.sh run-tests $YSH stdlib/table.ysh
1204# util/byo-client.sh run-tests -f x $YSH stdlib/table.ysh
1205
1206# Clean process
1207# Clean working dir
1208
1209#
1210# Stream Protocol:
1211# #.byo - is this she-dot, that's for a file
1212# Do we need metadata?
1213#
1214
1215# The harness
1216#
1217# It's process based testing.
1218#
1219# Test runner process: bash or OSH (unlike sharness!)
1220# Tested process: any language - bash,
1221#
1222# Key point: you don't have to quote shell code?
1223
1224list-byo-tests() {
1225 echo TODO
1226}
1227
1228run-byo-tests() {
1229 # source it
1230 echo TODO
1231}
1232
1233byo-maybe-main
1234)zZXx");
1235
1236GLOBAL_STR(gStr42, R"zZXx(# table.ysh - Library for tables.
1237#
1238# Usage:
1239# source --builtin table.ysh
1240
1241# make this file a test server
1242source --builtin byo-server-lib.sh
1243
1244proc table (...words; place; ; block) {
1245 var n = len(words)
1246
1247 # TODO: parse flags
1248 #
1249 # --by-row
1250 # --by-col
1251 #
1252 # Place is optional
1253
1254 if (n === 0) {
1255 echo TODO
1256 return
1257 }
1258
1259 var action = words[0]
1260
1261 # textual operations
1262 case (action) {
1263 cat {
1264 echo todo
1265 }
1266 align {
1267 echo todo
1268 }
1269 tabify {
1270 echo todo
1271 }
1272 tabify {
1273 echo todo
1274 }
1275 header {
1276 echo todo
1277 }
1278 slice {
1279 # this has typed args
1280 # do we do some sort of splat?
1281 echo todo
1282 }
1283 to-tsv {
1284 echo todo
1285 }
1286 }
1287
1288 echo TODO
1289}
1290
1291proc test-table {
1292 return
1293
1294 table (&files1) {
1295 cols num_bytes path
1296 type Int Str
1297
1298 row 10 README.md
1299 row 12 main.py
1300
1301 row (12, 'lib.py')
1302 row (num_bytes=12, path='util.py')
1303 }
1304
1305 # 2 columns - The default is by column?
1306 assert ['Dict' === type(files1)]
1307 assert [2 === len(files1)]
1308
1309 # Same table
1310 table --by-row (&files2) {
1311 cols num_bytes path
1312 type Int Str
1313
1314 row 10 README.md
1315 row 12 main.py
1316
1317 row (12, 'lib.py')
1318 row (num_bytes=12, path='util.py')
1319 }
1320
1321 # 4 rows
1322 assert ['List' === type(files2)]
1323 assert [4 === len(files2)]
1324}
1325
1326# "subcommands" of the dialect
1327
1328proc cols (...names) {
1329 # cols name age
1330 echo TODO
1331}
1332
1333proc types (...types) {
1334 # types - Int? Str?
1335 echo TODO
1336}
1337
1338proc attr (name; ...values) {
1339 # attr units ('-', 'secs')
1340 echo TODO
1341}
1342
1343# is this allowed outside table {} blocks too?
1344proc row {
1345 echo TODO
1346}
1347
1348#
1349# dplyr names
1350#
1351
1352# TODO: can we parse select?
1353
1354proc where {
1355 echo
1356}
1357
1358# TODO: should be able to test argv[0] or something
1359# Or pass to _mutate-transmute
1360
1361proc mutate {
1362 echo TODO
1363}
1364
1365proc transmute {
1366 echo TODO
1367}
1368
1369proc rename {
1370 echo TODO
1371}
1372
1373proc group-by {
1374 echo TODO
1375}
1376
1377proc sort-by {
1378 echo TODO
1379}
1380
1381proc summary {
1382 echo TODO
1383}
1384
1385byo-maybe-main
1386)zZXx");
1387
1388GLOBAL_STR(gStr43, R"zZXx(# testing.ysh
1389#
1390# Usage:
1391# source --builtin testing.sh
1392#
1393# func f(x) { return (x + 1) }
1394#
1395# describe foo {
1396# assert (43 === f(42))
1397# }
1398#
1399# if is-main {
1400# run-tests @ARGV # --filter
1401# }
1402
1403module stdlib/testing || return 0
1404
1405source --builtin args.ysh
1406
1407proc assert ( ; cond ; fail_message='default fail message') {
1408 echo 'hi from assert'
1409
1410 = cond
1411
1412 # I think this might be ready now?
1413
1414 var val = evalExpr(cond)
1415
1416 echo
1417 echo 'value'
1418 = val
1419 pp line (val)
1420
1421 = fail_message
1422
1423 if (val) {
1424 echo 'OK'
1425 } else {
1426 var m = evalExpr(fail_message)
1427 echo "FAIL - this is where we extract the string - $m"
1428 }
1429}
1430
1431proc test-assert {
1432 var x = 42
1433 assert [42 === x]
1434}
1435
1436proc test-expr ( ; expr ) {
1437 echo 'expr'
1438 pp line (expr)
1439}
1440
1441proc test-named ( ; ; n=^[99] ) {
1442 echo 'n'
1443 pp line (n)
1444}
1445
1446# What happens when there are duplicate test IDs?
1447#
1448# Also I think filter by "$test_id/$case_id"
1449
1450proc __it (case_id ; ; ; block) {
1451 # This uses a clean directory
1452 echo TODO
1453}
1454
1455# is this accessible to users?
1456# It can contain a global list of things to run
1457
1458# Naming convention: a proc named 'describe' mutates a global named _describe?
1459# Or maybe _describe_list ?
1460
1461var _describe_list = []
1462
1463proc describe (test_id ; ; ; block) {
1464 echo describe
1465 #= desc
1466
1467 # TODO:
1468 # - need append
1469 # - need ::
1470 # _ _describe->append(cmd)
1471 #
1472 # Need to clean this up
1473 # append (_describe, cmd) # does NOT work!
1474
1475 call _describe_list->append(block)
1476}
1477
1478proc Args {
1479 echo TODO
1480}
1481
1482# Problem: this creates a global variable?
1483Args (&spec) {
1484 flag --filter 'Regex of test descriptions'
1485}
1486
1487proc run-tests {
1488 var opt, i = parseArgs(spec, ARGV)
1489
1490 # TODO:
1491 # - parse --filter foo, which you can use eggex for!
1492
1493 for cmd in (_describe) {
1494 # TODO: print filename and 'describe' name?
1495 try {
1496 eval (cmd)
1497 }
1498 if (_status !== 0) {
1499 echo 'failed'
1500 }
1501 }
1502}
1503)zZXx");
1504
1505GLOBAL_STR(gStr44, R"zZXx(# Two functions I actually use, all the time.
1506#
1507# To keep depenedencies small, this library will NEVER grow other functions
1508# (and is named to imply that.)
1509#
1510# Usage:
1511# source --builtin two.sh
1512#
1513# Examples:
1514# log 'hi'
1515# die 'expected a number'
1516
1517log() {
1518 ### Write a message to stderr.
1519 echo "$@" >&2
1520}
1521
1522die() {
1523 ### Write an error message with the script name, and exit with status 1.
1524 log "$0: fatal: $@"
1525 exit 1
1526}
1527
1528)zZXx");
1529
1530
1531
1532TextFile array[] = {
1533 {.rel_path = "_devbuild/help/data-errors", .contents = gStr0},
1534 {.rel_path = "_devbuild/help/data-front-end", .contents = gStr1},
1535 {.rel_path = "_devbuild/help/data-j8-notation", .contents = gStr2},
1536 {.rel_path = "_devbuild/help/help", .contents = gStr3},
1537 {.rel_path = "_devbuild/help/oils-usage", .contents = gStr4},
1538 {.rel_path = "_devbuild/help/osh-builtin-cmd", .contents = gStr5},
1539 {.rel_path = "_devbuild/help/osh-chapters", .contents = gStr6},
1540 {.rel_path = "_devbuild/help/osh-cmd-lang", .contents = gStr7},
1541 {.rel_path = "_devbuild/help/osh-front-end", .contents = gStr8},
1542 {.rel_path = "_devbuild/help/osh-mini-lang", .contents = gStr9},
1543 {.rel_path = "_devbuild/help/osh-option", .contents = gStr10},
1544 {.rel_path = "_devbuild/help/osh-osh-assign", .contents = gStr11},
1545 {.rel_path = "_devbuild/help/osh-plugin", .contents = gStr12},
1546 {.rel_path = "_devbuild/help/osh-special-var", .contents = gStr13},
1547 {.rel_path = "_devbuild/help/osh-stdlib", .contents = gStr14},
1548 {.rel_path = "_devbuild/help/osh-type-method", .contents = gStr15},
1549 {.rel_path = "_devbuild/help/osh-usage", .contents = gStr16},
1550 {.rel_path = "_devbuild/help/osh-word-lang", .contents = gStr17},
1551 {.rel_path = "_devbuild/help/ysh-builtin-cmd", .contents = gStr18},
1552 {.rel_path = "_devbuild/help/ysh-builtin-func", .contents = gStr19},
1553 {.rel_path = "_devbuild/help/ysh-chapters", .contents = gStr20},
1554 {.rel_path = "_devbuild/help/ysh-cmd-lang", .contents = gStr21},
1555 {.rel_path = "_devbuild/help/ysh-expr-lang", .contents = gStr22},
1556 {.rel_path = "_devbuild/help/ysh-front-end", .contents = gStr23},
1557 {.rel_path = "_devbuild/help/ysh-mini-lang", .contents = gStr24},
1558 {.rel_path = "_devbuild/help/ysh-option", .contents = gStr25},
1559 {.rel_path = "_devbuild/help/ysh-plugin", .contents = gStr26},
1560 {.rel_path = "_devbuild/help/ysh-special-var", .contents = gStr27},
1561 {.rel_path = "_devbuild/help/ysh-stdlib", .contents = gStr28},
1562 {.rel_path = "_devbuild/help/ysh-type-method", .contents = gStr29},
1563 {.rel_path = "_devbuild/help/ysh-usage", .contents = gStr30},
1564 {.rel_path = "_devbuild/help/ysh-word-lang", .contents = gStr31},
1565 {.rel_path = "_devbuild/help/ysh-ysh-cmd", .contents = gStr32},
1566 {.rel_path = "stdlib/TEST.sh", .contents = gStr33},
1567 {.rel_path = "stdlib/args.ysh", .contents = gStr34},
1568 {.rel_path = "stdlib/byo-server-lib.sh", .contents = gStr35},
1569 {.rel_path = "stdlib/funcs.ysh", .contents = gStr36},
1570 {.rel_path = "stdlib/list.ysh", .contents = gStr37},
1571 {.rel_path = "stdlib/math.ysh", .contents = gStr38},
1572 {.rel_path = "stdlib/methods.ysh", .contents = gStr39},
1573 {.rel_path = "stdlib/prelude.ysh", .contents = gStr40},
1574 {.rel_path = "stdlib/stream.ysh", .contents = gStr41},
1575 {.rel_path = "stdlib/table.ysh", .contents = gStr42},
1576 {.rel_path = "stdlib/testing.ysh", .contents = gStr43},
1577 {.rel_path = "stdlib/two.sh", .contents = gStr44},
1578
1579 {.rel_path = nullptr, .contents = nullptr},
1580};
1581
1582} // namespace embedded_file
1583
1584TextFile* gEmbeddedFiles = embedded_file::array; // turn array into pointer