Skip to content

Commit

Permalink
Merge pull request #8 from jcchavezs/fails_on_list_if_found
Browse files Browse the repository at this point in the history
Fails on list if found
  • Loading branch information
jcchavezs authored Sep 25, 2021
2 parents 1d36906 + 3a1bf43 commit dc63ced
Show file tree
Hide file tree
Showing 13 changed files with 1,357 additions and 40 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/merge.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ jobs:
runs-on: ubuntu-20.04
strategy:
matrix:
go: ["1.13", "1.14", "1.15"]
go: ["1.13", "1.14", "1.15", "1.16", "1.17"]
steps:
# Set fetch-depth: 0 to fetch commit history and tags for use in version calculation
- name: Check out code
Expand All @@ -34,7 +34,7 @@ jobs:
uses: golangci/golangci-lint-action@v2
with:
# Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version.
version: v1.29
version: v1.42

- name: Run tests
run: go test ./...
22 changes: 22 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
.DEFAULT_GOAL := test

.PHONY: test
test:
@go test -count=1 -v -race -cover ./...

.PHONY: lint
lint:
@echo "Running linters..."
@golangci-lint run ./... && echo "Done."

.PHONY: deps
deps:
@go get -v -t -d ./...

.PHONY: fmt
fmt:
gofmt -w -s ./

.PHONY: install-tools
install-tools: ## Install all the dependencies under the tools module
$(MAKE) -C ./tools install
22 changes: 13 additions & 9 deletions cmd/porto/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,15 @@ import (
)

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")
flagWriteOutputToFile := flag.Bool("w", false, "write result to (source) file instead of stdout")
flagListDiff := 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)
if len(flag.Args()) == 0 {
fmt.Println(`
usage: porto [options] path
usage: porto [options] <target-path>
Options:
-w Write result to (source) file instead of stdout (default: false)
Expand All @@ -31,19 +31,19 @@ Options:
Examples:
Add import path to a folder
$ porto -w myproject
$ porto -w ./myproject
`)
os.Exit(0)
}

baseAbsDir, err := filepath.Abs(baseDir)
if err != nil {
log.Fatalf("failed to resolve base absolute path for %q: %v", baseDir, err)
log.Fatalf("failed to resolve base absolute path for target path %q: %v", baseDir, err)
}

workingDir, err := os.Getwd()
if err != nil {
log.Fatalf("failed to resolve base absolute path for %q: %v", baseDir, err)
log.Fatalf("failed to resolve base absolute path for current working dir: %v", err)
}

var skipFilesRegex []*regexp.Regexp
Expand All @@ -57,12 +57,16 @@ Add import path to a folder
}
}

