github.com/elek/golangci-lint@v1.42.2-0.20211208090441-c05b7fcb3a9a/pkg/result/processors/diff.go (about)

     1  package processors
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"io"
     7  	"io/ioutil"
     8  	"os"
     9  	"strings"
    10  
    11  	"github.com/golangci/revgrep"
    12  
    13  	"github.com/elek/golangci-lint/pkg/result"
    14  )
    15  
    16  type Diff struct {
    17  	onlyNew       bool
    18  	fromRev       string
    19  	patchFilePath string
    20  	patch         string
    21  }
    22  
    23  var _ Processor = Diff{}
    24  
    25  func NewDiff(onlyNew bool, fromRev, patchFilePath string) *Diff {
    26  	return &Diff{
    27  		onlyNew:       onlyNew,
    28  		fromRev:       fromRev,
    29  		patchFilePath: patchFilePath,
    30  		patch:         os.Getenv("GOLANGCI_DIFF_PROCESSOR_PATCH"),
    31  	}
    32  }
    33  
    34  func (p Diff) Name() string {
    35  	return "diff"
    36  }
    37  
    38  func (p Diff) Process(issues []result.Issue) ([]result.Issue, error) {
    39  	if !p.onlyNew && p.fromRev == "" && p.patchFilePath == "" && p.patch == "" { // no need to work
    40  		return issues, nil
    41  	}
    42  
    43  	var patchReader io.Reader
    44  	if p.patchFilePath != "" {
    45  		patch, err := ioutil.ReadFile(p.patchFilePath)
    46  		if err != nil {
    47  			return nil, fmt.Errorf("can't read from patch file %s: %s", p.patchFilePath, err)
    48  		}
    49  		patchReader = bytes.NewReader(patch)
    50  	} else if p.patch != "" {
    51  		patchReader = strings.NewReader(p.patch)
    52  	}
    53  
    54  	c := revgrep.Checker{
    55  		Patch:        patchReader,
    56  		RevisionFrom: p.fromRev,
    57  	}
    58  	if err := c.Prepare(); err != nil {
    59  		return nil, fmt.Errorf("can't prepare diff by revgrep: %s", err)
    60  	}
    61  
    62  	return transformIssues(issues, func(i *result.Issue) *result.Issue {
    63  		hunkPos, isNew := c.IsNewIssue(i)
    64  		if !isNew {
    65  			return nil
    66  		}
    67  
    68  		newI := *i
    69  		newI.HunkPos = hunkPos
    70  		return &newI
    71  	}), nil
    72  }
    73  
    74  func (Diff) Finish() {}