-
Notifications
You must be signed in to change notification settings - Fork 66
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
automatically detect Go module path #31
Draft
dmke
wants to merge
1
commit into
daixiang0:master
Choose a base branch
from
dmke:feat/modules
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
sections: | ||
- Standard | ||
- Module | ||
- Default |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
package main | ||
import ( | ||
"github.com/daixiang0/gci" | ||
|
||
"golang.org/x/tools" | ||
|
||
"fmt" | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
package main | ||
import ( | ||
"fmt" | ||
|
||
"github.com/daixiang0/gci" | ||
|
||
"golang.org/x/tools" | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,100 @@ | ||
package gci | ||
|
||
import ( | ||
"errors" | ||
"fmt" | ||
"io/ioutil" | ||
"os" | ||
"path/filepath" | ||
"strings" | ||
|
||
"golang.org/x/mod/modfile" | ||
) | ||
|
||
// moduleResolver looksup the module path for a given (Go) file. | ||
// To improve performance, the file paths and module paths are | ||
// cached. | ||
// | ||
// Given the following directory structure: | ||
// | ||
// /path/to/example | ||
// +-- go.mod (module example) | ||
// +-- cmd/sample/main.go (package main, imports example/util) | ||
// +-- util/util.go (package util) | ||
// | ||
// After looking up main.go and util.go, the internal cache will contain: | ||
// | ||
// "/path/to/foobar/": "example" | ||
// | ||
// For more complex module structures (i.e. sub-modules), the cache | ||
// might look like this: | ||
// | ||
// "/path/to/example/": "example" | ||
// "/path/to/example/cmd/sample/": "go.example.com/historic/path" | ||
// | ||
// When matching files against this cache, the resolver will select the | ||
// entry with the most specific path (so that, in this example, the file | ||
// cmd/sample/main.go will resolve to go.example.com/historic/path). | ||
type moduleResolver map[string]string | ||
|
||
func (m moduleResolver) Lookup(file string) (string, error) { | ||
abs, err := filepath.Abs(file) | ||
if err != nil { | ||
return "", fmt.Errorf("could not make path absolute: %w", err) | ||
} | ||
|
||
var bestMatch string | ||
for path := range m { | ||
if strings.HasPrefix(abs, path) && len(path) > len(bestMatch) { | ||
bestMatch = path | ||
} | ||
} | ||
if bestMatch != "" { | ||
return m[bestMatch], nil | ||
} | ||
|
||
return m.findRecursively(filepath.Dir(abs)) | ||
} | ||
|
||
func (m moduleResolver) findRecursively(dir string) (string, error) { | ||
// When going up the directory tree, we might never find a go.mod | ||
// file. In this case remember where we started, so that the next | ||
// time we can short circuit the recursive ascent. | ||
stop := dir | ||
|
||
for { | ||
gomod := filepath.Join(dir, "go.mod") | ||
_, err := os.Stat(gomod) | ||
if errors.Is(err, os.ErrNotExist) { | ||
// go.mod doesn't exist at current location | ||
next := filepath.Dir(dir) | ||
if next == dir { | ||
// we're at the top of the filesystem | ||
m[stop] = "" | ||
return "", nil | ||
} | ||
// go one level up | ||
dir = next | ||
continue | ||
} else if err != nil { | ||
// other error (likely EPERM) | ||
return "", fmt.Errorf("module lookup failed: %w", err) | ||
} | ||
|
||
// we found a go.mod | ||
mod, err := ioutil.ReadFile(gomod) | ||
if err != nil { | ||
return "", fmt.Errorf("reading module failed: %w", err) | ||
} | ||
|
||
// store module path at m[dir]. add path separator to avoid | ||
// false-positive (think of /foo and /foobar). | ||
mpath := modfile.ModulePath(mod) | ||
if dir != "/" { | ||
// add trailing path sep, but not for *nix root directory | ||
dir += string(os.PathListSeparator) | ||
} | ||
m[dir] = mpath | ||
return mpath, nil | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
package sections | ||
|
||
import ( | ||
"strings" | ||
|
||
"github.com/daixiang0/gci/pkg/configuration" | ||
importPkg "github.com/daixiang0/gci/pkg/gci/imports" | ||
"github.com/daixiang0/gci/pkg/gci/specificity" | ||
) | ||
|
||
func init() { | ||
prefixType := SectionType{ | ||
generatorFun: func(parameter string, sectionPrefix, sectionSuffix Section) (Section, error) { | ||
return Module{}, nil | ||
}, | ||
aliases: []string{"Module", "Mod"}, | ||
description: "Groups all imports of the corresponding Go module", | ||
}.StandAloneSection().WithoutParameter() | ||
SectionParserInst.registerSectionWithoutErr(&prefixType) | ||
} | ||
|
||
type Module struct { | ||
// modulePaths contains all known Go module path names. | ||
// | ||
// This must be a pointer, because gci.formatImportBlock() will create | ||
// mapping between sections and imports, and slices are unhashable. | ||
modulePaths *[]string | ||
} | ||
|
||
func (m Module) MatchSpecificity(spec importPkg.ImportDef) specificity.MatchSpecificity { | ||
if m.modulePaths == nil { | ||
return specificity.MisMatch{} | ||
} | ||
|
||
importPath := spec.Path() | ||
for _, path := range *m.modulePaths { | ||
if strings.HasPrefix(importPath, path) { | ||
return specificity.Module{} | ||
} | ||
} | ||
return specificity.MisMatch{} | ||
} | ||
|
||
func (m Module) Format(imports []importPkg.ImportDef, cfg configuration.FormatterConfiguration) string { | ||
return inorderSectionFormat(m, imports, cfg) | ||
} | ||
|
||
func (Module) sectionPrefix() Section { return nil } | ||
func (Module) sectionSuffix() Section { return nil } | ||
|
||
func (Module) String() string { | ||
return "Module" | ||
} | ||
|
||
func (m *Module) SetModulePaths(paths []string) { | ||
dup := make([]string, len(paths), len(paths)) | ||
copy(dup, paths) | ||
|
||
m.modulePaths = &dup | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
package specificity | ||
|
||
type Module struct{} | ||
|
||
func (m Module) IsMoreSpecific(than MatchSpecificity) bool { | ||
return isMoreSpecific(m, than) | ||
} | ||
|
||
func (m Module) Equal(to MatchSpecificity) bool { | ||
return equalSpecificity(m, to) | ||
} | ||
|
||
func (Module) class() specificityClass { | ||
return ModuleClass | ||
} | ||
|
||
func (Module) String() string { | ||
return "Module" | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This doesn't work,
moduleSection
is a pointer to a copy ofg.Section[i]
.