err = porto.FindAndAddVanityImportForDir(workingDir, baseAbsDir, porto.Options{
WriteResultToFile: *flagWrite,
ListDiffFiles: *flagList,
diffCount, err := porto.FindAndAddVanityImportForDir(workingDir, baseAbsDir, porto.Options{
WriteResultToFile: *flagWriteOutputToFile,
ListDiffFiles: *flagListDiff,
SkipFilesRegexes: skipFilesRegex,
})
if err != nil {
log.Fatal(err)
}

if *flagListDiff && diffCount > 0 {
os.Exit(2)
}
}
81 changes: 54 additions & 27 deletions import.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,30 +57,38 @@ func addImportPath(absFilepath string, module string) (bool, []byte, error) {
newContent = append(newContent, importComment...)
newContent = append(newContent, content[endPackageLinePos:]...)

return bytes.Compare(content, newContent) != 0, newContent, nil
return !bytes.Equal(content, newContent), newContent, nil
}

func findAndAddVanityImportForModuleDir(workingDir, absDir string, moduleName string, opts Options) error {
func findAndAddVanityImportForModuleDir(workingDir, absDir string, moduleName string, opts Options) (int, error) {
files, err := ioutil.ReadDir(absDir)
if err != nil {
return fmt.Errorf("failed to read the content of %q: %v", absDir, err)
return 0, fmt.Errorf("failed to read the content of %q: %v", absDir, err)
}

gc := 0
for _, f := range files {
if isDir, dirName := f.IsDir(), f.Name(); isDir {
var (
c int
err error
)
if isUnexportedDir(dirName) {
continue
} else if newModuleName, ok := findGoModule(absDir + pathSeparator + dirName); ok {
// if folder contains go.mod we use it from now on to build the vanity import
if err := findAndAddVanityImportForModuleDir(workingDir, absDir+pathSeparator+dirName, newModuleName, opts); err != nil {
return err
c, err = findAndAddVanityImportForModuleDir(workingDir, absDir+pathSeparator+dirName, newModuleName, opts)
if err != nil {
return 0, err
}
} else {
// if not, we add the folder name to the vanity import
if err := findAndAddVanityImportForModuleDir(workingDir, absDir+pathSeparator+dirName, moduleName+"/"+dirName, opts); err != nil {
return err
if c, err = findAndAddVanityImportForModuleDir(workingDir, absDir+pathSeparator+dirName, moduleName+"/"+dirName, opts); err != nil {
return 0, err
}
}

gc += c
} else if fileName := f.Name(); isGoFile(fileName) && !isGoTestFile(fileName) && !isIgnoredFile(opts.SkipFilesRegexes, fileName) {
absFilepath := absDir + pathSeparator + fileName

Expand All @@ -94,31 +102,34 @@ func findAndAddVanityImportForModuleDir(workingDir, absDir string, moduleName st
if opts.WriteResultToFile {
err = writeContentToFile(absFilepath, newContent)
if err != nil {
return fmt.Errorf("failed to write file: %v", err)
return 0, fmt.Errorf("failed to write file: %v", err)
}
gc++
} else if opts.ListDiffFiles {
relFilepath, err := filepath.Rel(workingDir, absFilepath)
if err != nil {
return fmt.Errorf("failed to resolve relative path: %v", err)
return 0, fmt.Errorf("failed to resolve relative path: %v", err)
}
fmt.Println(relFilepath)
fmt.Printf("%s: missing right vanity import\n", relFilepath)
gc++
} else {
relFilepath, err := filepath.Rel(workingDir, absFilepath)
if err != nil {
return fmt.Errorf("failed to resolve relative path: %v", err)
return 0, fmt.Errorf("failed to resolve relative path: %v", err)
}
fmt.Printf("👉 %s\n\n", relFilepath)
fmt.Println(string(newContent))
gc++
}
case errMainPackage:
continue
default:
return fmt.Errorf("failed to add vanity import path to %q: %v", absDir+pathSeparator+fileName, err)
return 0, fmt.Errorf("failed to add vanity import path to %q: %v", absDir+pathSeparator+fileName, err)
}
}
}

return nil
return gc, nil
}

func isIgnoredFile(fileRegexes []*regexp.Regexp, filename string) bool {
Expand All @@ -131,12 +142,13 @@ func isIgnoredFile(fileRegexes []*regexp.Regexp, filename string) bool {
return false
}

func findAndAddVanityImportForNonModuleDir(workingDir, absDir string, opts Options) error {
func findAndAddVanityImportForNonModuleDir(workingDir, absDir string, opts Options) (int, error) {
files, err := ioutil.ReadDir(absDir)
if err != nil {
return fmt.Errorf("failed to read %q: %v", absDir, err)
return 0, fmt.Errorf("failed to read %q: %v", absDir, err)
}

gc := 0
for _, f := range files {
if !f.IsDir() {
continue
Expand All @@ -147,18 +159,26 @@ func findAndAddVanityImportForNonModuleDir(workingDir, absDir string, opts Optio
continue
}

var (
c int
err error
)

absDirName := absDir + pathSeparator + dirName
if moduleName, ok := findGoModule(absDirName); ok {
if err := findAndAddVanityImportForModuleDir(workingDir, dirName, moduleName, opts); err != nil {
return err
if c, err = findAndAddVanityImportForModuleDir(workingDir, dirName, moduleName, opts); err != nil {
return 0, err
}
} else {
if err := findAndAddVanityImportForNonModuleDir(workingDir, absDirName, opts); err != nil {
return err
if c, err = findAndAddVanityImportForNonModuleDir(workingDir, absDirName, opts); err != nil {
return 0, err
}
}

gc += c
}
return nil

return gc, nil
}

// Options represents the options for adding vanity import.
Expand All @@ -173,16 +193,17 @@ type Options struct {

// FindAndAddVanityImportForDir scans all files in a folder and based on go.mod files
// encountered decides wether add a vanity import or not.
func FindAndAddVanityImportForDir(workingDir, absDir string, opts Options) error {
func FindAndAddVanityImportForDir(workingDir, absDir string, opts Options) (int, error) {
if moduleName, ok := findGoModule(absDir); ok {
return findAndAddVanityImportForModuleDir(workingDir, absDir, moduleName, opts)
}

files, err := ioutil.ReadDir(absDir)
if err != nil {
return fmt.Errorf("failed to read the content of %q: %v", absDir, err)
return 0, fmt.Errorf("failed to read the content of %q: %v", absDir, err)
}

gc := 0
for _, f := range files {
if !f.IsDir() {
// we already knew this is not a Go modules folder hence we are not looking
Expand All @@ -195,17 +216,23 @@ func FindAndAddVanityImportForDir(workingDir, absDir string, opts Options) error
continue
}

var (
c int
err error
)
absDirName := absDir + pathSeparator + dirName
if moduleName, ok := findGoModule(absDirName); ok {
if err := findAndAddVanityImportForModuleDir(workingDir, dirName, moduleName, opts); err != nil {
return err
if c, err = findAndAddVanityImportForModuleDir(workingDir, dirName, moduleName, opts); err != nil {
return 0, err
}
} else {
if err := findAndAddVanityImportForNonModuleDir(workingDir, absDirName, opts); err != nil {
return err
if c, err = findAndAddVanityImportForNonModuleDir(workingDir, absDirName, opts); err != nil {
return 0, err
}
}

gc += c
}

return nil
return gc, nil
}
35 changes: 34 additions & 1 deletion import_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ func TestAddImportPathAddsVanityImport(t *testing.T) {

require.NoError(t, err)
assert.True(t, hasChanged)
assert.Equal(t, "package leftpad // import \"mypackage\"", string(newContent[14:51]))
assert.Equal(t, "package leftpad // import \"mypackage\"", string(newContent[15:52]))
}

func TestAddImportPathFixesTheVanityImport(t *testing.T) {
Expand All @@ -31,6 +31,39 @@ func TestAddImportPathFixesTheVanityImport(t *testing.T) {
assert.Equal(t, "package rightpad // import \"mypackage\"", string(newContent[:38]))
}

func TestFindFilesWithVanityImport(t *testing.T) {
cwd, _ := os.Getwd()

t.Run("one file listed", func(t *testing.T) {
c, err := findAndAddVanityImportForModuleDir(
cwd,
cwd+"/testdata/leftpad",
"github.com/jcchavezs/porto-integration-leftpad",
Options{
ListDiffFiles: true,
},
)

require.NoError(t, err)
assert.Equal(t, 2, c)
})

t.Run("no files listed", func(t *testing.T) {
c, err := findAndAddVanityImportForModuleDir(
cwd,
cwd+"/testdata/nopad",
"github.com/jcchavezs/porto-integration/nopad",
Options{
ListDiffFiles: true,
},
)

require.NoError(t, err)
assert.Equal(t, 0, c)
})

}

func TestIsIgnoredFile(t *testing.T) {
assert.True(
t,
Expand Down
2 changes: 1 addition & 1 deletion testdata/leftpad/leftpad.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// a coment!
// a comment!

package leftpad

Expand Down
3 changes: 3 additions & 0 deletions testdata/leftpad/other.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
// another comment!

package leftpad
3 changes: 3 additions & 0 deletions testdata/nopad/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module github.com/jcchavezs/porto-integration/nopad

go 1.15
6 changes: 6 additions & 0 deletions testdata/nopad/nopad.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package nopad // import "github.com/jcchavezs/porto-integration/nopad"

// NoPad returns the same string
func NoPad(s string, length int) string {
return s
}
4 changes: 4 additions & 0 deletions tools/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
.PHONY: install
install:
go mod download
go install github.com/golangci/golangci-lint/cmd/golangci-lint
5 changes: 5 additions & 0 deletions tools/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module tools

go 1.15

require github.com/golangci/golangci-lint v1.42.1
Loading

0 comments on commit dc63ced

Please sign in to comment.