github.com/jenkins-x/jx/v2@v2.1.155/pkg/cmd/step/git/step_git_envs.go (about)

     1  package git
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/jenkins-x/jx/v2/pkg/cmd/helper"
     7  	"github.com/jenkins-x/jx/v2/pkg/cmd/opts/step"
     8  
     9  	"github.com/jenkins-x/jx/v2/pkg/cmd/opts"
    10  	"github.com/jenkins-x/jx/v2/pkg/cmd/templates"
    11  	"github.com/pkg/errors"
    12  	"github.com/spf13/cobra"
    13  )
    14  
    15  // StepGitEnvsOptions contains the command line flags
    16  type StepGitEnvsOptions struct {
    17  	step.StepOptions
    18  
    19  	ServiceKind string
    20  }
    21  
    22  var (
    23  	// StepGitEnvsLong command long description
    24  	StepGitEnvsLong = templates.LongDesc(`
    25  		This pipeline step generates a Git environment variables from the current Git provider pipeline Secrets
    26  
    27  `)
    28  	// StepGitEnvsExample command example
    29  	StepGitEnvsExample = templates.Examples(`
    30  		# Sets the Git environment variables for the current GitHub provider
    31  		jx step git envs
    32  
    33  		# Sets the Gie environment variables for the current Gtilab provider
    34  		jx step git envs --service-kind=gitlab
    35  `)
    36  )
    37  
    38  // NewCmdStepGitEnvs create the 'step git envs' command
    39  func NewCmdStepGitEnvs(commonOpts *opts.CommonOptions) *cobra.Command {
    40  	options := StepGitEnvsOptions{
    41  		StepOptions: step.StepOptions{
    42  			CommonOptions: commonOpts,
    43  		},
    44  	}
    45  	cmd := &cobra.Command{
    46  		Use:     "envs",
    47  		Short:   "Creates the Git environment variables for the current pipeline Git credentials",
    48  		Long:    StepGitEnvsLong,
    49  		Example: StepGitEnvsExample,
    50  		Run: func(cmd *cobra.Command, args []string) {
    51  			options.Cmd = cmd
    52  			options.Args = args
    53  			err := options.Run()
    54  			helper.CheckErr(err)
    55  		},
    56  	}
    57  
    58  	cmd.Flags().StringVarP(&options.ServiceKind, "service-kind", "", "github", "The kind of git service")
    59  	return cmd
    60  }
    61  
    62  // Run implements the command
    63  func (o *StepGitEnvsOptions) Run() error {
    64  	gitAuthSvc, err := o.GitAuthConfigService()
    65  	if err != nil {
    66  		return errors.Wrap(err, "creating the git auth config service")
    67  	}
    68  
    69  	cfg := gitAuthSvc.Config()
    70  	server := cfg.GetServerByKind(o.ServiceKind)
    71  	if server == nil {
    72  		return fmt.Errorf("no server found of kind %q", o.ServiceKind)
    73  	}
    74  	auth := server.CurrentAuth()
    75  	if auth == nil {
    76  		return fmt.Errorf("server %q has no user auth configured", server.URL)
    77  	}
    78  	_, _ = fmt.Fprintf(o.Out, "export GIT_USERNAME=%s\nexport GIT_API_TOKEN=%s\n", auth.Username, auth.ApiToken)
    79  
    80  	return nil
    81  }