Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ func (c *Cache) computePkgHash(pkg *packages.Package) (hashResults, error) {

fmt.Fprintf(key, "pkgpath %s\n", pkg.PkgPath)

for _, f := range pkg.CompiledGoFiles {
for _, f := range slices.Concat(pkg.CompiledGoFiles, pkg.IgnoredFiles) {
h, fErr := c.fileHash(f)
if fErr != nil {
return nil, fmt.Errorf("failed to calculate file %s hash: %w", f, fErr)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,25 +8,30 @@ package analysisinternal

import (
"fmt"
"os"
"slices"

"golang.org/x/tools/go/analysis"
)

// MakeReadFile returns a simple implementation of the Pass.ReadFile function.
func MakeReadFile(pass *analysis.Pass) func(filename string) ([]byte, error) {
// A ReadFileFunc is a function that returns the
// contents of a file, such as [os.ReadFile].
type ReadFileFunc = func(filename string) ([]byte, error)

// CheckedReadFile returns a wrapper around a Pass.ReadFile
// function that performs the appropriate checks.
func CheckedReadFile(pass *analysis.Pass, readFile ReadFileFunc) ReadFileFunc {
return func(filename string) ([]byte, error) {
if err := CheckReadable(pass, filename); err != nil {
return nil, err
}
return os.ReadFile(filename)
return readFile(filename)
}
}

// CheckReadable enforces the access policy defined by the ReadFile field of [analysis.Pass].
func CheckReadable(pass *analysis.Pass, filename string) error {
if slicesContains(pass.OtherFiles, filename) ||
slicesContains(pass.IgnoredFiles, filename) {
if slices.Contains(pass.OtherFiles, filename) ||
slices.Contains(pass.IgnoredFiles, filename) {
return nil
}
for _, f := range pass.Files {
Expand All @@ -36,13 +41,3 @@ func CheckReadable(pass *analysis.Pass, filename string) error {
}
return fmt.Errorf("Pass.ReadFile: %s is not among OtherFiles, IgnoredFiles, or names of Files", filename)
}

// TODO(adonovan): use go1.21 slices.Contains.
func slicesContains[S ~[]E, E comparable](slice S, x E) bool {
for _, elem := range slice {
if elem == x {
return true
}
}
return false
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ package diff

import (
"fmt"
"slices"
"sort"
"strings"
)
Expand Down Expand Up @@ -64,7 +65,7 @@ func ApplyBytes(src []byte, edits []Edit) ([]byte, error) {
// It may return a different slice.
func validate(src string, edits []Edit) ([]Edit, int, error) {
if !sort.IsSorted(editsSort(edits)) {
edits = append([]Edit(nil), edits...)
edits = slices.Clone(edits)
SortEdits(edits)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ func (l lcs) fix() lcs {
// from the set of diagonals in l, find a maximal non-conflicting set
// this problem may be NP-complete, but we use a greedy heuristic,
// which is quadratic, but with a better data structure, could be D log D.
// indepedent is not enough: {0,3,1} and {3,0,2} can't both occur in an lcs
// independent is not enough: {0,3,1} and {3,0,2} can't both occur in an lcs
// which has to have monotone x and y
if len(l) == 0 {
return nil
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ computed labels. That is the worst case. Had the code noticed (x,y)=(u,v)=(3,3)
from the edgegraph. The implementation looks for a number of special cases to try to avoid computing an extra forward path.

If the two-sided algorithm has stop early (because D has become too large) it will have found a forward LCS and a
backwards LCS. Ideally these go with disjoint prefixes and suffixes of A and B, but disjointness may fail and the two
backwards LCS. Ideally these go with disjoint prefixes and suffixes of A and B, but disjointedness may fail and the two
computed LCS may conflict. (An easy example is where A is a suffix of B, and shares a short prefix. The backwards LCS
is all of A, and the forward LCS is a prefix of A.) The algorithm combines the two
to form a best-effort LCS. In the worst case the forward partial LCS may have to
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ func forward(e *editGraph) lcs {
return ans
}
// from D to D+1
for D := 0; D < e.limit; D++ {
for D := range e.limit {
e.setForward(D+1, -(D + 1), e.getForward(D, -D))
if ok, ans := e.fdone(D+1, -(D + 1)); ok {
return ans
Expand Down Expand Up @@ -199,13 +199,14 @@ func (e *editGraph) bdone(D, k int) (bool, lcs) {
}

// run the backward algorithm, until success or up to the limit on D.
// (used only by tests)
func backward(e *editGraph) lcs {
e.setBackward(0, 0, e.ux)
if ok, ans := e.bdone(0, 0); ok {
return ans
}
// from D to D+1
for D := 0; D < e.limit; D++ {
for D := range e.limit {
e.setBackward(D+1, -(D + 1), e.getBackward(D, -D)-1)
if ok, ans := e.bdone(D+1, -(D + 1)); ok {
return ans
Expand Down Expand Up @@ -299,7 +300,7 @@ func twosided(e *editGraph) lcs {
e.setBackward(0, 0, e.ux)

// from D to D+1
for D := 0; D < e.limit; D++ {
for D := range e.limit {
// just finished a backwards pass, so check
if got, ok := e.twoDone(D, D); ok {
return e.twolcs(D, D, got)
Expand Down Expand Up @@ -376,10 +377,7 @@ func (e *editGraph) twoDone(df, db int) (int, bool) {
if (df+db+e.delta)%2 != 0 {
return 0, false // diagonals cannot overlap
}
kmin := -db + e.delta
if -df > kmin {
kmin = -df
}
kmin := max(-df, -db+e.delta)
kmax := db + e.delta
if df < kmax {
kmax = df
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ func diffRunes(before, after []rune) []Edit {
func runes(bytes []byte) []rune {
n := utf8.RuneCount(bytes)
runes := make([]rune, n)
for i := 0; i < n; i++ {
for i := range n {
r, sz := utf8.DecodeRune(bytes)
bytes = bytes[sz:]
runes[i] = r
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -129,12 +129,12 @@ func toUnified(fromName, toName string, content string, edits []Edit, contextLin

switch {
case h != nil && start == last:
//direct extension
// direct extension
case h != nil && start <= last+gap:
//within range of previous lines, add the joiners
// within range of previous lines, add the joiners
addEqualLines(h, lines, last, start)
default:
//need to start a new hunk
// need to start a new hunk
if h != nil {
// add the edge to the previous hunk
addEqualLines(h, lines, last, last+contextLines)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import (
"github.com/santhosh-tekuri/jsonschema/v6"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"gopkg.in/yaml.v3"
"go.yaml.in/yaml/v3"

"github.com/palantir/godel-distgo-asset-dist-golangci-lint/generated_src/golangcilint/internal/github.com/golangci/golangci-lint/v2/pkg/exitcodes"
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"log"
"os"

"github.com/fatih/color"
"github.com/spf13/cobra"

"github.com/palantir/godel-distgo-asset-dist-golangci-lint/generated_src/golangcilint/internal/github.com/golangci/golangci-lint/v2/pkg/commands/internal"
Expand All @@ -13,11 +14,19 @@ import (

const envKeepTempFiles = "CUSTOM_GCL_KEEP_TEMP_FILES"

type customOptions struct {
version string
name string
destination string
}

type customCommand struct {
cmd *cobra.Command

cfg *internal.Configuration

opts customOptions

log logutils.Log
}

Expand All @@ -33,6 +42,13 @@ func newCustomCommand(logger logutils.Log) *customCommand {
SilenceUsage: true,
}

flagSet := customCmd.PersistentFlags()
flagSet.SortFlags = false // sort them as they are defined here

flagSet.StringVar(&c.opts.version, "version", "", color.GreenString("The golangci-lint version used to build the custom binary"))
flagSet.StringVar(&c.opts.name, "name", "", color.GreenString("The name of the custom binary"))
flagSet.StringVar(&c.opts.destination, "destination", "", color.GreenString("The directory path used to store the custom binary"))

c.cmd = customCmd

return c
Expand All @@ -44,6 +60,18 @@ func (c *customCommand) preRunE(_ *cobra.Command, _ []string) error {
return err
}

if c.opts.version != "" {
cfg.Version = c.opts.version
}

if c.opts.name != "" {
cfg.Name = c.opts.name
}

if c.opts.destination != "" {
cfg.Destination = c.opts.destination
}

err = cfg.Validate()
if err != nil {
return err
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -138,5 +138,5 @@ func setupIssuesFlagSet(v *viper.Viper, fs *pflag.FlagSet) {
internal.AddFlagAndBind(v, fs, fs.Bool, "whole-files", "issues.whole-files", false,
color.GreenString("Show issues in any part of update files (requires new-from-rev or new-from-patch)"))
internal.AddFlagAndBind(v, fs, fs.Bool, "fix", "issues.fix", false,
color.GreenString("Fix found issues (if it's supported by the linter)"))
color.GreenString("Apply the fixes detected by the linters and formatters (if it's supported by the linter)"))
}
Original file line number Diff line number Diff line change
Expand Up @@ -113,14 +113,11 @@ func (c *fmtCommand) preRunE(_ *cobra.Command, _ []string) error {
}

func (c *fmtCommand) execute(_ *cobra.Command, args []string) error {
paths, err := cleanArgs(args)
if err != nil {
return fmt.Errorf("failed to clean arguments: %w", err)
}
paths := cleanArgs(args)

c.log.Infof("Formatting Go files...")

err = c.runner.Run(paths)
err := c.runner.Run(paths)
if err != nil {
return fmt.Errorf("failed to process files: %w", err)
}
Expand All @@ -134,25 +131,15 @@ func (c *fmtCommand) persistentPostRun(_ *cobra.Command, _ []string) {
}
}

func cleanArgs(args []string) ([]string, error) {
func cleanArgs(args []string) []string {
if len(args) == 0 {
abs, err := filepath.Abs(".")
if err != nil {
return nil, err
}

return []string{abs}, nil
return []string{"."}
}

var expanded []string
for _, arg := range args {
abs, err := filepath.Abs(strings.ReplaceAll(arg, "...", ""))
if err != nil {
return nil, err
}

expanded = append(expanded, abs)
expanded = append(expanded, filepath.Clean(strings.ReplaceAll(arg, "...", "")))
}

return expanded, nil
return expanded
}
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ func (b Builder) clone(ctx context.Context) error {
//nolint:gosec // the variable is sanitized.
cmd := exec.CommandContext(ctx,
"git", "clone", "--branch", sanitizeVersion(b.cfg.Version),
"--single-branch", "--depth", "1", "-c advice.detachedHead=false", "-q",
"--single-branch", "--depth", "1", "-c", "advice.detachedHead=false", "-q",
"https://github.com/golangci/golangci-lint.git",
)
cmd.Dir = b.root
Expand Down Expand Up @@ -257,7 +257,7 @@ func (b Builder) createVersion(orig string) (string, error) {
continue
}

dh, err := dirhash.HashDir(plugin.Path, "", dirhash.DefaultHash)
dh, err := hashDir(plugin.Path, "", dirhash.DefaultHash)
if err != nil {
return "", fmt.Errorf("hash plugin directory: %w", err)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
"path/filepath"
"strings"

"gopkg.in/yaml.v3"
"go.yaml.in/yaml/v3"
)

const base = ".custom-gcl"
Expand Down
Loading