Skip to content

Commit c5c91b3

Browse files
committed
Enable the half-implemented -f, --function option
1. When docopts is run inside functions it shall not exit but rather return. 2. Variables should be defined using local.
1 parent 4130f5b commit c5c91b3

File tree

1 file changed

+11
-2
lines changed

1 file changed

+11
-2
lines changed

docopts.go

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,8 @@ Options:
7979
with -A argument.
8080
--debug Output extra parsing information for debugging.
8181
Output cannot be used in bash eval.
82+
-f, --function Return instead of exit. Useful inside shell
83+
functions.
8284
`
8385

8486
// testing trick, out can be mocked to catch stdout and validate
@@ -210,6 +212,12 @@ func (d *Docopts) Print_bash_global(args docopt.Opts) error {
210212
var new_name string
211213
var err error
212214
var out_buf string
215+
var var_format_str string = "%s=%s\n"
216+
var output_format_str string = "%s"
217+
if d.Exit_function {
218+
var_format_str = "%s=%s "
219+
output_format_str = "local %s"
220+
}
213221

214222
varmap := make(map[string]string)
215223

@@ -241,11 +249,11 @@ func (d *Docopts) Print_bash_global(args docopt.Opts) error {
241249
varmap[new_name] = key
242250
}
243251

244-
out_buf += fmt.Sprintf("%s=%s\n", new_name, To_bash(args[key]))
252+
out_buf += fmt.Sprintf(var_format_str, new_name, To_bash(args[key]))
245253
}
246254

247255
// final output
248-
fmt.Fprintf(out, "%s", out_buf)
256+
fmt.Fprintf(out, output_format_str, out_buf)
249257

250258
return nil
251259
}
@@ -414,6 +422,7 @@ func main() {
414422
separator := arguments["--separator"].(string)
415423
d.Mangle_key = !arguments["--no-mangle"].(bool)
416424
d.Output_declare = !arguments["--no-declare"].(bool)
425+
d.Exit_function = arguments["--function"].(bool)
417426
global_prefix, err := arguments.String("-G")
418427
if err == nil {
419428
d.Global_prefix = global_prefix

0 commit comments

Comments
 (0)