From c5c91b3a824b2535cf31c9621daacc996bf962be Mon Sep 17 00:00:00 2001 From: Rezart Qelibari Date: Sat, 22 Jan 2022 22:26:26 +0100 Subject: [PATCH 1/2] 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. --- docopts.go | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/docopts.go b/docopts.go index 9cf512f..f1fe782 100644 --- a/docopts.go +++ b/docopts.go @@ -79,6 +79,8 @@ Options: with -A argument. --debug Output extra parsing information for debugging. Output cannot be used in bash eval. + -f, --function Return instead of exit. Useful inside shell + functions. ` // 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 { var new_name string var err error var out_buf string + var var_format_str string = "%s=%s\n" + var output_format_str string = "%s" + if d.Exit_function { + var_format_str = "%s=%s " + output_format_str = "local %s" + } varmap := make(map[string]string) @@ -241,11 +249,11 @@ func (d *Docopts) Print_bash_global(args docopt.Opts) error { varmap[new_name] = key } - out_buf += fmt.Sprintf("%s=%s\n", new_name, To_bash(args[key])) + out_buf += fmt.Sprintf(var_format_str, new_name, To_bash(args[key])) } // final output - fmt.Fprintf(out, "%s", out_buf) + fmt.Fprintf(out, output_format_str, out_buf) return nil } @@ -414,6 +422,7 @@ func main() { separator := arguments["--separator"].(string) d.Mangle_key = !arguments["--no-mangle"].(bool) d.Output_declare = !arguments["--no-declare"].(bool) + d.Exit_function = arguments["--function"].(bool) global_prefix, err := arguments.String("-G") if err == nil { d.Global_prefix = global_prefix From a0212e2fd92963adc58113cae08875d662f08b6d Mon Sep 17 00:00:00 2001 From: Rezart Qelibari Date: Sun, 23 Jan 2022 23:59:16 +0100 Subject: [PATCH 2/2] Do not print empty 'local' When the command does not take any arguments nor options docopt must not print anything out. This is a problem if `docopts` was started with `-f, --function` option, as `docopts` would print out only `local` and that prints out all environment variables instead of setting one. --- docopts.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docopts.go b/docopts.go index f1fe782..dd42620 100644 --- a/docopts.go +++ b/docopts.go @@ -253,7 +253,9 @@ func (d *Docopts) Print_bash_global(args docopt.Opts) error { } // final output - fmt.Fprintf(out, output_format_str, out_buf) + if (len(out_buf) > 0) { + fmt.Fprintf(out, output_format_str, out_buf) + } return nil }