Skip to content

Commit

Permalink
Merge pull request #7 from jcchavezs/adds_support_for_skip_dirs
Browse files Browse the repository at this point in the history
feat: adds support for ignoring files.
  • Loading branch information
jcchavezs authored May 25, 2021
2 parents 0f6b9ac + 9ec7f8f commit 1d36906
Show file tree
Hide file tree
Showing 6 changed files with 66 additions and 25 deletions.
1 change: 0 additions & 1 deletion .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ linters:
- golint
- govet
- ineffassign
#- interfacer
- lll
- misspell
- nakedret
Expand Down
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,9 @@ If you just want to list the files that porto would change vanity import, run:
```bash
porto -l path/to/library
```

If you want to ignore files (e.g. proto generated files), pass the `--skip-files` flag:

```bash
porto --skip-files ".*\\.pb\\.go$" path/to/library
```
21 changes: 18 additions & 3 deletions cmd/porto/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,16 @@ import (
"log"
"os"
"path/filepath"
"regexp"
"strings"

"github.com/jcchavezs/porto"
)

func main() {
flagWrite := flag.Bool("w", false, "write result to (source) file instead of stdout")
flagList := flag.Bool("l", false, "list files whose vanity import differs from porto's")
flagSkipFiles := flag.String("skip-files", "", "Regexps of files to skip")
flag.Parse()

baseDir := flag.Arg(0)
Expand All @@ -21,8 +24,9 @@ func main() {
usage: porto [options] path
Options:
-w write result to (source) file instead of stdout (default: false)
-l list files whose vanity import differs from porto's (default: false)
-w Write result to (source) file instead of stdout (default: false)
-l List files whose vanity import differs from porto's (default: false)
--skip-files Regexps of files to skip
Examples:
Expand All @@ -42,10 +46,21 @@ Add import path to a folder
log.Fatalf("failed to resolve base absolute path for %q: %v", baseDir, err)
}

var skipFilesRegex []*regexp.Regexp
if len(*flagSkipFiles) > 0 {
for _, sfrp := range strings.Split(*flagSkipFiles, ",") {
sfr, err := regexp.Compile(sfrp)
if err != nil {
log.Fatalf("failed to resolve base absolute path for %q: %v", baseDir, err)
}
skipFilesRegex = append(skipFilesRegex, sfr)
}
}

err = porto.FindAndAddVanityImportForDir(workingDir, baseAbsDir, porto.Options{
WriteResultToFile: *flagWrite,
ListDiffFiles: *flagList,
GeneratedPrefixes: []string{"Code generated"},
SkipFilesRegexes: skipFilesRegex,
})
if err != nil {
log.Fatal(err)
Expand Down
36 changes: 20 additions & 16 deletions import.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,15 @@ import (
"go/token"
"io/ioutil"
"path/filepath"
"strings"
"regexp"
)

var (
errGeneratedCode = errors.New("failed to add import to a generated code")
errMainPackage = errors.New("failed to add import to a main package")
errMainPackage = errors.New("failed to add import to a main package")
)

// addImportPath adds the vanity import path to a given go file.
func addImportPath(absFilepath string, module string, genPrefixes []string) (bool, []byte, error) {
func addImportPath(absFilepath string, module string) (bool, []byte, error) {
fset := token.NewFileSet()
pf, err := parser.ParseFile(fset, absFilepath, nil, 0)
if err != nil {
Expand All @@ -36,13 +35,6 @@ func addImportPath(absFilepath string, module string, genPrefixes []string) (boo
// 9 = len("package ") + 1 because that is the first character of the package name
startPackageLinePos := int(pf.Name.NamePos) - 9

headerComments := string(content[0:startPackageLinePos])
for _, genPrefix := range genPrefixes {
if strings.Contains(headerComments, "// "+genPrefix) {
return false, nil, errGeneratedCode
}
}

// first 1 = len(" ") as in "package " and the other 1 is for newline
endPackageLinePos := pf.Name.NamePos
newLineChar := byte(10)
Expand Down Expand Up @@ -89,10 +81,10 @@ func findAndAddVanityImportForModuleDir(workingDir, absDir string, moduleName st
return err
}
}
} else if fileName := f.Name(); isGoFile(fileName) && !isGoTestFile(fileName) {
} else if fileName := f.Name(); isGoFile(fileName) && !isGoTestFile(fileName) && !isIgnoredFile(opts.SkipFilesRegexes, fileName) {
absFilepath := absDir + pathSeparator + fileName

hasChanged, newContent, err := addImportPath(absDir+pathSeparator+fileName, moduleName, opts.GeneratedPrefixes)
hasChanged, newContent, err := addImportPath(absDir+pathSeparator+fileName, moduleName)
if !hasChanged {
continue
}
Expand All @@ -118,7 +110,7 @@ func findAndAddVanityImportForModuleDir(workingDir, absDir string, moduleName st
fmt.Printf("👉 %s\n\n", relFilepath)
fmt.Println(string(newContent))
}
case errGeneratedCode, errMainPackage:
case errMainPackage:
continue
default:
return fmt.Errorf("failed to add vanity import path to %q: %v", absDir+pathSeparator+fileName, err)
Expand All @@ -129,6 +121,16 @@ func findAndAddVanityImportForModuleDir(workingDir, absDir string, moduleName st
return nil
}

func isIgnoredFile(fileRegexes []*regexp.Regexp, filename string) bool {
for _, fr := range fileRegexes {
if matched := fr.MatchString(filename); matched {
return true
}
}

return false
}

func findAndAddVanityImportForNonModuleDir(workingDir, absDir string, opts Options) error {
files, err := ioutil.ReadDir(absDir)
if err != nil {
Expand Down Expand Up @@ -163,8 +165,10 @@ func findAndAddVanityImportForNonModuleDir(workingDir, absDir string, opts Optio
type Options struct {
// writes result to file directly
WriteResultToFile bool
ListDiffFiles bool
GeneratedPrefixes []string
// List files to be changed
ListDiffFiles bool
// Set of regex for matching files to be skipped
SkipFilesRegexes []*regexp.Regexp
}

// FindAndAddVanityImportForDir scans all files in a folder and based on go.mod files
Expand Down
25 changes: 21 additions & 4 deletions import_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package porto

import (
"os"
"regexp"
"testing"

"github.com/stretchr/testify/assert"
Expand All @@ -12,8 +13,7 @@ func TestAddImportPathAddsVanityImport(t *testing.T) {
cwd, _ := os.Getwd()
hasChanged, newContent, err := addImportPath(
cwd+"/testdata/leftpad/leftpad.go",
"mypackage",
[]string{})
"mypackage")

require.NoError(t, err)
assert.True(t, hasChanged)
Expand All @@ -24,10 +24,27 @@ func TestAddImportPathFixesTheVanityImport(t *testing.T) {
cwd, _ := os.Getwd()
hasChanged, newContent, err := addImportPath(
cwd+"/testdata/rightpad/rightpad.go",
"mypackage",
[]string{})
"mypackage")

require.NoError(t, err)
assert.True(t, hasChanged)
assert.Equal(t, "package rightpad // import \"mypackage\"", string(newContent[:38]))
}

func TestIsIgnoredFile(t *testing.T) {
assert.True(
t,
isIgnoredFile(
[]*regexp.Regexp{regexp.MustCompile(".*\\.pb\\.go$")},
"myfile.pb.go",
),
)

assert.False(
t,
isIgnoredFile(
[]*regexp.Regexp{},
"myfile.pb.go",
),
)
}
2 changes: 1 addition & 1 deletion testdata/codegen/gen.go → testdata/codegen/user.pb.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 1d36906

Please sign in to comment.