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

1156 lines, 123 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 [[ -z '' ]]
157 bool-other [[ -o errexit ]]
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
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 OSH Types <a class="group-link" href="chap-type-method.html">type-method</a>
231
232
233 [OSH] BashArray BashAssoc
234)zZXx");
235
236GLOBAL_STR(gStr15, R"zZXx(bin/osh is compatible with POSIX shell, bash, and other shells.
237
238Usage: osh FLAG* SCRIPT ARG*
239 osh FLAG* -c COMMAND ARG*
240 osh FLAG*
241
242The command line accepted by `bin/osh` is compatible with /bin/sh and bash.
243
244 osh -c 'echo hi'
245 osh myscript.sh
246 echo 'echo hi' | osh
247
248It also has a few enhancements:
249
250 osh -n -c 'hello' # pretty-print the AST
251 osh --ast-format text -n -c 'hello' # print it full
252
253osh accepts POSIX sh flags, with these additions:
254
255 -n parse the program but don't execute it. Print the AST.
256 --ast-format what format the AST should be in
257)zZXx");
258
259GLOBAL_STR(gStr16, R"zZXx(
260 Word Language <a class="group-link" href="chap-word-lang.html">word-lang</a>
261
262
263 [Quotes] osh-string 'abc' $'line\n' "$var"
264 [Substitutions] command-sub $(command) `command`
265 var-sub ${var} $0 $9
266 arith-sub $((1 + 2))
267 tilde-sub ~/src
268 proc-sub diff <(sort L.txt) <(sort R.txt)
269 [Var Ops] op-test ${x:-default}
270 op-strip ${x%%suffix} etc.
271 op-replace ${x//y/z}
272 op-index ${a[i+1}
273 op-slice ${a[@]:0:1}
274 op-format ${x@P}
275)zZXx");
276
277GLOBAL_STR(gStr17, R"zZXx(
278 Builtin Commands <a class="group-link" href="chap-builtin-cmd">builtin-cmd</a>
279
280
281 [Memory] cmd/append Add elements to end of array
282 pp asdl cell X gc-stats line proc
283 [Handle Errors] try Run with errexit, set _status _error
284 boolstatus Enforce 0 or 1 exit status
285 error error 'failed' (status=2)
286 [Shell State] ysh-cd ysh-shopt compatible, and takes a block
287 shvar Temporary modify global settings
288 ctx Share and update a temporary "context"
289 push-registers Save registers like $?, PIPESTATUS
290 [Modules] runproc Run a proc; use as main entry point
291 module guard against duplicate 'source'
292 is-main false when sourcing a file
293 use change first word lookup
294 [I/O] ysh-read flags --all, -0
295 ysh-echo no -e -n with simple_echo
296 write Like echo, with --, --sep, --end
297 fork forkwait Replace & and (), and takes a block
298 fopen Open multiple streams, takes a block
299 X dbg Only thing that can be used in funcs
300 X log X die Common functions (polyfill)
301 [Hay Config] hay haynode For DSLs and config files
302 [Completion] compadjust compexport
303 [Data Formats] json read write
304 json8 read write
305X [TSV8] rows pick rows; dplyr filter()
306 cols pick columns ('select' already taken)
307 group-by add a column with a group ID [ext]
308 sort-by sort by columns; dplyr arrange() [ext]
309 summary count, sum, histogram, etc. [ext]
310 [Args Parser] parser Parse command line arguments
311 flag
312 arg
313 rest
314 parseArgs()
315X [Testing] describe Test harness
316 assert takes an expression
317)zZXx");
318
319GLOBAL_STR(gStr18, R"zZXx(
320 Builtin Functions <a class="group-link" href="chap-builtin-func.html">builtin-func</a>
321
322
323 [Values] len() func/type() X repeat()
324 [Conversions] bool() int() float() str() list() dict()
325 X chr() X ord() X runes()
326 [Str] X strcmp() X split() shSplit()
327 [List] join() any() all()
328 [Collections] X copy() X deepCopy()
329 [Word] glob() maybe()
330 [Math] abs() max() min() X round() sum()
331 [Serialize] toJson() fromJson()
332 toJson8() fromJson8()
333X [J8 Decode] J8.Bool() J8.Int() ...
334 [Pattern] _group() _start() _end()
335 [Introspection] shvarGet() getVar() evalExpr()
336 [Hay Config] parseHay() evalHay()
337X [Hashing] sha1dc() sha256()
338)zZXx");
339
340GLOBAL_STR(gStr19, R"zZXx(The reference is divided in to "chapters", each of which has its own table of
341contents. Type:
342
343 help ysh-$CHAPTER
344
345Where $CHAPTER is one of:
346
347 front-end
348 command-lang
349 expr-lang
350 word-lang
351 builtin-cmd
352 option
353 special-var
354 type-method
355 builtin-func
356
357Example:
358
359 help ysh-expr-lang
360)zZXx");
361
362GLOBAL_STR(gStr20, R"zZXx(
363 Command Language <a class="group-link" href="chap-cmd-lang.html">cmd-lang</a>
364
365
366 [YSH Simple] typed-arg json write (x)
367 lazy-expr-arg assert [42 === x]
368 block-arg cd /tmp { echo $PWD }; cd /tmp (; ; blockexpr)
369 [YSH Cond] ysh-case case (x) { *.py { echo 'python' } }
370 ysh-if if (x > 0) { echo }
371 [YSH Iter] ysh-while while (x > 0) { echo }
372 ysh-for for i, item in (mylist) { echo }
373)zZXx");
374
375GLOBAL_STR(gStr21, R"zZXx(
376 Expression Language and Assignments <a class="group-link" href="chap-expr-lang.html">expr-lang</a>
377
378
379 [Assignment] assign =
380 aug-assign += -= *= /= **= //= %=
381 &= |= ^= <<= >>=
382 [Literals] atom-literal true false null
383 int-literal 42 65_536 0xFF 0o755 0b10
384 float-lit 3.14 1.5e-10
385 X num-suffix 42 K Ki M Mi G Gi T Ti / ms us
386 ysh-string "x is $x" $"x is $x" r'[a-z]\n'
387 u'line\n' b'byte \yff'
388 triple-quoted """ $""" r''' u''' b'''
389 str-template ^"$a and $b" for Str::replace()
390 list-literal ['one', 'two', 3] :| unquoted words |
391 dict-literal {name: 'bob'} {a, b}
392 range 1 .. n+1
393 block-expr ^(echo $PWD)
394 expr-literal ^[1 + 2*3]
395 X expr-sub $[myobj]
396 X expr-splice @[myobj]
397 [Operators] op-precedence Like Python
398 concat s1 ++ s2, L1 ++ L2
399 ysh-equals === !== ~== is, is not
400 ysh-in in, not in
401 ysh-compare < <= > >= (numbers only)
402 ysh-logical not and or
403 ysh-arith + - * / // % **
404 ysh-bitwise ~ & | ^ << >>
405 ysh-ternary '+' if x >= 0 else '-'
406 ysh-index s[0] mylist[3] mydict['key']
407 ysh-attr mydict.key
408 ysh-slice a[1:-1] s[1:-1]
409 func-call f(x, y; ...named)
410 thin-arrow mylist->pop()
411 fat-arrow mystr => startsWith('prefix')
412 match-ops ~ !~ ~~ !~~
413 [Eggex] re-literal / d+ ; re-flags ; ERE /
414 re-primitive %zero 'sq'
415 class-literal [c a-z 'abc' @str_var \\ \xFF \u0100]
416 named-class dot digit space word d s w
417 re-repeat d? d* d+ d{3} d{2,4}
418 re-compound seq1 seq2 alt1|alt2 (expr1 expr2)
419 re-capture <capture d+ as name: int>
420 re-splice Subpattern @subpattern
421 re-flags reg_icase reg_newline
422 X re-multiline ///
423)zZXx");
424
425GLOBAL_STR(gStr22, R"zZXx(
426 Front End <a class="group-link" href="chap-front-end.html">front-end</a>
427
428
429 [Usage] oils-usage ysh-usage
430 [Lexing] ascii-whitespace [ \t\r\n]
431 doc-comment ### multiline-command ...
432 [Tools] cat-em
433)zZXx");
434
435GLOBAL_STR(gStr23, R"zZXx(
436 Other Mini Languages <a class="group-link" href="chap-mini-lang.html">mini-lang</a>
437
438
439 [Patterns] glob-pat *.py
440 [Other Sublang] braces {alice,bob}@example.com
441)zZXx");
442
443GLOBAL_STR(gStr24, R"zZXx(
444 Global Shell Options <a class="group-link" href="chap-option.html">option</a>
445
446
447 [Groups] strict:all ysh:upgrade ysh:all
448 [YSH Details] opts-redefine opts-internal
449)zZXx");
450
451GLOBAL_STR(gStr25, R"zZXx(
452 Plugins and Hooks <a class="group-link" href="chap-plugin.html">plugin</a>
453
454
455 [YSH] renderPrompt()
456)zZXx");
457
458GLOBAL_STR(gStr26, R"zZXx(
459 Special Variables <a class="group-link" href="chap-special-var.html">special-var</a>
460
461
462 [YSH Vars] ARGV X ENV X _ESCAPE
463 _this_dir
464 [YSH Status] _status _error
465 _pipeline_status _process_sub_status
466 [YSH Tracing] SHX_indent SHX_punct SHX_pid_str
467 [YSH read] _reply
468 [History] YSH_HISTFILE
469 [Oils VM] OILS_VERSION
470 OILS_GC_THRESHOLD OILS_GC_ON_EXIT
471 OILS_GC_STATS OILS_GC_STATS_FD
472)zZXx");
473
474GLOBAL_STR(gStr27, R"zZXx(
475 Types and Methods <a class="group-link" href="chap-type-method.html">type-method</a>
476
477
478 [Atom Types] Null Bool
479 [Number Types] Int Float
480 [Str] X find() replace()
481 trim() trimStart() trimEnd()
482 startsWith() endsWith()
483 upper() lower()
484 search() leftMatch()
485 [List] List/append() pop() extend() indexOf()
486 X insert() X remove() reverse()
487 [Dict] keys() values() X get() X erase()
488 X inc() X accum()
489 [Range]
490 [Eggex]
491 [Match] group() start() end()
492 X groups() X groupDict()
493 [Place] setValue()
494 [Code Types] Expr Command
495 BuiltinFunc BoundFunc
496X [Func] name() location() toJson()
497X [Proc] name() location() toJson()
498X [Module] name() filename()
499 [IO] X eval() X captureStdout()
500 promptVal()
501 X time() X strftime()
502 X glob()
503X [Guts] heapId()
504)zZXx");
505
506GLOBAL_STR(gStr28, R"zZXx(bin/ysh is the shell with data tYpes, influenced by pYthon, JavaScript, ...
507
508Usage: ysh FLAG* SCRIPT ARG*
509 ysh FLAG* -c COMMAND ARG*
510 ysh FLAG*
511
512`bin/ysh` is the same as `bin/osh` with a the `ysh:all` option group set. So
513`bin/ysh` also accepts shell flags.
514
515 ysh -c 'echo hi'
516 ysh myscript.ysh
517 echo 'echo hi' | ysh
518)zZXx");
519
520GLOBAL_STR(gStr29, R"zZXx(
521 Word Language <a class="group-link" href="chap-word-lang.html">word-lang</a>
522
523
524 [Quotes] ysh-string "x is $x" $"x is $x" r'[a-z]\n'
525 u'line\n' b'byte \yff'
526 triple-quoted """ $""" r''' u''' b'''
527 X tagged-str "<span id=$x>"html
528 [Substitutions] expr-sub echo $[42 + a[i]]
529 expr-splice echo @[split(x)]
530 var-splice @myarray @ARGV
531 command-sub @(split command)
532 [Formatting] X ysh-printf ${x %.3f}
533 X ysh-format ${x|html}
534)zZXx");
535
536GLOBAL_STR(gStr30, R"zZXx(
537 YSH Command Language Keywords <a class="group-link" href="chap-ysh-cmd.html">ysh-cmd</a>
538
539
540 [Assignment] const var Declare variables
541 setvar setvar a[i] = 42
542 setglobal setglobal d.key = 'foo'
543 [Expression] equal = = 1 + 2*3
544 call call mylist->append(42)
545 [Definitions] proc proc p (s, ...rest) {
546 typed proc p (; typed, ...rest; n=0; b) {
547 func func f(x; opt1, opt2) { return (x + 1) }
548 ysh-return return (myexpr)
549)zZXx");
550
551GLOBAL_STR(gStr31, R"zZXx(# args.ysh
552#
553# Usage:
554# source --builtin args.sh
555#
556# parser (&spec) {
557# flag -v --verbose (help="Verbosely") # default is Bool, false
558#
559# flag -P --max-procs ('int', default=-1, doc='''
560# Run at most P processes at a time
561# ''')
562#
563# flag -i --invert ('bool', default=true, doc='''
564# Long multiline
565# Description
566# ''')
567#
568# arg src (help='Source')
569# arg dest (help='Dest')
570# arg times (help='Foo')
571#
572# rest files
573# }
574#
575# var args = parseArgs(spec, ARGV)
576#
577# echo "Verbose $[args.verbose]"
578
579# TODO: See list
580# - It would be nice to keep `flag` and `arg` private, injecting them into the
581# proc namespace only within `Args`
582# - We need "type object" to replace the strings 'int', 'bool', etc.
583# - flag builtin:
584# - handle only long flag or only short flag
585# - flag aliases
586
587proc parser (; place ; ; block_def) {
588 ## Create an args spec which can be passed to parseArgs.
589 ##
590 ## Example:
591 ##
592 ## # NOTE: &spec will create a variable named spec
593 ## parser (&spec) {
594 ## flag -v --verbose ('bool')
595 ## }
596 ##
597 ## var args = parseArgs(spec, ARGV)
598
599 var p = {flags: [], args: []}
600 ctx push (p; ; block_def)
601
602 # Validate that p.rest = [name] or null and reduce p.rest into name or null.
603 if ('rest' in p) {
604 if (len(p.rest) > 1) {
605 error '`rest` was called more than once' (status=3)
606 } else {
607 setvar p.rest = p.rest[0]
608 }
609 } else {
610 setvar p.rest = null
611 }
612
613 var names = {}
614 for items in ([p.flags, p.args]) {
615 for x in (items) {
616 if (x.name in names) {
617 error "Duplicate flag/arg name $[x.name] in spec" (status=3)
618 }
619
620 setvar names[x.name] = null
621 }
622 }
623
624 # TODO: what about `flag --name` and then `arg name`?
625
626 call place->setValue(p)
627}
628
629proc flag (short, long ; type='bool' ; default=null, help=null) {
630 ## Declare a flag within an `arg-parse`.
631 ##
632 ## Examples:
633 ##
634 ## arg-parse (&spec) {
635 ## flag -v --verbose
636 ## flag -n --count ('int', default=1)
637 ## flag -f --file ('str', help="File to process")
638 ## }
639
640 # bool has a default of false, not null
641 if (type === 'bool' and default === null) {
642 setvar default = false
643 }
644
645 # TODO: validate `type`
646
647 # TODO: Should use "trimPrefix"
648 var name = long[2:]
649
650 ctx emit flags ({short, long, name, type, default, help})
651}
652
653proc arg (name ; ; help=null) {
654 ## Declare a positional argument within an `arg-parse`.
655 ##
656 ## Examples:
657 ##
658 ## arg-parse (&spec) {
659 ## arg name
660 ## arg config (help="config file path")
661 ## }
662
663 ctx emit args ({name, help})
664}
665
666proc rest (name) {
667 ## Take the remaining positional arguments within an `arg-parse`.
668 ##
669 ## Examples:
670 ##
671 ## arg-parse (&grepSpec) {
672 ## arg query
673 ## rest files
674 ## }
675
676 # We emit instead of set to detect multiple invocations of "rest"
677 ctx emit rest (name)
678}
679
680func parseArgs(spec, argv) {
681 ## Given a spec created by `parser`. Parse an array of strings `argv` per
682 ## that spec.
683 ##
684 ## See `parser` for examples of use.
685
686 var i = 0
687 var positionalPos = 0
688 var argc = len(argv)
689 var args = {}
690 var rest = []
691
692 var value
693 var found
694 while (i < argc) {
695 var arg = argv[i]
696 if (arg->startsWith('-')) {
697 setvar found = false
698
699 for flag in (spec.flags) {
700 if ( (flag.short and flag.short === arg) or
701 (flag.long and flag.long === arg) ) {
702 case (flag.type) {
703 ('bool') | (null) { setvar value = true }
704 int {
705 setvar i += 1
706 if (i >= len(argv)) {
707 error "Expected integer after '$arg'" (status=2)
708 }
709
710 try { setvar value = int(argv[i]) }
711 if (_status !== 0) {
712 error "Expected integer after '$arg', got '$[argv[i]]'" (status=2)
713 }
714 }
715 }
716
717 setvar args[flag.name] = value
718 setvar found = true
719 break
720 }
721 }
722
723 if (not found) {
724 error "Unknown flag '$arg'" (status=2)
725 }
726 } elif (positionalPos >= len(spec.args)) {
727 if (not spec.rest) {
728 error "Too many arguments, unexpected '$arg'" (status=2)
729 }
730
731 call rest->append(arg)
732 } else {
733 var pos = spec.args[positionalPos]
734 setvar positionalPos += 1
735 setvar value = arg
736 setvar args[pos.name] = value
737 }
738
739 setvar i += 1
740 }
741
742 if (spec.rest) {
743 setvar args[spec.rest] = rest
744 }
745
746 # Set defaults for flags
747 for flag in (spec.flags) {
748 if (flag.name not in args) {
749 setvar args[flag.name] = flag.default
750 }
751 }
752
753 # Raise error on missing args
754 for arg in (spec.args) {
755 if (arg.name not in args) {
756 error "Usage Error: Missing required argument $[arg.name]" (status=2)
757 }
758 }
759
760 return (args)
761}
762)zZXx");
763
764GLOBAL_STR(gStr32, R"zZXx(#!/usr/bin/env ysh
765
766module stdlib/synch || return 0
767
768############################
769### FIFO File Desriptors ###
770############################
771
772proc fifo-fd-new(; out_fd) {
773 # WARN: this section should be critical but for now it's not
774 # A solution may be retry on fail.
775 #====================
776 var fifo = $(mktemp -u)
777 mkfifo $fifo
778 #====================
779 exec {fd}<>$fifo
780 call out_fd->setValue(fd)
781}
782
783proc fifo-fd-destroy(; fd) {
784 var fifoFile = $(readlink /proc/$$/fd/$fd)
785 exec {fd}>&-
786 exec {fd}<&-
787 rm $fifoFile
788}
789
790#################
791### Semaphore ###
792#################
793
794proc sema-new(; value, out_sema) {
795 fifo-fd-new (&sema)
796 sema-up (sema, value)
797 call out_sema->setValue(sema)
798}
799
800proc sema-down(; sema) {
801 read <&$sema
802}
803
804proc sema-up(; sema, delta = 1) {
805 fork {
806 for _ in (0 .. delta) {
807 echo >&$sema
808 }
809 }
810}
811
812proc sema-destroy(; sema) {
813 fifo-fd-destroy (sema)
814}
815)zZXx");
816
817GLOBAL_STR(gStr33, R"zZXx(func identity(x) {
818 ## The identity function. Returns its argument.
819
820 return (x)
821}
822)zZXx");
823
824GLOBAL_STR(gStr34, R"zZXx(func any(list) {
825 ## Returns true if any value in the list is truthy.
826 ##
827 ## If the list is empty, return false.
828
829 for item in (list) {
830 if (item) {
831 return (true)
832 }
833 }
834 return (false)
835}
836
837func all(list) {
838 ## Returns true if all values in the list are truthy.
839 ##
840 ## If the list is empty, return true.
841
842 for item in (list) {
843 if (not item) {
844 return (false)
845 }
846 }
847 return (true)
848}
849
850func sum(list; start=0) {
851 ## Computes the sum of all elements in the list.
852 ##
853 ## Returns 0 for an empty list.
854
855 var sum = start
856 for item in (list) {
857 setvar sum += item
858 }
859 return (sum)
860}
861)zZXx");
862
863GLOBAL_STR(gStr35, R"zZXx(func __math_select(list, cmp) {
864 ## Internal helper for `max` and `min`.
865 ##
866 ## NOTE: If `list` is empty, then an error is thrown.
867
868 if (len(list) === 0) {
869 error "Unexpected empty list" (status=3)
870 }
871
872 if (len(list) === 1) {
873 return (list[0])
874 }
875
876 var match = list[0]
877 for i in (1 .. len(list)) {
878 setvar match = cmp(list[i], match)
879 }
880 return (match)
881}
882
883func max(...args) {
884 ## Compute the maximum of 2 or more values.
885 ##
886 ## `max` takes two different signatures:
887 ## - `max(a, b)` to return the maximum of `a`, `b`
888 ## - `max(list)` to return the greatest item in the `list`
889 ##
890 ## So, for example:
891 ##
892 ## max(1, 2) # => 2
893 ## max([1, 2, 3]) # => 3
894
895 case (len(args)) {
896 (1) { return (__math_select(args[0], max)) }
897 (2) {
898 if (args[0] > args[1]) {
899 return (args[0])
900 } else {
901 return (args[1])
902 }
903 }
904 (else) { error "max expects 1 or 2 args" (status=3) }
905 }
906}
907
908func min(...args) {
909 ## Compute the minimum of 2 or more values.
910 ##
911 ## `min` takes two different signatures:
912 ## - `min(a, b)` to return the minimum of `a`, `b`
913 ## - `min(list)` to return the least item in the `list`
914 ##
915 ## So, for example:
916 ##
917 ## min(2, 3) # => 2
918 ## max([1, 2, 3]) # => 1
919
920 case (len(args)) {
921 (1) { return (__math_select(args[0], min)) }
922 (2) {
923 if (args[0] < args[1]) {
924 return (args[0])
925 } else {
926 return (args[1])
927 }
928 }
929 (else) { error "min expects 1 or 2 args" (status=3) }
930 }
931}
932
933func abs(x) {
934 ## Compute the absolute (positive) value of a number (float or int).
935
936 if (x < 0) {
937 return (-x)
938 } else {
939 return (x)
940 }
941}
942)zZXx");
943
944GLOBAL_STR(gStr36, R"zZXx(# Can we define methods in pure YSH?
945#
946# (mylist->find(42) !== -1)
947#
948# instead of
949#
950# ('42' in mylist)
951#
952# Because 'in' is for Dict
953
954func find (haystack List, needle) {
955 for i, x in (haystack) {
956 if (x === needle) {
957 return (i)
958 }
959 }
960 return (-1)
961}
962)zZXx");
963
964GLOBAL_STR(gStr37, R"zZXx(# These were helpful while implementing args.ysh
965# Maybe we will want to export them in a prelude so that others can use them too?
966#
967# Prior art: Rust has `todo!()` which is quite nice. Other languages allow
968# users to `raise NotImplmentedError()`.
969
970# Andy comments:
971# - 'pass' can be : or true in shell. It's a little obscure / confusing, but
972# there is an argument for minimalism. Although I prefer words like 'true',
973# and that already means something.
974# - UPDATE: we once took 'pass' as a keyword, but users complained because
975# there is a command 'pass'. So we probably can't have this by default.
976# Need to discuss source --builtin.
977
978# - todo could be more static? Rust presumably does it at compile time
979
980proc todo () {
981 ## Raises a not implemented error when run.
982 error ("TODO: not implemented") # TODO: is error code 1 ok?
983}
984
985proc pass () {
986 ## Use when you want to temporarily leave a block empty.
987 _ null
988}
989)zZXx");
990
991GLOBAL_STR(gStr38, R"zZXx(# testing.ysh
992#
993# Usage:
994# source --builtin testing.sh
995#
996# func f(x) { return (x + 1) }
997#
998# describe foo {
999# assert (43 === f(42))
1000# }
1001#
1002# if is-main {
1003# run-tests @ARGV # --filter
1004# }
1005
1006module stdlib/testing || return 0
1007
1008source --builtin args.ysh
1009
1010proc assert ( ; cond ; fail_message='default fail message') {
1011 echo 'hi from assert'
1012
1013 = cond
1014
1015 # I think this might be ready now?
1016
1017 var val = evalExpr(cond)
1018
1019 echo
1020 echo 'value'
1021 = val
1022 pp line (val)
1023
1024 = fail_message
1025
1026 if (val) {
1027 echo 'OK'
1028 } else {
1029 var m = evalExpr(fail_message)
1030 echo "FAIL - this is where we extract the string - $m"
1031 }
1032}
1033
1034proc test-assert {
1035 var x = 42
1036 assert [42 === x]
1037}
1038
1039proc test-expr ( ; expr ) {
1040 echo 'expr'
1041 pp line (expr)
1042}
1043
1044proc test-named ( ; ; n=^[99] ) {
1045 echo 'n'
1046 pp line (n)
1047}
1048
1049# What happens when there are duplicate test IDs?
1050#
1051# Also I think filter by "$test_id/$case_id"
1052
1053proc __it (case_id ; ; ; block) {
1054 # This uses a clean directory
1055 echo TODO
1056}
1057
1058# is this accessible to users?
1059# It can contain a global list of things to run
1060
1061# Naming convention: a proc named 'describe' mutates a global named _describe?
1062# Or maybe _describe_list ?
1063
1064var _describe_list = []
1065
1066proc describe (test_id ; ; ; block) {
1067 echo describe
1068 #= desc
1069
1070 # TODO:
1071 # - need append
1072 # - need ::
1073 # _ _describe->append(cmd)
1074 #
1075 # Need to clean this up
1076 # append (_describe, cmd) # does NOT work!
1077
1078 call _describe_list->append(block)
1079}
1080
1081proc Args {
1082 echo TODO
1083}
1084
1085# Problem: this creates a global variable?
1086Args (&spec) {
1087 flag --filter 'Regex of test descriptions'
1088}
1089
1090proc run-tests {
1091 var opt, i = parseArgs(spec, ARGV)
1092
1093 # TODO:
1094 # - parse --filter foo, which you can use eggex for!
1095
1096 for cmd in (_describe) {
1097 # TODO: print filename and 'describe' name?
1098 try {
1099 eval (cmd)
1100 }
1101 if (_status !== 0) {
1102 echo 'failed'
1103 }
1104 }
1105}
1106)zZXx");
1107
1108
1109
1110TextFile array[] = {
1111 {.rel_path = "_devbuild/help/data-errors", .contents = gStr0},
1112 {.rel_path = "_devbuild/help/data-front-end", .contents = gStr1},
1113 {.rel_path = "_devbuild/help/data-j8-notation", .contents = gStr2},
1114 {.rel_path = "_devbuild/help/help", .contents = gStr3},
1115 {.rel_path = "_devbuild/help/oils-usage", .contents = gStr4},
1116 {.rel_path = "_devbuild/help/osh-builtin-cmd", .contents = gStr5},
1117 {.rel_path = "_devbuild/help/osh-chapters", .contents = gStr6},
1118 {.rel_path = "_devbuild/help/osh-cmd-lang", .contents = gStr7},
1119 {.rel_path = "_devbuild/help/osh-front-end", .contents = gStr8},
1120 {.rel_path = "_devbuild/help/osh-mini-lang", .contents = gStr9},
1121 {.rel_path = "_devbuild/help/osh-option", .contents = gStr10},
1122 {.rel_path = "_devbuild/help/osh-osh-assign", .contents = gStr11},
1123 {.rel_path = "_devbuild/help/osh-plugin", .contents = gStr12},
1124 {.rel_path = "_devbuild/help/osh-special-var", .contents = gStr13},
1125 {.rel_path = "_devbuild/help/osh-type-method", .contents = gStr14},
1126 {.rel_path = "_devbuild/help/osh-usage", .contents = gStr15},
1127 {.rel_path = "_devbuild/help/osh-word-lang", .contents = gStr16},
1128 {.rel_path = "_devbuild/help/ysh-builtin-cmd", .contents = gStr17},
1129 {.rel_path = "_devbuild/help/ysh-builtin-func", .contents = gStr18},
1130 {.rel_path = "_devbuild/help/ysh-chapters", .contents = gStr19},
1131 {.rel_path = "_devbuild/help/ysh-cmd-lang", .contents = gStr20},
1132 {.rel_path = "_devbuild/help/ysh-expr-lang", .contents = gStr21},
1133 {.rel_path = "_devbuild/help/ysh-front-end", .contents = gStr22},
1134 {.rel_path = "_devbuild/help/ysh-mini-lang", .contents = gStr23},
1135 {.rel_path = "_devbuild/help/ysh-option", .contents = gStr24},
1136 {.rel_path = "_devbuild/help/ysh-plugin", .contents = gStr25},
1137 {.rel_path = "_devbuild/help/ysh-special-var", .contents = gStr26},
1138 {.rel_path = "_devbuild/help/ysh-type-method", .contents = gStr27},
1139 {.rel_path = "_devbuild/help/ysh-usage", .contents = gStr28},
1140 {.rel_path = "_devbuild/help/ysh-word-lang", .contents = gStr29},
1141 {.rel_path = "_devbuild/help/ysh-ysh-cmd", .contents = gStr30},
1142 {.rel_path = "stdlib/args.ysh", .contents = gStr31},
1143 {.rel_path = "stdlib/draft-synch.ysh", .contents = gStr32},
1144 {.rel_path = "stdlib/funcs.ysh", .contents = gStr33},
1145 {.rel_path = "stdlib/list.ysh", .contents = gStr34},
1146 {.rel_path = "stdlib/math.ysh", .contents = gStr35},
1147 {.rel_path = "stdlib/methods.ysh", .contents = gStr36},
1148 {.rel_path = "stdlib/prelude.ysh", .contents = gStr37},
1149 {.rel_path = "stdlib/testing.ysh", .contents = gStr38},
1150
1151 {.rel_path = nullptr, .contents = nullptr},
1152};
1153
1154} // namespace embedded_file
1155
1156TextFile* gEmbeddedFiles = embedded_file::array; // turn array into pointer