Skip to content

Commit

Permalink
Allow skipping generated files (#67)
Browse files Browse the repository at this point in the history
* Implement skipping generated files

Add a new command-line flag that is disabled by default which will skip
processing generated files.

Signed-off-by: Mario Valderrama <mario.valderrama@ionos.com>

* Add test for skipping generated files

Signed-off-by: Mario Valderrama <mario.valderrama@ionos.com>

* Fix gofumpt issues

Signed-off-by: Mario Valderrama <mario.valderrama@ionos.com>
  • Loading branch information
avorima authored Jun 30, 2022
1 parent dc2b1ce commit 1964a6b
Show file tree
Hide file tree
Showing 8 changed files with 85 additions and 7 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ Flags:
Std | Standard - Captures all standard packages if they do not match another section
(default [Standard,Default])
-x, --SectionSeparator strings SectionSeparators are inserted between Sections (default [NewLine])
--SkipGeneratedFiles Don't process generated files
-h, --help help for print
```
Expand All @@ -62,6 +63,7 @@ Flags:
Std | Standard - Captures all standard packages if they do not match another section
(default [Standard,Default])
-x, --SectionSeparator strings SectionSeparators are inserted between Sections (default [NewLine])
--SkipGeneratedFiles Don't process generated files
-h, --help help for write
```
Expand All @@ -83,6 +85,7 @@ Flags:
Std | Standard - Captures all standard packages if they do not match another section
(default [Standard,Default])
-x, --SectionSeparator strings SectionSeparators are inserted between Sections (default [NewLine])
--SkipGeneratedFiles Don't process generated files
-d, --debug Enables debug output from the formatter
-h, --help help for diff
```
Expand Down
7 changes: 5 additions & 2 deletions cmd/gci/gcicommand.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import (
type processingFunc = func(args []string, gciCfg gci.GciConfiguration) error

func (e *Executor) newGciCommand(use, short, long string, aliases []string, stdInSupport bool, processingFunc processingFunc) *cobra.Command {
var noInlineComments, noPrefixComments, debug *bool
var noInlineComments, noPrefixComments, debug, skipGeneratedFiles *bool
var sectionStrings, sectionSeparatorStrings *[]string
cmd := cobra.Command{
Use: use,
Expand All @@ -26,7 +26,9 @@ func (e *Executor) newGciCommand(use, short, long string, aliases []string, stdI
ValidArgsFunction: goFileCompletion,
RunE: func(cmd *cobra.Command, args []string) error {
fmtCfg := configuration.FormatterConfiguration{*noInlineComments, *noPrefixComments, *debug}
gciCfg, err := gci.GciStringConfiguration{fmtCfg, *sectionStrings, *sectionSeparatorStrings}.Parse()
gciCfg, err := gci.GciStringConfiguration{
fmtCfg, *sectionStrings, *sectionSeparatorStrings, *skipGeneratedFiles,
}.Parse()
if err != nil {
return err
}
Expand Down Expand Up @@ -55,5 +57,6 @@ func (e *Executor) newGciCommand(use, short, long string, aliases []string, stdI
noPrefixComments = cmd.Flags().Bool("NoPrefixComments", false, "Drops comment lines above an import statement while formatting")
sectionStrings = cmd.Flags().StringSliceP("Section", "s", gci.DefaultSections().String(), sectionHelp)
sectionSeparatorStrings = cmd.Flags().StringSliceP("SectionSeparator", "x", gci.DefaultSectionSeparators().String(), "SectionSeparators are inserted between Sections")
skipGeneratedFiles = cmd.Flags().Bool("SkipGeneratedFiles", false, "Don't process generated files")
return &cmd
}
4 changes: 3 additions & 1 deletion cmd/gci/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,9 @@ func (e *Executor) runInCompatibilityMode(cmd *cobra.Command, args []string) err
// generate section specification from old localFlags format
sections := gci.LocalFlagsToSections(*e.localFlags)
sectionSeparators := gci.DefaultSectionSeparators()
cfg := gci.GciConfiguration{configuration.FormatterConfiguration{false, false, false}, sections, sectionSeparators}
cfg := gci.GciConfiguration{
configuration.FormatterConfiguration{false, false, false}, sections, sectionSeparators, false,
}
if *e.writeMode {
return gci.WriteFormattedFiles(args, cfg)
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/analyzer/analyzer.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ func parseGciConfiguration() (*gci.GciConfiguration, error) {
sectionSeparatorStrings = strings.Split(sectionSeparatorsStr, SectionDelimiter)
fmt.Println(sectionSeparatorsStr)
}
return gci.GciStringConfiguration{fmtCfg, sectionStrings, sectionSeparatorStrings}.Parse()
return gci.GciStringConfiguration{fmtCfg, sectionStrings, sectionSeparatorStrings, false}.Parse()
}

func generateCmdLine(cfg gci.GciConfiguration) string {
Expand Down
8 changes: 5 additions & 3 deletions pkg/gci/configuration.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,16 @@ import (

type GciConfiguration struct {
configuration.FormatterConfiguration
Sections SectionList
SectionSeparators SectionList
Sections SectionList
SectionSeparators SectionList
SkipGeneratedFiles bool
}

type GciStringConfiguration struct {
Cfg configuration.FormatterConfiguration `yaml:",inline"`
SectionStrings []string `yaml:"sections"`
SectionSeparatorStrings []string `yaml:"sectionseparators"`
SkipGeneratedFiles bool `yaml:"skipGeneratedFiles"`
}

func (g GciStringConfiguration) Parse() (*GciConfiguration, error) {
Expand All @@ -37,7 +39,7 @@ func (g GciStringConfiguration) Parse() (*GciConfiguration, error) {
return nil, err
}
}
return &GciConfiguration{g.Cfg, sections, sectionSeparators}, nil
return &GciConfiguration{g.Cfg, sections, sectionSeparators, g.SkipGeneratedFiles}, nil
}

func initializeGciConfigFromYAML(filePath string) (*GciConfiguration, error) {
Expand Down
26 changes: 26 additions & 0 deletions pkg/gci/gci.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"os"
"strings"
"sync"

"github.com/hexops/gotextdiff"
Expand Down Expand Up @@ -129,6 +130,9 @@ func LoadFormatGoFile(file io.FileObj, cfg GciConfiguration) (unmodifiedFile, fo
if err != nil {
return nil, nil, err
}
if cfg.SkipGeneratedFiles && isGeneratedFileByComment(string(unmodifiedFile)) {
return unmodifiedFile, unmodifiedFile, nil
}

formattedFile, err = formatGoFile(unmodifiedFile, cfg)
if err != nil {
Expand All @@ -141,3 +145,25 @@ func LoadFormatGoFile(file io.FileObj, cfg GciConfiguration) (unmodifiedFile, fo
}
return unmodifiedFile, formattedFile, nil
}

// isGenerated reports whether the source file is generated code.
// Using a bit laxer rules than https://golang.org/s/generatedcode to
// match more generated code.
// Taken from https://github.com/golangci/golangci-lint.
func isGeneratedFileByComment(doc string) bool {
const (
genCodeGenerated = "code generated"
genDoNotEdit = "do not edit"
genAutoFile = "autogenerated file" // easyjson
)

markers := []string{genCodeGenerated, genDoNotEdit, genAutoFile}
doc = strings.ToLower(doc)
for _, marker := range markers {
if strings.Contains(doc, marker) {
return true
}
}

return false
}
28 changes: 28 additions & 0 deletions pkg/gci/gci_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,34 @@ func TestSkippingOverIncorrectlyFormattedFiles(t *testing.T) {
assert.True(t, <-validFileProcessedChan)
}

func TestSkippingGeneratedFiles(t *testing.T) {
cfg, err := GciStringConfiguration{SkipGeneratedFiles: true}.Parse()
assert.NoError(t, err)

var generatedCodeCtr int
var files []io.FileObj
files = append(files, TestFile{io.File{"internal/skipTest/generated_code.go"}, &generatedCodeCtr})

validFileProcessedChan := make(chan bool, len(files))

generatorFunc := func() ([]io.FileObj, error) {
return files, nil
}
fileAccessTestFunc := func(_ string, unmodifiedFile, formattedFile []byte) error {
validFileProcessedChan <- true
assert.NotEmpty(t, unmodifiedFile)
assert.Equal(t, string(unmodifiedFile), string(formattedFile))
return nil
}
err = processFiles(generatorFunc, *cfg, fileAccessTestFunc)

assert.NoError(t, err)
// check all files have been accessed
assert.Equal(t, generatedCodeCtr, 1)
// check that processing for the valid file was called
assert.True(t, <-validFileProcessedChan)
}

type TestFile struct {
wrappedFile io.File
accessCounter *int
Expand Down
14 changes: 14 additions & 0 deletions pkg/gci/internal/skipTest/generated_code.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package testdata

// DO NOT EDIT

import (
"testing"

"fmt"
)

// nolint
func Test(t *testing.T) {
fmt.Println("test")
}

0 comments on commit 1964a6b

Please sign in to comment.