github.com/argoproj/argo-cd/v3@v3.2.1/cmd/argocd-git-ask-pass/commands/argocd_git_ask_pass.go (about)

     1  package commands
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"strings"
     7  
     8  	"github.com/spf13/cobra"
     9  	"google.golang.org/grpc"
    10  	"google.golang.org/grpc/credentials/insecure"
    11  
    12  	"github.com/argoproj/argo-cd/v3/util/askpass"
    13  	"github.com/argoproj/argo-cd/v3/util/errors"
    14  	grpc_util "github.com/argoproj/argo-cd/v3/util/grpc"
    15  	utilio "github.com/argoproj/argo-cd/v3/util/io"
    16  )
    17  
    18  const (
    19  	// cliName is the name of the CLI
    20  	cliName = "argocd-git-ask-pass"
    21  )
    22  
    23  func NewCommand() *cobra.Command {
    24  	command := cobra.Command{
    25  		Use:               cliName,
    26  		Short:             "Argo CD git credential helper",
    27  		DisableAutoGenTag: true,
    28  		Run: func(c *cobra.Command, _ []string) {
    29  			ctx := c.Context()
    30  
    31  			if len(os.Args) != 2 {
    32  				errors.CheckError(fmt.Errorf("expected 1 argument, got %d", len(os.Args)-1))
    33  			}
    34  			nonce := os.Getenv(askpass.ASKPASS_NONCE_ENV)
    35  			if nonce == "" {
    36  				errors.CheckError(fmt.Errorf("%s is not set", askpass.ASKPASS_NONCE_ENV))
    37  			}
    38  			conn, err := grpc_util.BlockingNewClient(ctx, "unix", askpass.SocketPath, nil, grpc.WithTransportCredentials(insecure.NewCredentials()))
    39  			errors.CheckError(err)
    40  			defer utilio.Close(conn)
    41  			client := askpass.NewAskPassServiceClient(conn)
    42  
    43  			creds, err := client.GetCredentials(ctx, &askpass.CredentialsRequest{Nonce: nonce})
    44  			errors.CheckError(err)
    45  			switch {
    46  			case strings.HasPrefix(os.Args[1], "Username"):
    47  				fmt.Println(creds.Username)
    48  			case strings.HasPrefix(os.Args[1], "Password"):
    49  				fmt.Println(creds.Password)
    50  			default:
    51  				errors.CheckError(fmt.Errorf("unknown credential type '%s'", os.Args[1]))
    52  			}
    53  		},
    54  	}
    55  
    56  	return &command
    57  }