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