github.com/zppinho/prow@v0.0.0-20240510014325-1738badeb017/pkg/git/v2/executor.go (about)

     1  /*
     2  Copyright 2019 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 git
    18  
    19  import (
    20  	"os/exec"
    21  	"strings"
    22  
    23  	"github.com/sirupsen/logrus"
    24  )
    25  
    26  // executor knows how to execute Git commands
    27  type executor interface {
    28  	Run(args ...string) ([]byte, error)
    29  }
    30  
    31  // Censor censors content to remove secrets
    32  type Censor func(content []byte) []byte
    33  
    34  func NewCensoringExecutor(dir string, censor Censor, logger *logrus.Entry) (executor, error) {
    35  	g, err := exec.LookPath("git")
    36  	if err != nil {
    37  		return nil, err
    38  	}
    39  	return &censoringExecutor{
    40  		logger: logger.WithField("client", "git"),
    41  		dir:    dir,
    42  		git:    g,
    43  		censor: censor,
    44  		execute: func(dir, command string, args ...string) ([]byte, error) {
    45  			c := exec.Command(command, args...)
    46  			c.Dir = dir
    47  			return c.CombinedOutput()
    48  		},
    49  	}, nil
    50  }
    51  
    52  type censoringExecutor struct {
    53  	// logger will be used to log git operations
    54  	logger *logrus.Entry
    55  	// dir is the location of this repo.
    56  	dir string
    57  	// git is the path to the git binary.
    58  	git string
    59  	// censor removes sensitive data from output
    60  	censor Censor
    61  	// execute executes a command
    62  	execute func(dir, command string, args ...string) ([]byte, error)
    63  }
    64  
    65  func (e *censoringExecutor) Run(args ...string) ([]byte, error) {
    66  	logger := e.logger.WithField("args", strings.Join(args, " "))
    67  	b, err := e.execute(e.dir, e.git, args...)
    68  	b = e.censor(b)
    69  	if err != nil {
    70  		logger.WithError(err).WithField("output", string(b)).Debug("Running command failed.")
    71  	} else {
    72  		logger.Debug("Running command succeeded.")
    73  	}
    74  	return b, err
    75  }