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

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