...

Source file src/sigs.k8s.io/release-utils/mage/git.go

Documentation: sigs.k8s.io/release-utils/mage

     1  /*
     2  Copyright 2022 The Kubernetes Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package mage
    18  
    19  import (
    20  	"fmt"
    21  
    22  	"sigs.k8s.io/release-utils/command"
    23  )
    24  
    25  const (
    26  	gitConfigNameKey    = "user.name"
    27  	gitConfigNameValue  = "releng-ci-user"
    28  	gitConfigEmailKey   = "user.email"
    29  	gitConfigEmailValue = "nobody@k8s.io"
    30  )
    31  
    32  func CheckGitConfigExists() bool {
    33  	userName := command.New(
    34  		"git",
    35  		"config",
    36  		"--global",
    37  		"--get",
    38  		gitConfigNameKey,
    39  	)
    40  
    41  	stream, err := userName.RunSilentSuccessOutput()
    42  	if err != nil || stream.OutputTrimNL() == "" {
    43  		// NB: We're intentionally ignoring the error here because 'git config'
    44  		// returns an error (result code -1) if the config doesn't exist.
    45  		return false
    46  	}
    47  
    48  	userEmail := command.New(
    49  		"git",
    50  		"config",
    51  		"--global",
    52  		"--get",
    53  		gitConfigEmailKey,
    54  	)
    55  
    56  	stream, err = userEmail.RunSilentSuccessOutput()
    57  	if err != nil || stream.OutputTrimNL() == "" {
    58  		// NB: We're intentionally ignoring the error here because 'git config'
    59  		// returns an error (result code -1) if the config doesn't exist.
    60  		return false
    61  	}
    62  
    63  	return true
    64  }
    65  
    66  func EnsureGitConfig() error {
    67  	exists := CheckGitConfigExists()
    68  	if exists {
    69  		return nil
    70  	}
    71  
    72  	if err := command.New(
    73  		"git",
    74  		"config",
    75  		"--global",
    76  		gitConfigNameKey,
    77  		gitConfigNameValue,
    78  	).RunSuccess(); err != nil {
    79  		return fmt.Errorf("configuring git %s: %w", gitConfigNameKey, err)
    80  	}
    81  
    82  	if err := command.New(
    83  		"git",
    84  		"config",
    85  		"--global",
    86  		gitConfigEmailKey,
    87  		gitConfigEmailValue,
    88  	).RunSuccess(); err != nil {
    89  		return fmt.Errorf("configuring git %s: %w", gitConfigEmailKey, err)
    90  	}
    91  
    92  	return nil
    93  }
    94  

View as plain text