OILS / spec / ysh-builtin-ctx.test.sh View on Github | oilshell.org

168 lines, 124 significant
1## our_shell: ysh
2## oils_failures_allowed: 0
3
4#### ctx push and set
5var mydict = {}
6ctx push (mydict) {
7 ctx set (key1="value1")
8 ctx set (key2="value2")
9}
10json write (mydict)
11## STDOUT:
12{
13 "key1": "value1",
14 "key2": "value2"
15}
16## END
17
18#### ctx emit
19var p = {}
20ctx push (p) {
21 ctx emit flag ({short_name: '-v'})
22 # p => {'flag': [{short_name: '-v'}]}
23 json write (p)
24
25 ctx emit flag ({short_name: '-c'})
26 # p => {'flag': [{short_name: '-v'}, {short_name: '-c'}]}
27 json write (p)
28}
29json write (p)
30## STDOUT:
31{
32 "flag": [
33 {
34 "short_name": "-v"
35 }
36 ]
37}
38{
39 "flag": [
40 {
41 "short_name": "-v"
42 },
43 {
44 "short_name": "-c"
45 }
46 ]
47}
48{
49 "flag": [
50 {
51 "short_name": "-v"
52 },
53 {
54 "short_name": "-c"
55 }
56 ]
57}
58## END
59
60#### nested ctx
61var a = {}
62var b = {}
63ctx push (a) {
64 ctx set (from="a")
65 ctx push (b) {
66 ctx set (from="b")
67 }
68}
69json write (a)
70json write (b)
71## STDOUT:
72{
73 "from": "a"
74}
75{
76 "from": "b"
77}
78## END
79
80#### error in context
81var a = {}
82try {
83 ctx push (a) {
84 error "Error from inside a context" (code=100)
85 }
86}
87echo status=$_status
88exit 0
89## STDOUT:
90status=100
91## END
92
93#### no context, set
94ctx set (bad=true)
95echo status=$_status
96## status: 3
97## STDOUT:
98## END
99
100#### no context, emit
101ctx emit bad (true)
102echo status=$_status
103## status: 3
104## STDOUT:
105## END
106
107#### mini-parseArgs
108proc parser (; place ; ; block_def) {
109 var p = {}
110 ctx push (p; ; block_def)
111 call place->setValue(p)
112}
113
114var Bool = "Bool"
115var Int = "Int"
116proc flag (short_name, long_name; type; help) {
117 ctx emit flag ({short_name, long_name, type, help})
118}
119
120proc arg (name) {
121 ctx emit arg ({name})
122}
123
124parser (&spec) {
125 flag -t --tsv (Bool, help='Output as a TSV')
126 flag -r --recursive (Bool, help='Recurse into the given directory')
127 flag -N --count (Int, help='Process no more than N files')
128 arg path
129}
130json write (spec)
131## STDOUT:
132{
133 "flag": [
134 {
135 "short_name": "-t",
136 "long_name": "--tsv",
137 "type": "Bool",
138 "help": "Output as a TSV"
139 },
140 {
141 "short_name": "-r",
142 "long_name": "--recursive",
143 "type": "Bool",
144 "help": "Recurse into the given directory"
145 },
146 {
147 "short_name": "-N",
148 "long_name": "--count",
149 "type": "Int",
150 "help": "Process no more than N files"
151 }
152 ],
153 "arg": [
154 {
155 "name": "path"
156 }
157 ]
158}
159## END
160
161#### ctx with value.Place, not List/Dict (error location bug fix)
162
163ctx push (&p) {
164 true
165}
166## status: 3
167## STDOUT:
168## END