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

1536 lines, 138 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(# args.ysh
587#
588# Usage:
589# source --builtin args.sh
590#
591# parser (&spec) {
592# flag -v --verbose (help="Verbosely") # default is Bool, false
593#
594# flag -P --max-procs ('int', default=-1, doc='''
595# Run at most P processes at a time
596# ''')
597#
598# flag -i --invert ('bool', default=true, doc='''
599# Long multiline
600# Description
601# ''')
602#
603# arg src (help='Source')
604# arg dest (help='Dest')
605# arg times (help='Foo')
606#
607# rest files
608# }
609#
610# var args = parseArgs(spec, ARGV)
611#
612# echo "Verbose $[args.verbose]"
613
614# TODO: See list
615# - It would be nice to keep `flag` and `arg` private, injecting them into the
616# proc namespace only within `Args`
617# - We need "type object" to replace the strings 'int', 'bool', etc.
618# - flag builtin:
619# - handle only long flag or only short flag
620# - flag aliases
621
622proc parser (; place ; ; block_def) {
623 ## Create an args spec which can be passed to parseArgs.
624 ##
625 ## Example:
626 ##
627 ## # NOTE: &spec will create a variable named spec
628 ## parser (&spec) {
629 ## flag -v --verbose ('bool')
630 ## }
631 ##
632 ## var args = parseArgs(spec, ARGV)
633
634 var p = {flags: [], args: []}
635 ctx push (p; ; block_def)
636
637 # Validate that p.rest = [name] or null and reduce p.rest into name or null.
638 if ('rest' in p) {
639 if (len(p.rest) > 1) {
640 error '`rest` was called more than once' (code=3)
641 } else {
642 setvar p.rest = p.rest[0]
643 }
644 } else {
645 setvar p.rest = null
646 }
647
648 var names = {}
649 for items in ([p.flags, p.args]) {
650 for x in (items) {
651 if (x.name in names) {
652 error "Duplicate flag/arg name $[x.name] in spec" (code=3)
653 }
654
655 setvar names[x.name] = null
656 }
657 }
658
659 # TODO: what about `flag --name` and then `arg name`?
660
661 call place->setValue(p)
662}
663
664proc flag (short, long ; type='bool' ; default=null, help=null) {
665 ## Declare a flag within an `arg-parse`.
666 ##
667 ## Examples:
668 ##
669 ## arg-parse (&spec) {
670 ## flag -v --verbose
671 ## flag -n --count ('int', default=1)
672 ## flag -f --file ('str', help="File to process")
673 ## }
674
675 # bool has a default of false, not null
676 if (type === 'bool' and default === null) {
677 setvar default = false
678 }
679
680 # TODO: validate `type`
681
682 # TODO: Should use "trimPrefix"
683 var name = long[2:]
684
685 ctx emit flags ({short, long, name, type, default, help})
686}
687
688proc arg (name ; ; help=null) {
689 ## Declare a positional argument within an `arg-parse`.
690 ##
691 ## Examples:
692 ##
693 ## arg-parse (&spec) {
694 ## arg name
695 ## arg config (help="config file path")
696 ## }
697
698 ctx emit args ({name, help})
699}
700
701proc rest (name) {
702 ## Take the remaining positional arguments within an `arg-parse`.
703 ##
704 ## Examples:
705 ##
706 ## arg-parse (&grepSpec) {
707 ## arg query
708 ## rest files
709 ## }
710
711 # We emit instead of set to detect multiple invocations of "rest"
712 ctx emit rest (name)
713}
714
715func parseArgs(spec, argv) {
716 ## Given a spec created by `parser`. Parse an array of strings `argv` per
717 ## that spec.
718 ##
719 ## See `parser` for examples of use.
720
721 var i = 0
722 var positionalPos = 0
723 var argc = len(argv)
724 var args = {}
725 var rest = []
726
727 var value
728 var found
729 while (i < argc) {
730 var arg = argv[i]
731 if (arg->startsWith('-')) {
732 setvar found = false
733
734 for flag in (spec.flags) {
735 if ( (flag.short and flag.short === arg) or
736 (flag.long and flag.long === arg) ) {
737 case (flag.type) {
738 ('bool') | (null) { setvar value = true }
739 int {
740 setvar i += 1
741 if (i >= len(argv)) {
742 error "Expected integer after '$arg'" (code=2)
743 }
744
745 try { setvar value = int(argv[i]) }
746 if (_status !== 0) {
747 error "Expected integer after '$arg', got '$[argv[i]]'" (code=2)
748 }
749 }
750 }
751
752 setvar args[flag.name] = value
753 setvar found = true
754 break
755 }
756 }
757
758 if (not found) {
759 error "Unknown flag '$arg'" (code=2)
760 }
761 } elif (positionalPos >= len(spec.args)) {
762 if (not spec.rest) {
763 error "Too many arguments, unexpected '$arg'" (code=2)
764 }
765
766 call rest->append(arg)
767 } else {
768 var pos = spec.args[positionalPos]
769 setvar positionalPos += 1
770 setvar value = arg
771 setvar args[pos.name] = value
772 }
773
774 setvar i += 1
775 }
776
777 if (spec.rest) {
778 setvar args[spec.rest] = rest
779 }
780
781 # Set defaults for flags
782 for flag in (spec.flags) {
783 if (flag.name not in args) {
784 setvar args[flag.name] = flag.default
785 }
786 }
787
788 # Raise error on missing args
789 for arg in (spec.args) {
790 if (arg.name not in args) {
791 error "Usage Error: Missing required argument $[arg.name]" (code=2)
792 }
793 }
794
795 return (args)
796}
797)zZXx");
798
799GLOBAL_STR(gStr34, R"zZXx(func identity(x) {
800 ## The identity function. Returns its argument.
801
802 return (x)
803}
804)zZXx");
805
806GLOBAL_STR(gStr35, R"zZXx(func any(list) {
807 ## Returns true if any value in the list is truthy.
808 ##
809 ## If the list is empty, return false.
810
811 for item in (list) {
812 if (item) {
813 return (true)
814 }
815 }
816 return (false)
817}
818
819func all(list) {
820 ## Returns true if all values in the list are truthy.
821 ##
822 ## If the list is empty, return true.
823
824 for item in (list) {
825 if (not item) {
826 return (false)
827 }
828 }
829 return (true)
830}
831
832func sum(list; start=0) {
833 ## Computes the sum of all elements in the list.
834 ##
835 ## Returns 0 for an empty list.
836
837 var sum = start
838 for item in (list) {
839 setvar sum += item
840 }
841 return (sum)
842}
843)zZXx");
844
845GLOBAL_STR(gStr36, R"zZXx(func __math_select(list, cmp) {
846 ## Internal helper for `max` and `min`.
847 ##
848 ## NOTE: If `list` is empty, then an error is thrown.
849
850 if (len(list) === 0) {
851 error "Unexpected empty list" (code=3)
852 }
853
854 if (len(list) === 1) {
855 return (list[0])
856 }
857
858 var match = list[0]
859 for i in (1 .. len(list)) {
860 setvar match = cmp(list[i], match)
861 }
862 return (match)
863}
864
865func max(...args) {
866 ## Compute the maximum of 2 or more values.
867 ##
868 ## `max` takes two different signatures:
869 ## - `max(a, b)` to return the maximum of `a`, `b`
870 ## - `max(list)` to return the greatest item in the `list`
871 ##
872 ## So, for example:
873 ##
874 ## max(1, 2) # => 2
875 ## max([1, 2, 3]) # => 3
876
877 case (len(args)) {
878 (1) { return (__math_select(args[0], max)) }
879 (2) {
880 if (args[0] > args[1]) {
881 return (args[0])
882 } else {
883 return (args[1])
884 }
885 }
886 (else) { error "max expects 1 or 2 args" (code=3) }
887 }
888}
889
890func min(...args) {
891 ## Compute the minimum of 2 or more values.
892 ##
893 ## `min` takes two different signatures:
894 ## - `min(a, b)` to return the minimum of `a`, `b`
895 ## - `min(list)` to return the least item in the `list`
896 ##
897 ## So, for example:
898 ##
899 ## min(2, 3) # => 2
900 ## max([1, 2, 3]) # => 1
901
902 case (len(args)) {
903 (1) { return (__math_select(args[0], min)) }
904 (2) {
905 if (args[0] < args[1]) {
906 return (args[0])
907 } else {
908 return (args[1])
909 }
910 }
911 (else) { error "min expects 1 or 2 args" (code=3) }
912 }
913}
914
915func abs(x) {
916 ## Compute the absolute (positive) value of a number (float or int).
917
918 if (x < 0) {
919 return (-x)
920 } else {
921 return (x)
922 }
923}
924)zZXx");
925
926GLOBAL_STR(gStr37, R"zZXx(# Can we define methods in pure YSH?
927#
928# (mylist->find(42) !== -1)
929#
930# instead of
931#
932# ('42' in mylist)
933#
934# Because 'in' is for Dict
935
936func find (haystack List, needle) {
937 for i, x in (haystack) {
938 if (x === needle) {
939 return (i)
940 }
941 }
942 return (-1)
943}
944)zZXx");
945
946GLOBAL_STR(gStr38, R"zZXx(# Library to turn a file into a "BYO test server"
947#
948# Usage:
949# source --builtin test/byo-server-lib.sh # from Oils
950# source test/byo-server-lib.sh # can be used with bash
951#
952# The client creates a clean process state and directory state for each tests.
953#
954# (It relies on compgen -A, and maybe declare -f, so it's not POSIX shell.)
955
956# TODO: How do I get stdlib/two.sh
957log() {
958 echo "$@" >& 2
959}
960
961die() {
962 log "$0: fatal: $@"
963 exit 1
964}
965
966byo-maybe-run() {
967 local command=${BYO_COMMAND:-}
968
969 case $command in
970 '')
971 # Do nothing if it's not specified
972 return
973 ;;
974
975 detect)
976 # all the commands supported, except 'detect'
977 echo list-tests
978 echo run-test
979
980 exit 66 # ASCII code for 'B' - what the protocol specifies
981 ;;
982
983 list-tests)
984 # bash extension that OSH also implements
985 compgen -A function | grep '^test-'
986 exit 0
987 ;;
988
989 run-test)
990 local test_name=${BYO_ARG:-}
991 if test -z "$test_name"; then
992 die "BYO run-test: Expected BYO_ARG"
993 fi
994
995 # Shell convention: we name functions test-*
996 $test_name
997
998 # Only run if not set -e. Either way it's equivalent
999 exit $?
1000 ;;
1001
1002 *)
1003 die "Invalid BYO command '$command'"
1004 ;;
1005 esac
1006
1007 # Do nothing if BYO_COMMAND is not set.
1008 # The program continues to its "main".
1009}
1010
1011byo-must-run() {
1012 local command=${BYO_COMMAND:-}
1013 if test -z "$command"; then
1014 die "Expected BYO_COMMAND= in environment"
1015 fi
1016
1017 byo-maybe-run
1018}
1019)zZXx");
1020
1021GLOBAL_STR(gStr39, R"zZXx(# Two functions I actually use, all the time.
1022#
1023# To keep depenedencies small, this library will NEVER grow other functions
1024# (and is named to imply that.)
1025#
1026# Usage:
1027# source --builtin two.sh
1028#
1029# Examples:
1030# log 'hi'
1031# die 'expected a number'
1032
1033log() {
1034 ### Write a message to stderr.
1035 echo "$@" >&2
1036}
1037
1038die() {
1039 ### Write an error message with the script name, and exit with status 1.
1040 log "$0: fatal: $@"
1041 exit 1
1042}
1043
1044)zZXx");
1045
1046GLOBAL_STR(gStr40, R"zZXx(# These were helpful while implementing args.ysh
1047# Maybe we will want to export them in a prelude so that others can use them too?
1048#
1049# Prior art: Rust has `todo!()` which is quite nice. Other languages allow
1050# users to `raise NotImplmentedError()`.
1051
1052# Andy comments:
1053# - 'pass' can be : or true in shell. It's a little obscure / confusing, but
1054# there is an argument for minimalism. Although I prefer words like 'true',
1055# and that already means something.
1056# - UPDATE: we once took 'pass' as a keyword, but users complained because
1057# there is a command 'pass'. So we probably can't have this by default.
1058# Need to discuss source --builtin.
1059
1060# - todo could be more static? Rust presumably does it at compile time
1061
1062proc todo () {
1063 ## Raises a not implemented error when run.
1064 error ("TODO: not implemented") # TODO: is error code 1 ok?
1065}
1066
1067proc pass () {
1068 ## Use when you want to temporarily leave a block empty.
1069 _ null
1070}
1071)zZXx");
1072
1073GLOBAL_STR(gStr41, R"zZXx(# stream.ysh
1074#
1075# Usage:
1076# source --builtin stream.ysh
1077#
1078# For reading lines, decoding, extracting, splitting
1079
1080# make this file a test server
1081source --builtin osh/byo-server-lib.sh
1082
1083source --builtin args.ysh
1084
1085proc slurp-by (; num_lines) {
1086 # TODO: (stdin)
1087 for line in <> {
1088 echo TODO
1089 }
1090}
1091
1092# Note:
1093# - these are all the same algorithm
1094# - also word, block, etc. are all optional
1095
1096proc each-line (...words; template=null; ; block=null) {
1097 # TODO:
1098 # parse --j8 --max-jobs flag
1099
1100 # parse template_str as string
1101 # TODO: this is dangerous though ... because you can execute code
1102 # I think you need a SAFE version
1103
1104 # evaluate template string expression - I guess that allows $(echo hi) and so
1105 # forth
1106
1107 # evaluate block with _line binding
1108 # block: execute in parallel with --max-jobs
1109
1110 for line in <> {
1111 echo TODO
1112 }
1113}
1114
1115proc test-each-line {
1116 echo 'TODO: need basic test runner'
1117
1118 # ysh-tool test stream.ysh
1119 #
1120 # Col
1121
1122
1123}
1124
1125proc each-row (; ; block) {
1126 echo TODO
1127}
1128
1129proc split-by (; ifs=null; block) {
1130 echo TODO
1131}
1132
1133proc if-split-by (; ifs=null; block) {
1134 echo TODO
1135}
1136
1137proc chop () {
1138 ### alias for if-split-by
1139 echo TODO
1140}
1141
1142proc must-match (; pattern; block) {
1143 echo TODO
1144}
1145
1146proc if-match (; pattern; block) {
1147 echo TODO
1148}
1149
1150# Protocol:
1151#
1152# - The file lists its tests the "actions"
1153# - Then the test harness runs them
1154# - But should it be ENV vars
1155#
1156# - BYO_LIST_TESTS=1
1157# - BYO_RUN_TEST=foo
1158# - $PWD is a CLEAN temp dir, the process doesn't have to do anything
1159
1160# - silent on success, but prints file on output
1161# - OK this makes sense
1162#
1163# The trivial test in Python:
1164#
1165# from test import byo
1166# byo.maybe_main()
1167#
1168# bash library:
1169# source --builtin byo-server.sh
1170#
1171# byo-maybe-main # reads env variables, and then exits
1172#
1173# source --builtin assertions.ysh
1174#
1175# assert-ok 'echo hi'
1176# assert-stdout 'hi' 'echo -n hi'
1177#
1178# "$@"
1179#
1180# Run all tests
1181# util/byo-client.sh run-tests $YSH stdlib/table.ysh
1182# util/byo-client.sh run-tests -f x $YSH stdlib/table.ysh
1183
1184# Clean process
1185# Clean working dir
1186
1187#
1188# Stream Protocol:
1189# #.byo - is this she-dot, that's for a file
1190# Do we need metadata?
1191#
1192
1193# The harness
1194#
1195# It's process based testing.
1196#
1197# Test runner process: bash or OSH (unlike sharness!)
1198# Tested process: any language - bash,
1199#
1200# Key point: you don't have to quote shell code?
1201
1202list-byo-tests() {
1203 echo TODO
1204}
1205
1206run-byo-tests() {
1207 # source it
1208 echo TODO
1209}
1210
1211byo-maybe-run
1212)zZXx");
1213
1214GLOBAL_STR(gStr42, R"zZXx(# table.ysh - Library for tables.
1215#
1216# Usage:
1217# source --builtin table.ysh
1218
1219# make this file a test server
1220source --builtin osh/byo-server-lib.sh
1221
1222proc table (...words; place; ; block) {
1223 var n = len(words)
1224
1225 # TODO: parse flags
1226 #
1227 # --by-row
1228 # --by-col
1229 #
1230 # Place is optional
1231
1232 if (n === 0) {
1233 echo TODO
1234 return
1235 }
1236
1237 var action = words[0]
1238
1239 # textual operations
1240 case (action) {
1241 cat {
1242 echo todo
1243 }
1244 align {
1245 echo todo
1246 }
1247 tabify {
1248 echo todo
1249 }
1250 tabify {
1251 echo todo
1252 }
1253 header {
1254 echo todo
1255 }
1256 slice {
1257 # this has typed args
1258 # do we do some sort of splat?
1259 echo todo
1260 }
1261 to-tsv {
1262 echo todo
1263 }
1264 }
1265
1266 echo TODO
1267}
1268
1269proc test-table {
1270 return
1271
1272 table (&files1) {
1273 cols num_bytes path
1274 type Int Str
1275
1276 row 10 README.md
1277 row 12 main.py
1278
1279 row (12, 'lib.py')
1280 row (num_bytes=12, path='util.py')
1281 }
1282
1283 # 2 columns - The default is by column?
1284 assert ['Dict' === type(files1)]
1285 assert [2 === len(files1)]
1286
1287 # Same table
1288 table --by-row (&files2) {
1289 cols num_bytes path
1290 type Int Str
1291
1292 row 10 README.md
1293 row 12 main.py
1294
1295 row (12, 'lib.py')
1296 row (num_bytes=12, path='util.py')
1297 }
1298
1299 # 4 rows
1300 assert ['List' === type(files2)]
1301 assert [4 === len(files2)]
1302}
1303
1304# "subcommands" of the dialect
1305
1306proc cols (...names) {
1307 # cols name age
1308 echo TODO
1309}
1310
1311proc types (...types) {
1312 # types - Int? Str?
1313 echo TODO
1314}
1315
1316proc attr (name; ...values) {
1317 # attr units ('-', 'secs')
1318 echo TODO
1319}
1320
1321# is this allowed outside table {} blocks too?
1322proc row {
1323 echo TODO
1324}
1325
1326#
1327# dplyr names
1328#
1329
1330# TODO: can we parse select?
1331
1332proc where {
1333 echo
1334}
1335
1336# TODO: should be able to test argv[0] or something
1337# Or pass to _mutate-transmute
1338
1339proc mutate {
1340 echo TODO
1341}
1342
1343proc transmute {
1344 echo TODO
1345}
1346
1347proc rename {
1348 echo TODO
1349}
1350
1351proc group-by {
1352 echo TODO
1353}
1354
1355proc sort-by {
1356 echo TODO
1357}
1358
1359proc summary {
1360 echo TODO
1361}
1362
1363byo-maybe-run
1364)zZXx");
1365
1366GLOBAL_STR(gStr43, R"zZXx(# testing.ysh
1367#
1368# Usage:
1369# source --builtin testing.sh
1370#
1371# func f(x) { return (x + 1) }
1372#
1373# describe foo {
1374# assert (43 === f(42))
1375# }
1376#
1377# if is-main {
1378# run-tests @ARGV # --filter
1379# }
1380
1381module stdlib/testing || return 0
1382
1383source --builtin args.ysh
1384
1385proc assert ( ; cond ; fail_message='default fail message') {
1386 echo 'hi from assert'
1387
1388 = cond
1389
1390 # I think this might be ready now?
1391
1392 var val = evalExpr(cond)
1393
1394 echo
1395 echo 'value'
1396 = val
1397 pp line (val)
1398
1399 = fail_message
1400
1401 if (val) {
1402 echo 'OK'
1403 } else {
1404 var m = evalExpr(fail_message)
1405 echo "FAIL - this is where we extract the string - $m"
1406 }
1407}
1408
1409proc test-assert {
1410 var x = 42
1411 assert [42 === x]
1412}
1413
1414proc test-expr ( ; expr ) {
1415 echo 'expr'
1416 pp line (expr)
1417}
1418
1419proc test-named ( ; ; n=^[99] ) {
1420 echo 'n'
1421 pp line (n)
1422}
1423
1424# What happens when there are duplicate test IDs?
1425#
1426# Also I think filter by "$test_id/$case_id"
1427
1428proc __it (case_id ; ; ; block) {
1429 # This uses a clean directory
1430 echo TODO
1431}
1432
1433# is this accessible to users?
1434# It can contain a global list of things to run
1435
1436# Naming convention: a proc named 'describe' mutates a global named _describe?
1437# Or maybe _describe_list ?
1438
1439var _describe_list = []
1440
1441proc describe (test_id ; ; ; block) {
1442 echo describe
1443 #= desc
1444
1445 # TODO:
1446 # - need append
1447 # - need ::
1448 # _ _describe->append(cmd)
1449 #
1450 # Need to clean this up
1451 # append (_describe, cmd) # does NOT work!
1452
1453 call _describe_list->append(block)
1454}
1455
1456proc Args {
1457 echo TODO
1458}
1459
1460# Problem: this creates a global variable?
1461Args (&spec) {
1462 flag --filter 'Regex of test descriptions'
1463}
1464
1465proc run-tests {
1466 var opt, i = parseArgs(spec, ARGV)
1467
1468 # TODO:
1469 # - parse --filter foo, which you can use eggex for!
1470
1471 for cmd in (_describe) {
1472 # TODO: print filename and 'describe' name?
1473 try {
1474 eval (cmd)
1475 }
1476 if (_status !== 0) {
1477 echo 'failed'
1478 }
1479 }
1480}
1481)zZXx");
1482
1483
1484
1485TextFile array[] = {
1486 {.rel_path = "_devbuild/help/data-errors", .contents = gStr0},
1487 {.rel_path = "_devbuild/help/data-front-end", .contents = gStr1},
1488 {.rel_path = "_devbuild/help/data-j8-notation", .contents = gStr2},
1489 {.rel_path = "_devbuild/help/help", .contents = gStr3},
1490 {.rel_path = "_devbuild/help/oils-usage", .contents = gStr4},
1491 {.rel_path = "_devbuild/help/osh-builtin-cmd", .contents = gStr5},
1492 {.rel_path = "_devbuild/help/osh-chapters", .contents = gStr6},
1493 {.rel_path = "_devbuild/help/osh-cmd-lang", .contents = gStr7},
1494 {.rel_path = "_devbuild/help/osh-front-end", .contents = gStr8},
1495 {.rel_path = "_devbuild/help/osh-mini-lang", .contents = gStr9},
1496 {.rel_path = "_devbuild/help/osh-option", .contents = gStr10},
1497 {.rel_path = "_devbuild/help/osh-osh-assign", .contents = gStr11},
1498 {.rel_path = "_devbuild/help/osh-plugin", .contents = gStr12},
1499 {.rel_path = "_devbuild/help/osh-special-var", .contents = gStr13},
1500 {.rel_path = "_devbuild/help/osh-stdlib", .contents = gStr14},
1501 {.rel_path = "_devbuild/help/osh-type-method", .contents = gStr15},
1502 {.rel_path = "_devbuild/help/osh-usage", .contents = gStr16},
1503 {.rel_path = "_devbuild/help/osh-word-lang", .contents = gStr17},
1504 {.rel_path = "_devbuild/help/ysh-builtin-cmd", .contents = gStr18},
1505 {.rel_path = "_devbuild/help/ysh-builtin-func", .contents = gStr19},
1506 {.rel_path = "_devbuild/help/ysh-chapters", .contents = gStr20},
1507 {.rel_path = "_devbuild/help/ysh-cmd-lang", .contents = gStr21},
1508 {.rel_path = "_devbuild/help/ysh-expr-lang", .contents = gStr22},
1509 {.rel_path = "_devbuild/help/ysh-front-end", .contents = gStr23},
1510 {.rel_path = "_devbuild/help/ysh-mini-lang", .contents = gStr24},
1511 {.rel_path = "_devbuild/help/ysh-option", .contents = gStr25},
1512 {.rel_path = "_devbuild/help/ysh-plugin", .contents = gStr26},
1513 {.rel_path = "_devbuild/help/ysh-special-var", .contents = gStr27},
1514 {.rel_path = "_devbuild/help/ysh-stdlib", .contents = gStr28},
1515 {.rel_path = "_devbuild/help/ysh-type-method", .contents = gStr29},
1516 {.rel_path = "_devbuild/help/ysh-usage", .contents = gStr30},
1517 {.rel_path = "_devbuild/help/ysh-word-lang", .contents = gStr31},
1518 {.rel_path = "_devbuild/help/ysh-ysh-cmd", .contents = gStr32},
1519 {.rel_path = "stdlib/args.ysh", .contents = gStr33},
1520 {.rel_path = "stdlib/funcs.ysh", .contents = gStr34},
1521 {.rel_path = "stdlib/list.ysh", .contents = gStr35},
1522 {.rel_path = "stdlib/math.ysh", .contents = gStr36},
1523 {.rel_path = "stdlib/methods.ysh", .contents = gStr37},
1524 {.rel_path = "stdlib/osh/byo-server-lib.sh", .contents = gStr38},
1525 {.rel_path = "stdlib/osh/two.sh", .contents = gStr39},
1526 {.rel_path = "stdlib/prelude.ysh", .contents = gStr40},
1527 {.rel_path = "stdlib/stream.ysh", .contents = gStr41},
1528 {.rel_path = "stdlib/table.ysh", .contents = gStr42},
1529 {.rel_path = "stdlib/testing.ysh", .contents = gStr43},
1530
1531 {.rel_path = nullptr, .contents = nullptr},
1532};
1533
1534} // namespace embedded_file
1535
1536TextFile* gEmbeddedFiles = embedded_file::array; // turn array into pointer