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

1402 lines, 137 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 [Oils VM] OILS_VERSION LIB_OSH
228)zZXx");
229
230GLOBAL_STR(gStr14, R"zZXx(
231 Standard Library <a class="group-link" href="chap-stdlib.html">stdlib</a>
232
233
234 [two] log die
235 [no-quotes] nq-assert nq-run
236 nq-capture nq-capture-2
237 nq-redir nq-redir-2
238 [bash-strict]
239 [task-five]
240)zZXx");
241
242GLOBAL_STR(gStr15, R"zZXx(
243 OSH Types <a class="group-link" href="chap-type-method.html">type-method</a>
244
245
246 [OSH] BashArray BashAssoc
247)zZXx");
248
249GLOBAL_STR(gStr16, R"zZXx(bin/osh is compatible with POSIX shell, bash, and other shells.
250
251Usage: osh FLAG* SCRIPT ARG*
252 osh FLAG* -c COMMAND ARG*
253 osh FLAG*
254
255The command line accepted by `bin/osh` is compatible with /bin/sh and bash.
256
257 osh -c 'echo hi'
258 osh myscript.sh
259 echo 'echo hi' | osh
260
261It also has a few enhancements:
262
263 osh -n -c 'hello' # pretty-print the AST
264 osh --ast-format text -n -c 'hello' # print it full
265
266osh accepts POSIX sh flags, with these additions:
267
268 -n parse the program but don't execute it. Print the AST.
269 --ast-format what format the AST should be in
270)zZXx");
271
272GLOBAL_STR(gStr17, R"zZXx(
273 Word Language <a class="group-link" href="chap-word-lang.html">word-lang</a>
274
275
276 [Quotes] osh-string 'abc' $'line\n' "$var"
277 [Substitutions] command-sub $(command) `command`
278 var-sub ${var} $0 $9
279 arith-sub $((1 + 2))
280 tilde-sub ~/src
281 proc-sub diff <(sort L.txt) <(sort R.txt)
282 [Var Ops] op-test ${x:-default}
283 op-strip ${x%%suffix} etc.
284 op-replace ${x//y/z}
285 op-index ${a[i+1}
286 op-slice ${a[@]:0:1}
287 op-format ${x@P}
288)zZXx");
289
290GLOBAL_STR(gStr18, R"zZXx(
291 Builtin Commands <a class="group-link" href="chap-builtin-cmd.html">builtin-cmd</a>
292
293
294 [Memory] cmd/append Add elements to end of array
295 pp asdl cell X gc-stats line proc
296 [Handle Errors] error error 'failed' (status=2)
297 try Run with errexit, set _error
298 failed Test if _error.code !== 0
299 boolstatus Enforce 0 or 1 exit status
300 [Shell State] ysh-cd ysh-shopt compatible, and takes a block
301 shvar Temporary modify global settings
302 ctx Share and update a temporary "context"
303 push-registers Save registers like $?, PIPESTATUS
304 [Modules] runproc Run a proc; use as main entry point
305 module guard against duplicate 'source'
306 is-main false when sourcing a file
307 use change first word lookup
308 [I/O] ysh-read flags --all, -0
309 ysh-echo no -e -n with simple_echo
310 write Like echo, with --, --sep, --end
311 fork forkwait Replace & and (), and takes a block
312 fopen Open multiple streams, takes a block
313 X dbg Only thing that can be used in funcs
314 [Hay Config] hay haynode For DSLs and config files
315 [Completion] compadjust compexport
316 [Data Formats] json read write
317 json8 read write
318X [Testing] assert takes an expression
319)zZXx");
320
321GLOBAL_STR(gStr19, R"zZXx(
322 Builtin Functions <a class="group-link" href="chap-builtin-func.html">builtin-func</a>
323
324
325 [Values] len() func/type()
326 [Conversions] bool() int() float()
327 str() list() dict()
328 X runes() X encodeRunes()
329 X bytes() X encodeBytes()
330 [Str] X strcmp() X split() shSplit()
331 [List] join()
332 [Float] floatsEqual() X isinf() X isnan()
333 [Collections] X copy() X deepCopy()
334 [Word] glob() maybe()
335 [Serialize] toJson() fromJson()
336 toJson8() fromJson8()
337X [J8 Decode] J8.Bool() J8.Int() ...
338 [Pattern] _group() _start() _end()
339 [Introspection] shvarGet() getVar() evalExpr()
340 [Hay Config] parseHay() evalHay()
341X [Hashing] sha1dc() sha256()
342)zZXx");
343
344GLOBAL_STR(gStr20, R"zZXx(The reference is divided in to "chapters", each of which has its own table of
345contents. Type:
346
347 help ysh-$CHAPTER
348
349Where $CHAPTER is one of:
350
351 front-end
352 command-lang
353 expr-lang
354 word-lang
355 builtin-cmd
356 option
357 special-var
358 type-method
359 builtin-func
360
361Example:
362
363 help ysh-expr-lang
364)zZXx");
365
366GLOBAL_STR(gStr21, R"zZXx(
367 Command Language <a class="group-link" href="chap-cmd-lang.html">cmd-lang</a>
368
369
370 [YSH Simple] typed-arg json write (x)
371 lazy-expr-arg assert [42 === x]
372 block-arg cd /tmp { echo $PWD }; cd /tmp (; ; blockexpr)
373 [YSH Cond] ysh-case case (x) { *.py { echo 'python' } }
374 ysh-if if (x > 0) { echo }
375 [YSH Iter] ysh-while while (x > 0) { echo }
376 ysh-for for i, item in (mylist) { echo }
377)zZXx");
378
379GLOBAL_STR(gStr22, R"zZXx(
380 Expression Language and Assignments <a class="group-link" href="chap-expr-lang.html">expr-lang</a>
381
382
383 [Assignment] assign =
384 aug-assign += -= *= /= **= //= %=
385 &= |= ^= <<= >>=
386 [Literals] atom-literal true false null
387 int-literal 42 65_536 0xFF 0o755 0b10
388 float-lit 3.14 1.5e-10
389 X num-suffix 42 K Ki M Mi G Gi T Ti / ms us
390 ysh-string "x is $x" $"x is $x" r'[a-z]\n'
391 u'line\n' b'byte \yff'
392 triple-quoted """ $""" r''' u''' b'''
393 str-template ^"$a and $b" for Str::replace()
394 list-literal ['one', 'two', 3] :| unquoted words |
395 dict-literal {name: 'bob'} {a, b}
396 range 1 .. n+1
397 block-expr ^(echo $PWD)
398 expr-literal ^[1 + 2*3]
399 X expr-sub $[myobj]
400 X expr-splice @[myobj]
401 [Operators] op-precedence Like Python
402 concat s1 ++ s2, L1 ++ L2
403 ysh-equals === !== ~== is, is not
404 ysh-in in, not in
405 ysh-compare < <= > >= (numbers only)
406 ysh-logical not and or
407 ysh-arith + - * / // % **
408 ysh-bitwise ~ & | ^ << >>
409 ysh-ternary '+' if x >= 0 else '-'
410 ysh-index s[0] mylist[3] mydict['key']
411 ysh-attr mydict.key
412 ysh-slice a[1:-1] s[1:-1]
413 func-call f(x, y; ...named)
414 thin-arrow mylist->pop()
415 fat-arrow mystr => startsWith('prefix')
416 match-ops ~ !~ ~~ !~~
417 [Eggex] re-literal / d+ ; re-flags ; ERE /
418 re-primitive %zero 'sq'
419 class-literal [c a-z 'abc' @str_var \\ \xFF \u0100]
420 named-class dot digit space word d s w
421 re-repeat d? d* d+ d{3} d{2,4}
422 re-compound seq1 seq2 alt1|alt2 (expr1 expr2)
423 re-capture <capture d+ as name: int>
424 re-splice Subpattern @subpattern
425 re-flags reg_icase reg_newline
426 X re-multiline ///
427)zZXx");
428
429GLOBAL_STR(gStr23, R"zZXx(
430 Front End <a class="group-link" href="chap-front-end.html">front-end</a>
431
432
433 [Usage] oils-usage ysh-usage
434 [Lexing] ascii-whitespace [ \t\r\n]
435 doc-comment ### multiline-command ...
436 [Tools] cat-em
437)zZXx");
438
439GLOBAL_STR(gStr24, R"zZXx(
440 Other Mini Languages <a class="group-link" href="chap-mini-lang.html">mini-lang</a>
441
442
443 [Patterns] glob-pat *.py
444 [Other Sublang] braces {alice,bob}@example.com
445)zZXx");
446
447GLOBAL_STR(gStr25, R"zZXx(
448 Global Shell Options <a class="group-link" href="chap-option.html">option</a>
449
450
451 [Groups] strict:all ysh:upgrade ysh:all
452 [YSH Details] opts-redefine opts-internal
453)zZXx");
454
455GLOBAL_STR(gStr26, R"zZXx(
456 Plugins and Hooks <a class="group-link" href="chap-plugin.html">plugin</a>
457
458
459 [YSH] renderPrompt()
460)zZXx");
461
462GLOBAL_STR(gStr27, R"zZXx(
463 Special Variables <a class="group-link" href="chap-special-var.html">special-var</a>
464
465
466 [YSH Vars] ARGV X ENV X _ESCAPE
467 _this_dir
468 [YSH Status] _error
469 _pipeline_status _process_sub_status
470 [YSH Tracing] SHX_indent SHX_punct SHX_pid_str
471 [YSH read] _reply
472 [History] YSH_HISTFILE
473 [Oils VM] OILS_VERSION
474 OILS_GC_THRESHOLD OILS_GC_ON_EXIT
475 OILS_GC_STATS OILS_GC_STATS_FD
476 LIB_YSH
477 [Float] NAN INFINITY
478)zZXx");
479
480GLOBAL_STR(gStr28, R"zZXx(
481 Standard Library<a class="group-link" href="chap-stdlib.html">stdlib</a>
482
483
484 [math] abs()
485 max() min()
486 X round()
487 sum()
488 [list] all() any()
489 repeat()
490 [args] parser Parse command line arguments
491 flag
492 arg
493 rest
494 parseArgs()
495 [yblocks] yb-capture
496 yb-capture-2
497X [Lines] slurp-by combine adjacent lines into cells
498X [Awk] each-line --j8 --max-jobs (Str, Template, Block) - xargs
499 each-row --max-jobs (Str, Template, Block) - xargs
500 each-word xargs-like splitting, similar to IFS too
501 split-by (str=\n, ifs=':', pattern=/s+/)
502 if-split-by
503 chop alias for split-by (pattern=/s+/)
504 must-match (/ <capture d+> </capture w+> /)
505 if-match
506X [Table Create] table --by-row --by-col (&place); construct/parse a table
507 table/cols cols name age - cols name:Str age:Int
508 types type Str Int
509 attr attr units - secs
510 row emit row
511 table cat concatenate TSV8
512 table align to ssv8
513 table tabify to tsv8
514 table header (cols = :|name age|, types = :|Str Int|, units = :|- secs|)
515 table slice e.g. slice (1, -1) slice (5, 7)
516 table to-tsv lose type info, and error on \t in cells
517X [Table Ops] where subset of rows; dplyr filter()
518 pick subset of columns ('select' taken by shell)
519 mutate transmute [average = count / sum] - drop the ones that are used?
520 rename (bytes='bytes', path='filename')
521 group-by add a column with a group ID [ext]
522 sort-by sort by columns; dplyr arrange() [ext]
523 summary count, sum, histogram, any, all, reduce(), etc. [ext]
524)zZXx");
525
526GLOBAL_STR(gStr29, R"zZXx(
527 Types and Methods <a class="group-link" href="chap-type-method.html">type-method</a>
528
529
530 [Atom Types] Null Bool
531 [Number Types] Int Float
532 [Str] X find() replace()
533 trim() trimStart() trimEnd()
534 startsWith() endsWith()
535 upper() lower()
536 search() leftMatch()
537 [List] List/append() pop() extend() indexOf()
538 X insert() X remove() reverse()
539 [Dict] keys() values() X get() X erase()
540 X inc() X accum()
541 [Range]
542 [Eggex]
543 [Match] group() start() end()
544 X groups() X groupDict()
545 [Place] setValue()
546 [Code Types] Expr Command
547 BuiltinFunc BoundFunc
548X [Func] name() location() toJson()
549X [Proc] name() location() toJson()
550X [Module] name() filename()
551 [IO] X eval() X captureStdout()
552 promptVal()
553 X time() X strftime()
554 X glob()
555X [Guts] heapId()
556)zZXx");
557
558GLOBAL_STR(gStr30, R"zZXx(bin/ysh is the shell with data tYpes, influenced by pYthon, JavaScript, ...
559
560Usage: ysh FLAG* SCRIPT ARG*
561 ysh FLAG* -c COMMAND ARG*
562 ysh FLAG*
563
564`bin/ysh` is the same as `bin/osh` with a the `ysh:all` option group set. So
565`bin/ysh` also accepts shell flags.
566
567 ysh -c 'echo hi'
568 ysh myscript.ysh
569 echo 'echo hi' | ysh
570)zZXx");
571
572GLOBAL_STR(gStr31, R"zZXx(
573 Word Language <a class="group-link" href="chap-word-lang.html">word-lang</a>
574
575
576 [Quotes] ysh-string "x is $x" $"x is $x" r'[a-z]\n'
577 u'line\n' b'byte \yff'
578 triple-quoted """ $""" r''' u''' b'''
579 X tagged-str "<span id=$x>"html
580 [Substitutions] expr-sub echo $[42 + a[i]]
581 expr-splice echo @[split(x)]
582 var-splice @myarray @ARGV
583 command-sub @(split command)
584 [Formatting] X ysh-printf ${x %.3f}
585 X ysh-format ${x|html}
586)zZXx");
587
588GLOBAL_STR(gStr32, R"zZXx(
589 YSH Command Language Keywords <a class="group-link" href="chap-ysh-cmd.html">ysh-cmd</a>
590
591
592 [Assignment] const var Declare variables
593 setvar setvar a[i] = 42
594 setglobal setglobal d.key = 'foo'
595 [Expression] equal = = 1 + 2*3
596 call call mylist->append(42)
597 [Definitions] proc proc p (s, ...rest) {
598 typed proc p (; typed, ...rest; n=0; b) {
599 func func f(x; opt1, opt2) { return (x + 1) }
600 ysh-return return (myexpr)
601)zZXx");
602
603GLOBAL_STR(gStr33, R"zZXx(# args.ysh
604#
605# Usage:
606# source --builtin args.sh
607#
608# parser (&spec) {
609# flag -v --verbose (help="Verbosely") # default is Bool, false
610#
611# flag -P --max-procs ('int', default=-1, doc='''
612# Run at most P processes at a time
613# ''')
614#
615# flag -i --invert ('bool', default=true, doc='''
616# Long multiline
617# Description
618# ''')
619#
620# arg src (help='Source')
621# arg dest (help='Dest')
622# arg times (help='Foo')
623#
624# rest files
625# }
626#
627# var args = parseArgs(spec, ARGV)
628#
629# echo "Verbose $[args.verbose]"
630
631# TODO: See list
632# - It would be nice to keep `flag` and `arg` private, injecting them into the
633# proc namespace only within `Args`
634# - We need "type object" to replace the strings 'int', 'bool', etc.
635# - flag builtin:
636# - handle only long flag or only short flag
637# - flag aliases
638
639proc parser (; place ; ; block_def) {
640 ## Create an args spec which can be passed to parseArgs.
641 ##
642 ## Example:
643 ##
644 ## # NOTE: &spec will create a variable named spec
645 ## parser (&spec) {
646 ## flag -v --verbose ('bool')
647 ## }
648 ##
649 ## var args = parseArgs(spec, ARGV)
650
651 var p = {flags: [], args: []}
652 ctx push (p; ; block_def)
653
654 # Validate that p.rest = [name] or null and reduce p.rest into name or null.
655 if ('rest' in p) {
656 if (len(p.rest) > 1) {
657 error '`rest` was called more than once' (code=3)
658 } else {
659 setvar p.rest = p.rest[0]
660 }
661 } else {
662 setvar p.rest = null
663 }
664
665 var names = {}
666 for items in ([p.flags, p.args]) {
667 for x in (items) {
668 if (x.name in names) {
669 error "Duplicate flag/arg name $[x.name] in spec" (code=3)
670 }
671
672 setvar names[x.name] = null
673 }
674 }
675
676 # TODO: what about `flag --name` and then `arg name`?
677
678 call place->setValue(p)
679}
680
681proc flag (short, long ; type='bool' ; default=null, help=null) {
682 ## Declare a flag within an `arg-parse`.
683 ##
684 ## Examples:
685 ##
686 ## arg-parse (&spec) {
687 ## flag -v --verbose
688 ## flag -n --count ('int', default=1)
689 ## flag -f --file ('str', help="File to process")
690 ## }
691
692 # bool has a default of false, not null
693 if (type === 'bool' and default === null) {
694 setvar default = false
695 }
696
697 # TODO: validate `type`
698
699 # TODO: Should use "trimPrefix"
700 var name = long[2:]
701
702 ctx emit flags ({short, long, name, type, default, help})
703}
704
705proc arg (name ; ; help=null) {
706 ## Declare a positional argument within an `arg-parse`.
707 ##
708 ## Examples:
709 ##
710 ## arg-parse (&spec) {
711 ## arg name
712 ## arg config (help="config file path")
713 ## }
714
715 ctx emit args ({name, help})
716}
717
718proc rest (name) {
719 ## Take the remaining positional arguments within an `arg-parse`.
720 ##
721 ## Examples:
722 ##
723 ## arg-parse (&grepSpec) {
724 ## arg query
725 ## rest files
726 ## }
727
728 # We emit instead of set to detect multiple invocations of "rest"
729 ctx emit rest (name)
730}
731
732func parseArgs(spec, argv) {
733 ## Given a spec created by `parser`. Parse an array of strings `argv` per
734 ## that spec.
735 ##
736 ## See `parser` for examples of use.
737
738 var i = 0
739 var positionalPos = 0
740 var argc = len(argv)
741 var args = {}
742 var rest = []
743
744 var value
745 var found
746 while (i < argc) {
747 var arg = argv[i]
748 if (arg->startsWith('-')) {
749 setvar found = false
750
751 for flag in (spec.flags) {
752 if ( (flag.short and flag.short === arg) or
753 (flag.long and flag.long === arg) ) {
754 case (flag.type) {
755 ('bool') | (null) { setvar value = true }
756 int {
757 setvar i += 1
758 if (i >= len(argv)) {
759 error "Expected integer after '$arg'" (code=2)
760 }
761
762 try { setvar value = int(argv[i]) }
763 if (_status !== 0) {
764 error "Expected integer after '$arg', got '$[argv[i]]'" (code=2)
765 }
766 }
767 }
768
769 setvar args[flag.name] = value
770 setvar found = true
771 break
772 }
773 }
774
775 if (not found) {
776 error "Unknown flag '$arg'" (code=2)
777 }
778 } elif (positionalPos >= len(spec.args)) {
779 if (not spec.rest) {
780 error "Too many arguments, unexpected '$arg'" (code=2)
781 }
782
783 call rest->append(arg)
784 } else {
785 var pos = spec.args[positionalPos]
786 setvar positionalPos += 1
787 setvar value = arg
788 setvar args[pos.name] = value
789 }
790
791 setvar i += 1
792 }
793
794 if (spec.rest) {
795 setvar args[spec.rest] = rest
796 }
797
798 # Set defaults for flags
799 for flag in (spec.flags) {
800 if (flag.name not in args) {
801 setvar args[flag.name] = flag.default
802 }
803 }
804
805 # Raise error on missing args
806 for arg in (spec.args) {
807 if (arg.name not in args) {
808 error "Usage Error: Missing required argument $[arg.name]" (code=2)
809 }
810 }
811
812 return (args)
813}
814)zZXx");
815
816GLOBAL_STR(gStr34, R"zZXx(func identity(x) {
817 ## The identity function. Returns its argument.
818
819 return (x)
820}
821)zZXx");
822
823GLOBAL_STR(gStr35, R"zZXx(# Can we define methods in pure YSH?
824#
825# (mylist->find(42) !== -1)
826#
827# instead of
828#
829# ('42' in mylist)
830#
831# Because 'in' is for Dict
832
833func find (haystack List, needle) {
834 for i, x in (haystack) {
835 if (x === needle) {
836 return (i)
837 }
838 }
839 return (-1)
840}
841)zZXx");
842
843GLOBAL_STR(gStr36, R"zZXx(# Bash strict mode, updated for 2024
844
845set -o nounset
846set -o pipefail
847set -o errexit
848shopt -s inherit_errexit
849shopt -s strict:all 2>/dev/null || true # dogfood for OSH
850
851)zZXx");
852
853GLOBAL_STR(gStr37, R"zZXx(# Library to turn a shell file into a "BYO test server"
854#
855# Usage:
856#
857# # from both bash and OSH
858# if test -z "$LIB_OSH"; then LIB_OSH=stdlib/osh; fi
859# source $LIB_OSH/byo-server-lib.sh
860#
861# The client creates a clean process state and directory state for each tests.
862#
863# (This file requires compgen -A, and maybe declare -f, so it's not POSIX
864# shell.)
865
866: ${LIB_OSH:-stdlib/osh}
867source $LIB_OSH/two.sh
868
869byo-maybe-run() {
870 local command=${BYO_COMMAND:-}
871
872 case $command in
873 '')
874 # Do nothing if it's not specified
875 return
876 ;;
877
878 detect)
879 # all the commands supported, except 'detect'
880 echo list-tests
881 echo run-test
882
883 exit 66 # ASCII code for 'B' - what the protocol specifies
884 ;;
885
886 list-tests)
887 # bash extension that OSH also implements
888 compgen -A function | grep '^test-'
889 exit 0
890 ;;
891
892 run-test)
893 local test_name=${BYO_ARG:-}
894 if test -z "$test_name"; then
895 die "BYO run-test: Expected BYO_ARG"
896 fi
897
898 # Shell convention: we name functions test-*
899 $test_name
900
901 # Only run if not set -e. Either way it's equivalent
902 exit $?
903 ;;
904
905 *)
906 die "Invalid BYO command '$command'"
907 ;;
908 esac
909
910 # Do nothing if BYO_COMMAND is not set.
911 # The program continues to its "main".
912}
913
914byo-must-run() {
915 local command=${BYO_COMMAND:-}
916 if test -z "$command"; then
917 die "Expected BYO_COMMAND= in environment"
918 fi
919
920 byo-maybe-run
921}
922)zZXx");
923
924GLOBAL_STR(gStr38, R"zZXx(#!/usr/bin/env bash
925#
926# Testing library for bash and OSH.
927#
928# Capture status/stdout/stderr, and nq-assert those values.
929
930: ${LIB_OSH=stdlib/osh}
931source $LIB_OSH/two.sh
932
933nq-assert() {
934 ### Assertion with same syntax as shell 'test'
935
936 if ! test "$@"; then
937 die "line ${BASH_LINENO[0]}: nq-assert $(printf '%q ' "$@") failed"
938 fi
939}
940
941# Problem: we want to capture status and stdout at the same time
942#
943# We use:
944#
945# __stdout=$(set -o errexit; "$@")
946# __status=$?
947#
948# However, we lose the trailing \n, since that's how command subs work.
949
950# Here is another possibility:
951#
952# shopt -s lastpipe # need this too
953# ( set -o errexit; "$@" ) | read -r -d __stdout
954# __status=${PIPESTATUS[0]}
955# shopt -u lastpipe
956#
957# But this feels complex for just the \n issue, which can be easily worked
958# around.
959
960nq-run() {
961 ### capture status only
962
963 local -n out_status=$1
964 shift
965
966 local __status
967
968 # Tricky: turn errexit off so we can capture it, but turn it on against
969 set +o errexit
970 ( set -o errexit; "$@" )
971 __status=$?
972 set -o errexit
973
974 out_status=$__status
975}
976
977nq-capture() {
978 ### capture status and stdout
979
980 local -n out_status=$1
981 local -n out_stdout=$2
982 shift 2
983
984 local __status
985 local __stdout
986
987 # Tricky: turn errexit off so we can capture it, but turn it on against
988 set +o errexit
989 __stdout=$(set -o errexit; "$@")
990 __status=$?
991 set -o errexit
992
993 out_status=$__status
994 out_stdout=$__stdout
995}
996
997nq-capture-2() {
998 ### capture status and stderr
999
1000 # This is almost identical to the above
1001
1002 local -n out_status=$1
1003 local -n out_stderr=$2
1004 shift 2
1005
1006 local __status
1007 local __stderr
1008
1009 # Tricky: turn errexit off so we can capture it, but turn it on against
1010 set +o errexit
1011 __stderr=$(set -o errexit; "$@" 2>&1)
1012 __status=$?
1013 set -o errexit
1014
1015 out_status=$__status
1016 out_stderr=$__stderr
1017}
1018
1019# 'byo test' can set this?
1020: ${NQ_TEST_TEMP=/tmp}
1021
1022nq-redir() {
1023 ### capture status and stdout
1024
1025 local -n out_status=$1
1026 local -n out_stdout_file=$2
1027 shift 2
1028
1029 local __status
1030 local __stdout_file=$NQ_TEST_TEMP/nq-redir-$$.txt
1031
1032 # Tricky: turn errexit off so we can capture it, but turn it on against
1033 set +o errexit
1034 ( set -o errexit; "$@" ) > $__stdout_file
1035 __status=$?
1036 set -o errexit
1037
1038 out_status=$__status
1039 out_stdout_file=$__stdout_file
1040}
1041
1042nq-redir-2() {
1043 ### capture status and stdout
1044
1045 local -n out_status=$1
1046 local -n out_stderr_file=$2
1047 shift 2
1048
1049 local __status
1050 local __stderr_file=$NQ_TEST_TEMP/nq-redir-$$.txt
1051
1052 # Tricky: turn errexit off so we can capture it, but turn it on against
1053 set +o errexit
1054 ( set -o errexit; "$@" ) 2> $__stderr_file
1055 __status=$?
1056 set -o errexit
1057
1058 out_status=$__status
1059 out_stderr_file=$__stderr_file
1060}
1061)zZXx");
1062
1063GLOBAL_STR(gStr39, R"zZXx(#!/usr/bin/env bash
1064#
1065# Common shell functions for task scripts.
1066#
1067# Usage:
1068# source $LIB_OSH/task-five.sh
1069#
1070# test-foo() { # define task functions
1071# echo foo
1072# }
1073# task-five "$@"
1074
1075# Definition of a "task"
1076#
1077# - File invokes task-five "$@"
1078# - or maybe you can look at its source
1079# - It's a shell function
1080# - Has ### docstring
1081# - Doesn't start with _
1082
1083: ${LIB_OSH=stdlib/osh}
1084source $LIB_OSH/byo-server.sh
1085
1086
1087# List all functions defined in this file (and not in sourced files).
1088_bash-print-funcs() {
1089 ### Print shell functions in this file that don't start with _ (bash reflection)
1090
1091 local funcs
1092 funcs=($(compgen -A function))
1093 # extdebug makes `declare -F` print the file path, but, annoyingly, only
1094 # if you pass the function names as arguments.
1095 shopt -s extdebug
1096 declare -F "${funcs[@]}" | grep --fixed-strings " $0" | awk '{print $1}'
1097 shopt -u extdebug
1098}
1099
1100_gawk-print-funcs() {
1101 ### Print shell functions in this file that don't start with _ (awk parsing)
1102
1103 # Using gawk because it has match()
1104 # - doesn't start with _
1105
1106 # space = / ' '* /
1107 # shfunc = / %begin
1108 # <capture !['_' ' '] ![' ']*>
1109 # '()' space '{' space
1110 # %end /
1111 # docstring = / %begin
1112 # space '###' ' '+
1113 # <capture dot*>
1114 # %end /
1115 gawk '
1116 match($0, /^([^_ ][^ ]*)\(\)[ ]*{[ ]*$/, m) {
1117 #print NR " shfunc " m[1]
1118 print m[1]
1119 #print m[0]
1120 }
1121
1122 match($0, /^[ ]*###[ ]+(.*)$/, m) {
1123 print NR " docstring " m[1]
1124 }
1125' $0
1126}
1127
1128_print-funcs() {
1129 if command -v gawk > /dev/null; then
1130 _gawk-print-funcs
1131 else
1132 _bash-print-funcs
1133 fi
1134}
1135
1136_show-help() {
1137 # TODO:
1138 # - Use awk to find comments at the top of the file?
1139 # - Use OSH to extract docstrings
1140 # - BYO_COMMAND=list-tasks will reuse that logic? It only applies to the
1141 # current file, not anything in a different file?
1142
1143 echo "Usage: $0 TASK_NAME ARGS..."
1144 echo
1145 echo "To complete tasks, run:"
1146 echo " source devtools/completion.bash"
1147 echo
1148 echo "Tasks:"
1149
1150 if command -v column >/dev/null; then
1151 _print-funcs | column
1152 else
1153 _print-funcs
1154 fi
1155}
1156
1157task-five() {
1158 # Respond to BYO_COMMAND=list-tasks, etc. All task files need this.
1159 byo-maybe-run
1160
1161 case ${1:-} in
1162 ''|--help|-h)
1163 _show-help
1164 exit 0
1165 ;;
1166 esac
1167
1168 if ! declare -f "$1" >/dev/null; then
1169 echo "$0: '$1' isn't an action in this task file. Try '$0 --help'"
1170 exit 1
1171 fi
1172
1173 "$@"
1174}
1175)zZXx");
1176
1177GLOBAL_STR(gStr40, R"zZXx(# Two functions I actually use, all the time.
1178#
1179# To keep depenedencies small, this library will NEVER grow other functions
1180# (and is named to imply that.)
1181#
1182# Usage:
1183# source --builtin two.sh
1184#
1185# Examples:
1186# log 'hi'
1187# die 'expected a number'
1188
1189if command -v source-guard >/dev/null; then # include guard for YSH
1190 source-guard two || return 0
1191fi
1192
1193log() {
1194 ### Write a message to stderr.
1195 echo "$@" >&2
1196}
1197
1198die() {
1199 ### Write an error message with the script name, and exit with status 1.
1200 log "$0: fatal: $@"
1201 exit 1
1202}
1203
1204)zZXx");
1205
1206GLOBAL_STR(gStr41, R"zZXx(# These were helpful while implementing args.ysh
1207# Maybe we will want to export them in a prelude so that others can use them too?
1208#
1209# Prior art: Rust has `todo!()` which is quite nice. Other languages allow
1210# users to `raise NotImplmentedError()`.
1211
1212# Andy comments:
1213# - 'pass' can be : or true in shell. It's a little obscure / confusing, but
1214# there is an argument for minimalism. Although I prefer words like 'true',
1215# and that already means something.
1216# - UPDATE: we once took 'pass' as a keyword, but users complained because
1217# there is a command 'pass'. So we probably can't have this by default.
1218# Need to discuss source --builtin.
1219
1220# - todo could be more static? Rust presumably does it at compile time
1221
1222proc todo () {
1223 ## Raises a not implemented error when run.
1224 error ("TODO: not implemented") # TODO: is error code 1 ok?
1225}
1226
1227proc pass () {
1228 ## Use when you want to temporarily leave a block empty.
1229 _ null
1230}
1231)zZXx");
1232
1233GLOBAL_STR(gStr42, R"zZXx(# testing.ysh
1234#
1235# Usage:
1236# source --builtin testing.sh
1237#
1238# func f(x) { return (x + 1) }
1239#
1240# describe foo {
1241# assert (43 === f(42))
1242# }
1243#
1244# if is-main {
1245# run-tests @ARGV # --filter
1246# }
1247
1248module stdlib/testing || return 0
1249
1250source --builtin args.ysh
1251
1252proc assert ( ; cond ; fail_message='default fail message') {
1253 echo 'hi from assert'
1254
1255 = cond
1256
1257 # I think this might be ready now?
1258
1259 var val = evalExpr(cond)
1260
1261 echo
1262 echo 'value'
1263 = val
1264 pp line (val)
1265
1266 = fail_message
1267
1268 if (val) {
1269 echo 'OK'
1270 } else {
1271 var m = evalExpr(fail_message)
1272 echo "FAIL - this is where we extract the string - $m"
1273 }
1274}
1275
1276proc test-assert {
1277 var x = 42
1278 assert [42 === x]
1279}
1280
1281proc test-expr ( ; expr ) {
1282 echo 'expr'
1283 pp line (expr)
1284}
1285
1286proc test-named ( ; ; n=^[99] ) {
1287 echo 'n'
1288 pp line (n)
1289}
1290
1291# What happens when there are duplicate test IDs?
1292#
1293# Also I think filter by "$test_id/$case_id"
1294
1295proc __it (case_id ; ; ; block) {
1296 # This uses a clean directory
1297 echo TODO
1298}
1299
1300# is this accessible to users?
1301# It can contain a global list of things to run
1302
1303# Naming convention: a proc named 'describe' mutates a global named _describe?
1304# Or maybe _describe_list ?
1305
1306var _describe_list = []
1307
1308proc describe (test_id ; ; ; block) {
1309 echo describe
1310 #= desc
1311
1312 # TODO:
1313 # - need append
1314 # - need ::
1315 # _ _describe->append(cmd)
1316 #
1317 # Need to clean this up
1318 # append (_describe, cmd) # does NOT work!
1319
1320 call _describe_list->append(block)
1321}
1322
1323proc Args {
1324 echo TODO
1325}
1326
1327# Problem: this creates a global variable?
1328Args (&spec) {
1329 flag --filter 'Regex of test descriptions'
1330}
1331
1332proc run-tests {
1333 var opt, i = parseArgs(spec, ARGV)
1334
1335 # TODO:
1336 # - parse --filter foo, which you can use eggex for!
1337
1338 for cmd in (_describe) {
1339 # TODO: print filename and 'describe' name?
1340 try {
1341 eval (cmd)
1342 }
1343 if (_status !== 0) {
1344 echo 'failed'
1345 }
1346 }
1347}
1348)zZXx");
1349
1350
1351
1352TextFile array[] = {
1353 {.rel_path = "_devbuild/help/data-errors", .contents = gStr0},
1354 {.rel_path = "_devbuild/help/data-front-end", .contents = gStr1},
1355 {.rel_path = "_devbuild/help/data-j8-notation", .contents = gStr2},
1356 {.rel_path = "_devbuild/help/help", .contents = gStr3},
1357 {.rel_path = "_devbuild/help/oils-usage", .contents = gStr4},
1358 {.rel_path = "_devbuild/help/osh-builtin-cmd", .contents = gStr5},
1359 {.rel_path = "_devbuild/help/osh-chapters", .contents = gStr6},
1360 {.rel_path = "_devbuild/help/osh-cmd-lang", .contents = gStr7},
1361 {.rel_path = "_devbuild/help/osh-front-end", .contents = gStr8},
1362 {.rel_path = "_devbuild/help/osh-mini-lang", .contents = gStr9},
1363 {.rel_path = "_devbuild/help/osh-option", .contents = gStr10},
1364 {.rel_path = "_devbuild/help/osh-osh-assign", .contents = gStr11},
1365 {.rel_path = "_devbuild/help/osh-plugin", .contents = gStr12},
1366 {.rel_path = "_devbuild/help/osh-special-var", .contents = gStr13},
1367 {.rel_path = "_devbuild/help/osh-stdlib", .contents = gStr14},
1368 {.rel_path = "_devbuild/help/osh-type-method", .contents = gStr15},
1369 {.rel_path = "_devbuild/help/osh-usage", .contents = gStr16},
1370 {.rel_path = "_devbuild/help/osh-word-lang", .contents = gStr17},
1371 {.rel_path = "_devbuild/help/ysh-builtin-cmd", .contents = gStr18},
1372 {.rel_path = "_devbuild/help/ysh-builtin-func", .contents = gStr19},
1373 {.rel_path = "_devbuild/help/ysh-chapters", .contents = gStr20},
1374 {.rel_path = "_devbuild/help/ysh-cmd-lang", .contents = gStr21},
1375 {.rel_path = "_devbuild/help/ysh-expr-lang", .contents = gStr22},
1376 {.rel_path = "_devbuild/help/ysh-front-end", .contents = gStr23},
1377 {.rel_path = "_devbuild/help/ysh-mini-lang", .contents = gStr24},
1378 {.rel_path = "_devbuild/help/ysh-option", .contents = gStr25},
1379 {.rel_path = "_devbuild/help/ysh-plugin", .contents = gStr26},
1380 {.rel_path = "_devbuild/help/ysh-special-var", .contents = gStr27},
1381 {.rel_path = "_devbuild/help/ysh-stdlib", .contents = gStr28},
1382 {.rel_path = "_devbuild/help/ysh-type-method", .contents = gStr29},
1383 {.rel_path = "_devbuild/help/ysh-usage", .contents = gStr30},
1384 {.rel_path = "_devbuild/help/ysh-word-lang", .contents = gStr31},
1385 {.rel_path = "_devbuild/help/ysh-ysh-cmd", .contents = gStr32},
1386 {.rel_path = "stdlib/args.ysh", .contents = gStr33},
1387 {.rel_path = "stdlib/funcs.ysh", .contents = gStr34},
1388 {.rel_path = "stdlib/methods.ysh", .contents = gStr35},
1389 {.rel_path = "stdlib/osh/bash-strict.sh", .contents = gStr36},
1390 {.rel_path = "stdlib/osh/byo-server.sh", .contents = gStr37},
1391 {.rel_path = "stdlib/osh/no-quotes.sh", .contents = gStr38},
1392 {.rel_path = "stdlib/osh/task-five.sh", .contents = gStr39},
1393 {.rel_path = "stdlib/osh/two.sh", .contents = gStr40},
1394 {.rel_path = "stdlib/prelude.ysh", .contents = gStr41},
1395 {.rel_path = "stdlib/testing.ysh", .contents = gStr42},
1396
1397 {.rel_path = nullptr, .contents = nullptr},
1398};
1399
1400} // namespace embedded_file
1401
1402TextFile* gEmbeddedFiles = embedded_file::array; // turn array into pointer