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

1528 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
966
967byo-maybe-main() {
968 local command=${BYO_COMMAND:-}
969
970 case $command in
971 '')
972 # Do nothing if it's not specified
973 return
974 ;;
975
976 detect)
977 # all the commands supported, except 'detect'
978 echo list-tests
979 echo run-test
980
981 exit 66 # ASCII code for 'B' - what the protocol specifies
982 ;;
983
984 list-tests)
985 # bash extension that OSH also implements
986 compgen -A function | grep '^test-'
987 exit 0
988 ;;
989
990 run-test)
991 local test_name=${BYO_ARG:-}
992 if test -z "$test_name"; then
993 die "BYO run-test: Expected BYO_ARG"
994 fi
995
996 # Shell convention: we name functions test-*
997 $test_name
998
999 # Only run if not set -e. Either way it's equivalent
1000 exit $?
1001 ;;
1002
1003 *)
1004 die "Invalid BYO command '$command'"
1005 ;;
1006 esac
1007
1008 # Do nothing if BYO_COMMAND is not set.
1009 # The program continues to its "main".
1010}
1011)zZXx");
1012
1013GLOBAL_STR(gStr39, R"zZXx(# Two functions I actually use, all the time.
1014#
1015# To keep depenedencies small, this library will NEVER grow other functions
1016# (and is named to imply that.)
1017#
1018# Usage:
1019# source --builtin two.sh
1020#
1021# Examples:
1022# log 'hi'
1023# die 'expected a number'
1024
1025log() {
1026 ### Write a message to stderr.
1027 echo "$@" >&2
1028}
1029
1030die() {
1031 ### Write an error message with the script name, and exit with status 1.
1032 log "$0: fatal: $@"
1033 exit 1
1034}
1035
1036)zZXx");
1037
1038GLOBAL_STR(gStr40, R"zZXx(# These were helpful while implementing args.ysh
1039# Maybe we will want to export them in a prelude so that others can use them too?
1040#
1041# Prior art: Rust has `todo!()` which is quite nice. Other languages allow
1042# users to `raise NotImplmentedError()`.
1043
1044# Andy comments:
1045# - 'pass' can be : or true in shell. It's a little obscure / confusing, but
1046# there is an argument for minimalism. Although I prefer words like 'true',
1047# and that already means something.
1048# - UPDATE: we once took 'pass' as a keyword, but users complained because
1049# there is a command 'pass'. So we probably can't have this by default.
1050# Need to discuss source --builtin.
1051
1052# - todo could be more static? Rust presumably does it at compile time
1053
1054proc todo () {
1055 ## Raises a not implemented error when run.
1056 error ("TODO: not implemented") # TODO: is error code 1 ok?
1057}
1058
1059proc pass () {
1060 ## Use when you want to temporarily leave a block empty.
1061 _ null
1062}
1063)zZXx");
1064
1065GLOBAL_STR(gStr41, R"zZXx(# stream.ysh
1066#
1067# Usage:
1068# source --builtin stream.ysh
1069#
1070# For reading lines, decoding, extracting, splitting
1071
1072# make this file a test server
1073source --builtin osh/byo-server-lib.sh
1074
1075source --builtin args.ysh
1076
1077proc slurp-by (; num_lines) {
1078 # TODO: (stdin)
1079 for line in <> {
1080 echo TODO
1081 }
1082}
1083
1084# Note:
1085# - these are all the same algorithm
1086# - also word, block, etc. are all optional
1087
1088proc each-line (...words; template=null; ; block=null) {
1089 # TODO:
1090 # parse --j8 --max-jobs flag
1091
1092 # parse template_str as string
1093 # TODO: this is dangerous though ... because you can execute code
1094 # I think you need a SAFE version
1095
1096 # evaluate template string expression - I guess that allows $(echo hi) and so
1097 # forth
1098
1099 # evaluate block with _line binding
1100 # block: execute in parallel with --max-jobs
1101
1102 for line in <> {
1103 echo TODO
1104 }
1105}
1106
1107proc test-each-line {
1108 echo 'TODO: need basic test runner'
1109
1110 # ysh-tool test stream.ysh
1111 #
1112 # Col
1113
1114
1115}
1116
1117proc each-row (; ; block) {
1118 echo TODO
1119}
1120
1121proc split-by (; ifs=null; block) {
1122 echo TODO
1123}
1124
1125proc if-split-by (; ifs=null; block) {
1126 echo TODO
1127}
1128
1129proc chop () {
1130 ### alias for if-split-by
1131 echo TODO
1132}
1133
1134proc must-match (; pattern; block) {
1135 echo TODO
1136}
1137
1138proc if-match (; pattern; block) {
1139 echo TODO
1140}
1141
1142# Protocol:
1143#
1144# - The file lists its tests the "actions"
1145# - Then the test harness runs them
1146# - But should it be ENV vars
1147#
1148# - BYO_LIST_TESTS=1
1149# - BYO_RUN_TEST=foo
1150# - $PWD is a CLEAN temp dir, the process doesn't have to do anything
1151
1152# - silent on success, but prints file on output
1153# - OK this makes sense
1154#
1155# The trivial test in Python:
1156#
1157# from test import byo
1158# byo.maybe_main()
1159#
1160# bash library:
1161# source --builtin byo-server.sh
1162#
1163# byo-maybe-main # reads env variables, and then exits
1164#
1165# source --builtin assertions.ysh
1166#
1167# assert-ok 'echo hi'
1168# assert-stdout 'hi' 'echo -n hi'
1169#
1170# "$@"
1171#
1172# Run all tests
1173# util/byo-client.sh run-tests $YSH stdlib/table.ysh
1174# util/byo-client.sh run-tests -f x $YSH stdlib/table.ysh
1175
1176# Clean process
1177# Clean working dir
1178
1179#
1180# Stream Protocol:
1181# #.byo - is this she-dot, that's for a file
1182# Do we need metadata?
1183#
1184
1185# The harness
1186#
1187# It's process based testing.
1188#
1189# Test runner process: bash or OSH (unlike sharness!)
1190# Tested process: any language - bash,
1191#
1192# Key point: you don't have to quote shell code?
1193
1194list-byo-tests() {
1195 echo TODO
1196}
1197
1198run-byo-tests() {
1199 # source it
1200 echo TODO
1201}
1202
1203byo-maybe-main
1204)zZXx");
1205
1206GLOBAL_STR(gStr42, R"zZXx(# table.ysh - Library for tables.
1207#
1208# Usage:
1209# source --builtin table.ysh
1210
1211# make this file a test server
1212source --builtin osh/byo-server-lib.sh
1213
1214proc table (...words; place; ; block) {
1215 var n = len(words)
1216
1217 # TODO: parse flags
1218 #
1219 # --by-row
1220 # --by-col
1221 #
1222 # Place is optional
1223
1224 if (n === 0) {
1225 echo TODO
1226 return
1227 }
1228
1229 var action = words[0]
1230
1231 # textual operations
1232 case (action) {
1233 cat {
1234 echo todo
1235 }
1236 align {
1237 echo todo
1238 }
1239 tabify {
1240 echo todo
1241 }
1242 tabify {
1243 echo todo
1244 }
1245 header {
1246 echo todo
1247 }
1248 slice {
1249 # this has typed args
1250 # do we do some sort of splat?
1251 echo todo
1252 }
1253 to-tsv {
1254 echo todo
1255 }
1256 }
1257
1258 echo TODO
1259}
1260
1261proc test-table {
1262 return
1263
1264 table (&files1) {
1265 cols num_bytes path
1266 type Int Str
1267
1268 row 10 README.md
1269 row 12 main.py
1270
1271 row (12, 'lib.py')
1272 row (num_bytes=12, path='util.py')
1273 }
1274
1275 # 2 columns - The default is by column?
1276 assert ['Dict' === type(files1)]
1277 assert [2 === len(files1)]
1278
1279 # Same table
1280 table --by-row (&files2) {
1281 cols num_bytes path
1282 type Int Str
1283
1284 row 10 README.md
1285 row 12 main.py
1286
1287 row (12, 'lib.py')
1288 row (num_bytes=12, path='util.py')
1289 }
1290
1291 # 4 rows
1292 assert ['List' === type(files2)]
1293 assert [4 === len(files2)]
1294}
1295
1296# "subcommands" of the dialect
1297
1298proc cols (...names) {
1299 # cols name age
1300 echo TODO
1301}
1302
1303proc types (...types) {
1304 # types - Int? Str?
1305 echo TODO
1306}
1307
1308proc attr (name; ...values) {
1309 # attr units ('-', 'secs')
1310 echo TODO
1311}
1312
1313# is this allowed outside table {} blocks too?
1314proc row {
1315 echo TODO
1316}
1317
1318#
1319# dplyr names
1320#
1321
1322# TODO: can we parse select?
1323
1324proc where {
1325 echo
1326}
1327
1328# TODO: should be able to test argv[0] or something
1329# Or pass to _mutate-transmute
1330
1331proc mutate {
1332 echo TODO
1333}
1334
1335proc transmute {
1336 echo TODO
1337}
1338
1339proc rename {
1340 echo TODO
1341}
1342
1343proc group-by {
1344 echo TODO
1345}
1346
1347proc sort-by {
1348 echo TODO
1349}
1350
1351proc summary {
1352 echo TODO
1353}
1354
1355byo-maybe-main
1356)zZXx");
1357
1358GLOBAL_STR(gStr43, R"zZXx(# testing.ysh
1359#
1360# Usage:
1361# source --builtin testing.sh
1362#
1363# func f(x) { return (x + 1) }
1364#
1365# describe foo {
1366# assert (43 === f(42))
1367# }
1368#
1369# if is-main {
1370# run-tests @ARGV # --filter
1371# }
1372
1373module stdlib/testing || return 0
1374
1375source --builtin args.ysh
1376
1377proc assert ( ; cond ; fail_message='default fail message') {
1378 echo 'hi from assert'
1379
1380 = cond
1381
1382 # I think this might be ready now?
1383
1384 var val = evalExpr(cond)
1385
1386 echo
1387 echo 'value'
1388 = val
1389 pp line (val)
1390
1391 = fail_message
1392
1393 if (val) {
1394 echo 'OK'
1395 } else {
1396 var m = evalExpr(fail_message)
1397 echo "FAIL - this is where we extract the string - $m"
1398 }
1399}
1400
1401proc test-assert {
1402 var x = 42
1403 assert [42 === x]
1404}
1405
1406proc test-expr ( ; expr ) {
1407 echo 'expr'
1408 pp line (expr)
1409}
1410
1411proc test-named ( ; ; n=^[99] ) {
1412 echo 'n'
1413 pp line (n)
1414}
1415
1416# What happens when there are duplicate test IDs?
1417#
1418# Also I think filter by "$test_id/$case_id"
1419
1420proc __it (case_id ; ; ; block) {
1421 # This uses a clean directory
1422 echo TODO
1423}
1424
1425# is this accessible to users?
1426# It can contain a global list of things to run
1427
1428# Naming convention: a proc named 'describe' mutates a global named _describe?
1429# Or maybe _describe_list ?
1430
1431var _describe_list = []
1432
1433proc describe (test_id ; ; ; block) {
1434 echo describe
1435 #= desc
1436
1437 # TODO:
1438 # - need append
1439 # - need ::
1440 # _ _describe->append(cmd)
1441 #
1442 # Need to clean this up
1443 # append (_describe, cmd) # does NOT work!
1444
1445 call _describe_list->append(block)
1446}
1447
1448proc Args {
1449 echo TODO
1450}
1451
1452# Problem: this creates a global variable?
1453Args (&spec) {
1454 flag --filter 'Regex of test descriptions'
1455}
1456
1457proc run-tests {
1458 var opt, i = parseArgs(spec, ARGV)
1459
1460 # TODO:
1461 # - parse --filter foo, which you can use eggex for!
1462
1463 for cmd in (_describe) {
1464 # TODO: print filename and 'describe' name?
1465 try {
1466 eval (cmd)
1467 }
1468 if (_status !== 0) {
1469 echo 'failed'
1470 }
1471 }
1472}
1473)zZXx");
1474
1475
1476
1477TextFile array[] = {
1478 {.rel_path = "_devbuild/help/data-errors", .contents = gStr0},
1479 {.rel_path = "_devbuild/help/data-front-end", .contents = gStr1},
1480 {.rel_path = "_devbuild/help/data-j8-notation", .contents = gStr2},
1481 {.rel_path = "_devbuild/help/help", .contents = gStr3},
1482 {.rel_path = "_devbuild/help/oils-usage", .contents = gStr4},
1483 {.rel_path = "_devbuild/help/osh-builtin-cmd", .contents = gStr5},
1484 {.rel_path = "_devbuild/help/osh-chapters", .contents = gStr6},
1485 {.rel_path = "_devbuild/help/osh-cmd-lang", .contents = gStr7},
1486 {.rel_path = "_devbuild/help/osh-front-end", .contents = gStr8},
1487 {.rel_path = "_devbuild/help/osh-mini-lang", .contents = gStr9},
1488 {.rel_path = "_devbuild/help/osh-option", .contents = gStr10},
1489 {.rel_path = "_devbuild/help/osh-osh-assign", .contents = gStr11},
1490 {.rel_path = "_devbuild/help/osh-plugin", .contents = gStr12},
1491 {.rel_path = "_devbuild/help/osh-special-var", .contents = gStr13},
1492 {.rel_path = "_devbuild/help/osh-stdlib", .contents = gStr14},
1493 {.rel_path = "_devbuild/help/osh-type-method", .contents = gStr15},
1494 {.rel_path = "_devbuild/help/osh-usage", .contents = gStr16},
1495 {.rel_path = "_devbuild/help/osh-word-lang", .contents = gStr17},
1496 {.rel_path = "_devbuild/help/ysh-builtin-cmd", .contents = gStr18},
1497 {.rel_path = "_devbuild/help/ysh-builtin-func", .contents = gStr19},
1498 {.rel_path = "_devbuild/help/ysh-chapters", .contents = gStr20},
1499 {.rel_path = "_devbuild/help/ysh-cmd-lang", .contents = gStr21},
1500 {.rel_path = "_devbuild/help/ysh-expr-lang", .contents = gStr22},
1501 {.rel_path = "_devbuild/help/ysh-front-end", .contents = gStr23},
1502 {.rel_path = "_devbuild/help/ysh-mini-lang", .contents = gStr24},
1503 {.rel_path = "_devbuild/help/ysh-option", .contents = gStr25},
1504 {.rel_path = "_devbuild/help/ysh-plugin", .contents = gStr26},
1505 {.rel_path = "_devbuild/help/ysh-special-var", .contents = gStr27},
1506 {.rel_path = "_devbuild/help/ysh-stdlib", .contents = gStr28},
1507 {.rel_path = "_devbuild/help/ysh-type-method", .contents = gStr29},
1508 {.rel_path = "_devbuild/help/ysh-usage", .contents = gStr30},
1509 {.rel_path = "_devbuild/help/ysh-word-lang", .contents = gStr31},
1510 {.rel_path = "_devbuild/help/ysh-ysh-cmd", .contents = gStr32},
1511 {.rel_path = "stdlib/args.ysh", .contents = gStr33},
1512 {.rel_path = "stdlib/funcs.ysh", .contents = gStr34},
1513 {.rel_path = "stdlib/list.ysh", .contents = gStr35},
1514 {.rel_path = "stdlib/math.ysh", .contents = gStr36},
1515 {.rel_path = "stdlib/methods.ysh", .contents = gStr37},
1516 {.rel_path = "stdlib/osh/byo-server-lib.sh", .contents = gStr38},
1517 {.rel_path = "stdlib/osh/two.sh", .contents = gStr39},
1518 {.rel_path = "stdlib/prelude.ysh", .contents = gStr40},
1519 {.rel_path = "stdlib/stream.ysh", .contents = gStr41},
1520 {.rel_path = "stdlib/table.ysh", .contents = gStr42},
1521 {.rel_path = "stdlib/testing.ysh", .contents = gStr43},
1522
1523 {.rel_path = nullptr, .contents = nullptr},
1524};
1525
1526} // namespace embedded_file
1527
1528TextFile* gEmbeddedFiles = embedded_file::array; // turn array into pointer