github.com/jenkins-x/jx/v2@v2.1.155/pkg/cmd/step/git/step_git_validate.go (about) 1 package git 2 3 import ( 4 "os" 5 "os/user" 6 7 "github.com/jenkins-x/jx/v2/pkg/cmd/opts/step" 8 9 "github.com/jenkins-x/jx-logging/pkg/log" 10 "github.com/jenkins-x/jx/v2/pkg/cmd/helper" 11 "github.com/jenkins-x/jx/v2/pkg/cmd/opts" 12 "github.com/jenkins-x/jx/v2/pkg/cmd/templates" 13 "github.com/jenkins-x/jx/v2/pkg/util" 14 "github.com/spf13/cobra" 15 ) 16 17 // StepGitValidateOptions contains the command line flags 18 type StepGitValidateOptions struct { 19 step.StepOptions 20 } 21 22 var ( 23 stepGitValidateLong = templates.LongDesc(` 24 This pipeline step validates that the .gitconfig is correctly configured 25 26 `) 27 28 stepGitValidateExample = templates.Examples(` 29 # validates the user.name & user.email values are set in the .gitconfig 30 jx step git validate 31 `) 32 ) 33 34 // NewCmdStepGitValidate creates a command to validate gitconfig 35 func NewCmdStepGitValidate(commonOpts *opts.CommonOptions) *cobra.Command { 36 options := StepGitValidateOptions{ 37 StepOptions: step.StepOptions{ 38 CommonOptions: commonOpts, 39 }, 40 } 41 cmd := &cobra.Command{ 42 Use: "validate", 43 Short: "Validates the .gitconfig is correctly configured", 44 Long: stepGitValidateLong, 45 Example: stepGitValidateExample, 46 Run: func(cmd *cobra.Command, args []string) { 47 options.Cmd = cmd 48 options.Args = args 49 err := options.Run() 50 helper.CheckErr(err) 51 }, 52 } 53 return cmd 54 } 55 56 // Run validates git config 57 func (o *StepGitValidateOptions) Run() error { 58 // lets ignore errors which indicate no value set 59 userName, _ := o.Git().Username("") 60 userEmail, _ := o.Git().Email("") 61 var err error 62 if userName == "" { 63 // check the OS first 64 userName = os.Getenv("GIT_AUTHOR_NAME") 65 if userName == "" { 66 if !o.BatchMode { 67 userName, err = util.PickValue("Please enter the name you wish to use with git: ", "", true, "", o.GetIOFileHandles()) 68 if err != nil { 69 return err 70 } 71 } 72 } 73 if userName == "" { 74 user, err := user.Current() 75 if err == nil && user != nil { 76 userName = user.Username 77 } 78 } 79 if userName == "" { 80 userName = util.DefaultGitUserName 81 } 82 err = o.Git().SetUsername("", userName) 83 if err != nil { 84 return err 85 } 86 } 87 if userEmail == "" { 88 // check the OS first 89 userEmail = os.Getenv("GIT_AUTHOR_EMAIL") 90 if userEmail == "" { 91 if !o.BatchMode { 92 userEmail, err = util.PickValue("Please enter the email address you wish to use with git: ", "", true, "", o.GetIOFileHandles()) 93 if err != nil { 94 return err 95 } 96 } 97 } 98 if userEmail == "" { 99 userEmail = util.DefaultGitUserEmail 100 } 101 err = o.Git().SetEmail("", userEmail) 102 if err != nil { 103 return err 104 } 105 } 106 log.Logger().Infof("Git configured for user: %s and email %s", util.ColorInfo(userName), util.ColorInfo(userEmail)) 107 return nil 108 109 }