From 5e965740bae4aaeb2702a9ff1a153b2603d4084d Mon Sep 17 00:00:00 2001 From: rsteube Date: Mon, 25 Apr 2022 19:45:24 +0200 Subject: [PATCH] fix context env --- completers/aws_completer/cmd/complete.py | 54 --------- completers/aws_completer/cmd/root.go | 110 +++++------------- completers/gcloud_completer/cmd/root.go | 5 +- .../pulumi_completer/cmd/action/config.go | 5 +- .../pulumi_completer/cmd/action/stack.go | 5 +- completers/pulumi_completer/cmd/action/urn.go | 11 +- go.mod | 2 +- go.sum | 4 +- pkg/actions/bridge/argcomplete.go | 19 ++- pkg/actions/bridge/posener.go | 5 +- 10 files changed, 52 insertions(+), 168 deletions(-) delete mode 100644 completers/aws_completer/cmd/complete.py diff --git a/completers/aws_completer/cmd/complete.py b/completers/aws_completer/cmd/complete.py deleted file mode 100644 index a2a9b971c1..0000000000 --- a/completers/aws_completer/cmd/complete.py +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/env python -# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. - -# Licensed under the Apache License, Version 2.0 (the "License"). You -# may not use this file except in compliance with the License. A copy of -# the License is located at - -# http://aws.amazon.com/apache2.0/ - -# or in the "license" file accompanying this file. This file is -# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF -# ANY KIND, either express or implied. See the License for the specific -# language governing permissions and limitations under the License. -import json -import os -import sys - -if os.environ.get('LC_CTYPE', '') == 'UTF-8': - os.environ['LC_CTYPE'] = 'en_US.UTF-8' -from awscli.autocomplete.main import create_autocompleter -from awscli.clidriver import create_clidriver - - -def main(): - # bash exports COMP_LINE and COMP_POINT, tcsh COMMAND_LINE only - command_line = ( - os.environ.get('COMP_LINE') or os.environ.get('COMMAND_LINE') or '' - ) - command_index = int(os.environ.get('COMP_POINT') or len(command_line)) - - try: - completer = create_autocompleter(driver=create_clidriver()) - results = completer.autocomplete(command_line, command_index) - sys.stdout.write(json.dumps( - [{'name': result.name, 'help_text': _get_display_meta(result)} for result in results])) - except KeyboardInterrupt: - # If the user hits Ctrl+C, we don't want to print - # a traceback to the user. - pass - - -def _get_display_meta(completion): - display_meta = '' - type_name = getattr(completion, 'cli_type_name', None) - help_text = getattr(completion, 'help_text', None) - if type_name: - display_meta += f'[{type_name}] ' - if help_text: - display_meta += f'{help_text}' - return display_meta - - -if __name__ == '__main__': - main() diff --git a/completers/aws_completer/cmd/root.go b/completers/aws_completer/cmd/root.go index 255f8867b3..0a193b6795 100644 --- a/completers/aws_completer/cmd/root.go +++ b/completers/aws_completer/cmd/root.go @@ -1,10 +1,6 @@ package cmd import ( - _ "embed" - "encoding/json" - exec "golang.org/x/sys/execabs" - "os" "strings" "github.com/rsteube/carapace" @@ -23,91 +19,37 @@ func Execute() error { return rootCmd.Execute() } -//go:embed complete.py -var complete string - -type completionResult struct { - Name string - HelpText string `json:"help_text"` -} - func init() { carapace.Gen(rootCmd).Standalone() carapace.Gen(rootCmd).PositionalAnyCompletion( carapace.ActionCallback(func(c carapace.Context) carapace.Action { - path, err := exec.LookPath("aws_completer") - if err != nil { - return carapace.ActionMessage(err.Error()) - } - - info, err := os.Stat(path) - if err != nil { - return carapace.ActionMessage(err.Error()) - } - if info.Size() > 100000 { // python version is ~4 kb and compiled is >4 MB - return actionBinaryCompleter() - } else { - return actionPythonCompleter() - } + current := c.CallbackValue + if c.CallbackValue == "-" { + return carapace.ActionValues("--").NoSpace() // no shorthand flags so expand to longhand first (which is needed for the completer) + } + + c.Setenv("COMP_LINE", "aws "+strings.Join(append(c.Args, current), " ")) // TODO escape/quote special characters + return carapace.ActionExecCommand("aws_completer")(func(output []byte) carapace.Action { + lines := strings.Split(string(output), "\n") + if lines[0] == "" { + return carapace.ActionValues() + } + nospace := true + for index, line := range lines { + if strings.HasSuffix(line, " ") { + lines[index] = strings.TrimSuffix(line, " ") + nospace = false + } + } + a := carapace.ActionValues(lines[:len(lines)-1]...) + if nospace || + strings.HasPrefix(current, "file://") || + strings.HasPrefix(current, "fileb://") { + return a.NoSpace() + } + return a + }).Invoke(c).ToA() }), ) } - -func actionBinaryCompleter() carapace.Action { - return carapace.ActionCallback(func(c carapace.Context) carapace.Action { - current := c.CallbackValue - if c.CallbackValue == "-" { - return carapace.ActionValues("--").NoSpace() // no shorthand flags so expand to longhand first (which is needed for the completer) - } - os.Setenv("COMP_LINE", "aws "+strings.Join(append(c.Args, current), " ")) // TODO escape/quote special characters - return carapace.ActionExecCommand("aws_completer")(func(output []byte) carapace.Action { - lines := strings.Split(string(output), "\n") - if lines[0] == "" { - return carapace.ActionValues() - } - a := carapace.ActionValues(lines[:len(lines)-1]...) - if strings.HasPrefix(current, "file://") || - strings.HasPrefix(current, "fileb://") { - return a.NoSpace() - } - return a - }) - }) -} - -func actionPythonCompleter() carapace.Action { - return carapace.ActionCallback(func(c carapace.Context) carapace.Action { - current := c.CallbackValue - if c.CallbackValue == "-" { - return carapace.ActionValues("--").NoSpace() // no shorthand flags so expand to longhand first (which is needed for the completer) - } - os.Setenv("COMP_LINE", "aws "+strings.Join(append(c.Args, current), " ")) // TODO escape/quote special characters - return carapace.ActionExecCommand("python", "-c", complete)(func(output []byte) carapace.Action { - var completionResults []completionResult - if err := json.Unmarshal(output, &completionResults); err != nil { - return carapace.ActionMessage(err.Error()) - } - - prefix := "" - if index := strings.LastIndexAny(c.CallbackValue, "=,/"); index > -1 { - prefix = c.CallbackValue[:index+1] - } - - nospace := false - vals := make([]string, 0, len(completionResults)) - for _, c := range completionResults { - vals = append(vals, strings.TrimPrefix(c.Name, prefix), c.HelpText) - nospace = nospace || strings.ContainsAny(c.Name, "=,/") - } - - a := carapace.ActionValuesDescribed(vals...).Invoke(c).Prefix(prefix).ToA() - if nospace || - strings.HasPrefix(current, "file://") || - strings.HasPrefix(current, "fileb://") { - return a.NoSpace() - } - return a - }) - }) -} diff --git a/completers/gcloud_completer/cmd/root.go b/completers/gcloud_completer/cmd/root.go index 812bacaeab..98ff737ad5 100644 --- a/completers/gcloud_completer/cmd/root.go +++ b/completers/gcloud_completer/cmd/root.go @@ -4,7 +4,6 @@ import ( "github.com/rsteube/carapace" "github.com/rsteube/carapace-bin/pkg/actions/bridge" "github.com/spf13/cobra" - "os" ) var rootCmd = &cobra.Command{ @@ -29,8 +28,8 @@ func init() { if c.CallbackValue == "-" { return carapace.ActionValues("--").NoSpace() // seems shorthand flags aren't completed anyway so expand to longhand first } - os.Setenv("CLOUDSDK_COMPONENT_MANAGER_DISABLE_UPDATE_CHECK", "1") - return bridge.ActionArgcomplete("gcloud") + c.Setenv("CLOUDSDK_COMPONENT_MANAGER_DISABLE_UPDATE_CHECK", "1") + return bridge.ActionArgcomplete("gcloud").Invoke(c).ToA() }), ) } diff --git a/completers/pulumi_completer/cmd/action/config.go b/completers/pulumi_completer/cmd/action/config.go index 717ecc8129..c10363b44b 100644 --- a/completers/pulumi_completer/cmd/action/config.go +++ b/completers/pulumi_completer/cmd/action/config.go @@ -4,7 +4,6 @@ import ( "encoding/json" "github.com/rsteube/carapace" "github.com/spf13/cobra" - "os" ) type config struct { @@ -14,7 +13,7 @@ type config struct { func ActionConfigKeys(cmd *cobra.Command) carapace.Action { return carapace.ActionCallback(func(c carapace.Context) carapace.Action { - os.Setenv("PULUMI_SKIP_UPDATE_CHECK", "1") + c.Setenv("PULUMI_SKIP_UPDATE_CHECK", "1") return carapace.ActionExecCommand("pulumi", "--cwd", cmd.Flag("cwd").Value.String(), "config", "--json")(func(output []byte) carapace.Action { var config map[string]config if err := json.Unmarshal(output, &config); err != nil { @@ -26,6 +25,6 @@ func ActionConfigKeys(cmd *cobra.Command) carapace.Action { vals = append(vals, name, c.Value) } return carapace.ActionValuesDescribed(vals...).Invoke(c).ToMultiPartsA(":") - }) + }).Invoke(c).ToA() }) } diff --git a/completers/pulumi_completer/cmd/action/stack.go b/completers/pulumi_completer/cmd/action/stack.go index f5462b2164..47fd0c40bd 100644 --- a/completers/pulumi_completer/cmd/action/stack.go +++ b/completers/pulumi_completer/cmd/action/stack.go @@ -4,7 +4,6 @@ import ( "encoding/json" "github.com/rsteube/carapace" "github.com/spf13/cobra" - "os" ) type stack struct { @@ -25,7 +24,7 @@ func ActionStacks(cmd *cobra.Command, opts StackOpts) carapace.Action { args = append(args, "--all") } - os.Setenv("PULUMI_SKIP_UPDATE_CHECK", "1") + c.Setenv("PULUMI_SKIP_UPDATE_CHECK", "1") return carapace.ActionExecCommand("pulumi", args...)(func(output []byte) carapace.Action { var stacks []stack if err := json.Unmarshal(output, &stacks); err != nil { @@ -40,6 +39,6 @@ func ActionStacks(cmd *cobra.Command, opts StackOpts) carapace.Action { vals = append(vals, s.Name) } return carapace.ActionValues(vals...) - }) + }).Invoke(c).ToA() }) } diff --git a/completers/pulumi_completer/cmd/action/urn.go b/completers/pulumi_completer/cmd/action/urn.go index 9d9cb5a04f..d099b3b277 100644 --- a/completers/pulumi_completer/cmd/action/urn.go +++ b/completers/pulumi_completer/cmd/action/urn.go @@ -1,14 +1,15 @@ package action import ( - "github.com/rsteube/carapace" - "github.com/rsteube/carapace/pkg/cache" - "github.com/spf13/cobra" "os" "path/filepath" "regexp" "strings" "time" + + "github.com/rsteube/carapace" + "github.com/rsteube/carapace/pkg/cache" + "github.com/spf13/cobra" ) type resource struct { @@ -22,7 +23,7 @@ func ActionUrns(cmd *cobra.Command) carapace.Action { cwd := cmd.Flag("cwd").Value.String() stack := cmd.Flag("stack").Value.String() - os.Setenv("PULUMI_SKIP_UPDATE_CHECK", "1") + c.Setenv("PULUMI_SKIP_UPDATE_CHECK", "1") return carapace.ActionExecCommand("pulumi", "--cwd", cwd, "stack", "--stack", stack, "--show-urns")(func(output []byte) carapace.Action { reUrn := regexp.MustCompile(`URN: (?Purn:pulumi.*)`) reId := regexp.MustCompile(`ID: (?P.*)`) @@ -42,7 +43,7 @@ func ActionUrns(cmd *cobra.Command) carapace.Action { vals = append(vals, resource.Urn, resource.Id) } return carapace.ActionValuesDescribed(vals...) - }) + }).Invoke(c).ToA() }).Cache(5*time.Second, func() (string, error) { workdir, err := os.Getwd() if err != nil { diff --git a/go.mod b/go.mod index 6ce706754d..e0c0b8e364 100644 --- a/go.mod +++ b/go.mod @@ -6,7 +6,7 @@ require ( github.com/mitchellh/go-homedir v1.1.0 github.com/mitchellh/go-ps v1.0.0 github.com/pelletier/go-toml v1.9.5 - github.com/rsteube/carapace v0.19.6 + github.com/rsteube/carapace v0.19.7 github.com/spf13/cobra v1.4.0 github.com/spf13/pflag v1.0.5 golang.org/x/sys v0.0.0-20211205182925-97ca703d548d diff --git a/go.sum b/go.sum index ef343e15e8..376a68c98a 100644 --- a/go.sum +++ b/go.sum @@ -13,8 +13,8 @@ github.com/pelletier/go-toml v1.9.5 h1:4yBQzkHv+7BHq2PQUZF3Mx0IYxG7LsP222s7Agd3v github.com/pelletier/go-toml v1.9.5/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/rsteube/carapace v0.19.6 h1:8J+Ln3lzccYnJRGzPPvFGtdZRlYiL2qZ2NhbEgP46DU= -github.com/rsteube/carapace v0.19.6/go.mod h1:GgiwpPVhucHNOv0AmtIkxhiEFkCMP5BBRauyQLP0mFY= +github.com/rsteube/carapace v0.19.7 h1:qbRzBiiYWs/cvvgtSZ13JVepKmDvfR8wZHBuYuq6gxo= +github.com/rsteube/carapace v0.19.7/go.mod h1:GgiwpPVhucHNOv0AmtIkxhiEFkCMP5BBRauyQLP0mFY= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/spf13/cobra v1.4.0 h1:y+wJpx64xcgO1V+RcnwW0LEHxTKRi2ZDPSBjWnrg88Q= github.com/spf13/cobra v1.4.0/go.mod h1:Wo4iy3BUC+X2Fybo0PDqwJIv3dNRiZLHQymsfxlB84g= diff --git a/pkg/actions/bridge/argcomplete.go b/pkg/actions/bridge/argcomplete.go index 0a2ed5975c..52b235fbb1 100644 --- a/pkg/actions/bridge/argcomplete.go +++ b/pkg/actions/bridge/argcomplete.go @@ -1,7 +1,6 @@ package bridge import ( - "os" "os/exec" "strconv" "strings" @@ -51,15 +50,15 @@ func ActionArgcomplete(command string) carapace.Action { } compLine := command + " " + strings.Join(append(args, current), " ") // TODO escape/quote special characters - os.Setenv("_ARGCOMPLETE", "1") - os.Setenv("_ARGCOMPLETE_DFS", "\t") - os.Setenv("_ARGCOMPLETE_IFS", "\n") - os.Setenv("_ARGCOMPLETE_SHELL", "fish") - os.Setenv("_ARGCOMPLETE_SUPPRESS_SPACE", "1") // TODO needed? relevant for nospace detection? - // os.Setenv("_ARGCOMPLETE_COMP_WORDBREAKS", " ") // TODO set to space-only for multiparts? - os.Setenv("_ARGCOMPLETE", "1") - os.Setenv("COMP_LINE", compLine) - os.Setenv("COMP_POINT", strconv.Itoa(len(compLine))) + c.Setenv("_ARGCOMPLETE", "1") + c.Setenv("_ARGCOMPLETE_DFS", "\t") + c.Setenv("_ARGCOMPLETE_IFS", "\n") + c.Setenv("_ARGCOMPLETE_SHELL", "fish") + c.Setenv("_ARGCOMPLETE_SUPPRESS_SPACE", "1") // TODO needed? relevant for nospace detection? + // c.Setenv("_ARGCOMPLETE_COMP_WORDBREAKS", " ") // TODO set to space-only for multiparts? + c.Setenv("_ARGCOMPLETE", "1") + c.Setenv("COMP_LINE", compLine) + c.Setenv("COMP_POINT", strconv.Itoa(len(compLine))) nospace := false a := carapace.ActionExecCommand("sh", "-c", command+" 8>&1 9>&2 1>/dev/null 2>/dev/null")(func(output []byte) carapace.Action { lines := strings.Split(string(output), "\n") diff --git a/pkg/actions/bridge/posener.go b/pkg/actions/bridge/posener.go index e2d2567ecb..637fb8fc78 100644 --- a/pkg/actions/bridge/posener.go +++ b/pkg/actions/bridge/posener.go @@ -2,7 +2,6 @@ package bridge import ( "fmt" - "os" "strings" "github.com/rsteube/carapace" @@ -29,7 +28,7 @@ import ( // } func ActionPosenerComplete(cmd string) carapace.Action { return carapace.ActionCallback(func(c carapace.Context) carapace.Action { - os.Setenv("COMP_LINE", fmt.Sprintf("%v %v %v", cmd, strings.Join(c.Args, " "), c.CallbackValue)) + c.Setenv("COMP_LINE", fmt.Sprintf("%v %v %v", cmd, strings.Join(c.Args, " "), c.CallbackValue)) return carapace.ActionExecCommand(cmd)(func(output []byte) carapace.Action { lines := strings.Split(string(output), "\n") @@ -41,6 +40,6 @@ func ActionPosenerComplete(cmd string) carapace.Action { } } return a - }) + }).Invoke(c).ToA() }) }