Compare commits

..

6 Commits
v0.0.2 ... main

Author SHA1 Message Date
jolheiser 587759243a
fix: empty module
ci/woodpecker/push/goreleaser Pipeline was successful Details
Signed-off-by: jolheiser <john.olheiser@gmail.com>
2023-07-16 22:56:33 -05:00
jolheiser 49a668d1a9
fix: cwd
ci/woodpecker/push/goreleaser Pipeline was successful Details
Signed-off-by: jolheiser <john.olheiser@gmail.com>
2023-07-16 21:43:05 -05:00
jolheiser 5c91d2e95a
fix: print errors to stderr and exit code 1
ci/woodpecker/push/goreleaser Pipeline was successful Details
Signed-off-by: jolheiser <john.olheiser@gmail.com>
2023-07-16 21:12:52 -05:00
jolheiser f9f2f02f90
fix: stdin print string
ci/woodpecker/push/goreleaser Pipeline was successful Details
Signed-off-by: jolheiser <john.olheiser@gmail.com>
2023-07-16 19:01:14 -05:00
jolheiser f17818f834
feat: remove extra whitespace, clean up deps, and add optional gofumpt formatting
Signed-off-by: jolheiser <john.olheiser@gmail.com>
2023-07-16 14:49:44 -05:00
jolheiser 08f9985010
fix: check for single import
ci/woodpecker/push/goreleaser Pipeline was successful Details
ci/woodpecker/tag/goreleaser Pipeline was successful Details
Signed-off-by: jolheiser <john.olheiser@gmail.com>
2023-01-10 11:35:59 -06:00
8 changed files with 136 additions and 49 deletions

View File

@ -13,10 +13,13 @@ import (
)
```
imp includes three flags:
imp includes five flags:
* `--write` will write out the formatting rather than printing
* `--ignore` reads a `.impignore` file for globs to include/exclude (`.impignore` by default)
* `--stdin` will read from stdin and print to stdout
* `--gofumpt` will also format using [gofumpt](https://github.com/mvdan/gofumpt)
* `--gofumpt-extra` will include [gofumpt extra rules](https://github.com/mvdan/gofumpt#extra-rules-behind--extra)
### `.impignore` format

View File

@ -8,13 +8,18 @@ import (
)
var (
importRe = regexp.MustCompile(`(?ms)import \(([^)]+)\)`)
otherRe = regexp.MustCompile(`^(?:var|const|func)\s`)
ErrNoImports = errors.New("no imports found")
importRe = regexp.MustCompile(`(?ms)^import \(([^)]+)\)`)
singleImportRe = regexp.MustCompile(`(?ms)^import "[^"]+"`)
otherRe = regexp.MustCompile(`^(?:var|const|func)\s`)
ErrNoImports = errors.New("no imports found")
)
// Source formats a given src's imports
func Source(src []byte, module string) ([]byte, error) {
if singleImportRe.Match(src) {
return src, nil
}
importStart := importRe.FindIndex(src)
if importStart == nil {
return nil, fmt.Errorf("could not find imports: %w", ErrNoImports)

View File

@ -22,6 +22,9 @@ func TestSource(t *testing.T) {
formatted, err := Source(before, module)
assert.NoErr(err) // Should be able to format before block
assert.True(bytes.Equal(formatted, after)) // Formatted should match after block
_, err = Source(singleImport, module)
assert.NoErr(err) // Should not get an error for single import
}
var (
@ -34,6 +37,11 @@ func main() {
s := "import \"fmt\""
_ = s
}`)
singleImport = []byte(`package main
import "fmt"
func main() {}`)
before = []byte(`package main
import (

View File

@ -42,11 +42,11 @@ func (i importBlock) String() string {
var decl strings.Builder
decl.WriteString(strings.Join(importItemSlice(i.Stdlib), "\n\t"))
if len(i.Module) > 0 {
if len(i.Stdlib) != 0 && len(i.Module) > 0 {
decl.WriteString("\n\n\t")
}
decl.WriteString(strings.Join(importItemSlice(i.Module), "\n\t"))
if len(i.Other) > 0 {
if len(i.Module) != 0 && len(i.Other) > 0 {
decl.WriteString("\n\n\t")
}
decl.WriteString(strings.Join(importItemSlice(i.Other), "\n\t"))

8
go.mod
View File

@ -1,14 +1,16 @@
module gitea.com/jolheiser/imp
module go.jolheiser.com/imp
go 1.18
require (
gitea.com/jolheiser/globber v0.0.1
github.com/gobuffalo/here v0.6.6
github.com/matryer/is v1.4.0
mvdan.cc/gofumpt v0.5.0
)
require (
github.com/gobwas/glob v0.2.3 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
github.com/google/go-cmp v0.5.9 // indirect
golang.org/x/mod v0.10.0 // indirect
golang.org/x/tools v0.8.0 // indirect
)

38
go.sum
View File

@ -1,31 +1,19 @@
gitea.com/jolheiser/globber v0.0.1 h1:BVoc4Ml9N3ssix5Xy32gpQOO1jnAuzMsYc5h/LP7/jA=
gitea.com/jolheiser/globber v0.0.1/go.mod h1:vr1VkO/biaYgeGj8tRD6SMAWhsqINKFYl9en3YbpQvc=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/gobuffalo/here v0.6.6 h1:/o+jfSwe36pKQ577grsXGoMYql/zheiGwg1XFo3CBJU=
github.com/gobuffalo/here v0.6.6/go.mod h1:C4JZL5PsXWKzP/CAchaIzuUWlaae6CaAiMYQ0ieY62M=
github.com/frankban/quicktest v1.14.4 h1:g2rn0vABPOOXmZUj+vbmUp0lPoXEMuhTpIluN0XL9UY=
github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=
github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/matryer/is v1.4.0 h1:sosSmIWwkYITGrxZ25ULNDeKiMNzFSr4V/eqBQP0PeE=
github.com/matryer/is v1.4.0/go.mod h1:8I/i5uYgLzgsgEloJE1U6xx5HkBQpAZvepWuujKwMRU=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.7.1 h1:5TQK59W5E3v0r2duFAb7P95B6hEeOyEnHRa8MjYSMTY=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
golang.org/x/mod v0.10.0 h1:lFO9qtOdlre5W1jxS3r/4szv2/6iXxScdzjoBMXNhYk=
golang.org/x/mod v0.10.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU=
golang.org/x/tools v0.8.0 h1:vSDcovVPld282ceKgDimkRSC8kpaH1dgyc9UMzlt84Y=
golang.org/x/tools v0.8.0/go.mod h1:JxBZ99ISMI5ViVkT1tr6tdNmXeTrcpVSD3vZ1RsRdN4=
mvdan.cc/gofumpt v0.5.0 h1:0EQ+Z56k8tXjj/6TQD25BFNKQXpCvT0rnansIc7Ug5E=
mvdan.cc/gofumpt v0.5.0/go.mod h1:HBeVDtMKRZpXyxFciAirzdKklDlGu8aAy1wEbH5Y9js=

35
imp.go
View File

@ -9,18 +9,14 @@ import (
"path/filepath"
"strings"
"gitea.com/jolheiser/imp/format"
"go.jolheiser.com/imp/format"
"gitea.com/jolheiser/globber"
"github.com/gobuffalo/here"
gofumptFormat "mvdan.cc/gofumpt/format"
)
func runImp(root, ignore string, write bool) error {
info, err := here.Current()
if err != nil {
return err
}
module := info.Module.Path
func runImp(root, ignore string, write, gofumpt, gofumptExtra bool) error {
mod := modInfo(root)
globs, err := globber.ParseFile(ignore)
if err != nil {
if !errors.Is(err, fs.ErrNotExist) {
@ -48,8 +44,9 @@ func runImp(root, ignore string, write bool) error {
if err != nil {
return fmt.Errorf("could not read file %q: %w", walkPath, err)
}
formatted, err := format.Source(data, module)
if err != nil {
formatted, err := impFormat(data, mod, gofumpt, gofumptExtra)
if err != nil && !errors.Is(err, format.ErrNoImports) {
return fmt.Errorf("could not format file %q: %w", walkPath, err)
}
@ -73,6 +70,24 @@ func runImp(root, ignore string, write bool) error {
return nil
}
func impFormat(src []byte, mod module, gofumpt, gofumptExtra bool) ([]byte, error) {
formatted, err := format.Source(src, mod.Path)
if err != nil {
return src, err
}
if gofumpt {
formatted, err = gofumptFormat.Source(formatted, gofumptFormat.Options{
LangVersion: mod.GoVersion,
ModulePath: mod.Path,
ExtraRules: gofumptExtra,
})
if err != nil {
return src, err
}
}
return formatted, nil
}
func checkSkip(walkPath string, walkInfo os.FileInfo, globs *globber.GlobSet) walkStatus {
// Skip current directory
if strings.EqualFold(walkPath, ".") {

76
main.go
View File

@ -1,30 +1,96 @@
package main
import (
"encoding/json"
"flag"
"fmt"
"io"
"os"
"os/exec"
)
var Version = "develop"
func main() {
if err := mainErr(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func mainErr() error {
fs := flag.NewFlagSet("imp", flag.ExitOnError)
writeFlag := fs.Bool("write", false, "Write the re-ordered imports instead of just printing them")
fs.BoolVar(writeFlag, "w", *writeFlag, "--write")
ignoreFlag := fs.String("ignore", ".impignore", "Path to .impignore file")
fs.StringVar(ignoreFlag, "i", *ignoreFlag, "--ignore")
gofumptFlag := fs.Bool("gofumpt", false, "Also format using gofumpt")
gofumptExtraFlag := fs.Bool("gofumpt-extra", false, "Also use extra rules with gofumpt")
stdinFlag := fs.Bool("stdin", false, "Format stdin")
if err := fs.Parse(os.Args[1:]); err != nil {
fmt.Println(err)
return err
}
root := "."
cwd, err := os.Getwd()
if err != nil {
return err
}
if *stdinFlag {
mod := modInfo(cwd)
src, err := io.ReadAll(os.Stdin)
if err != nil {
return err
}
formatted, err := impFormat(src, mod, *gofumptFlag, *gofumptExtraFlag)
if err != nil {
return err
}
fmt.Print(string(formatted))
return nil
}
root := cwd
if fs.NArg() > 0 {
root = fs.Arg(0)
}
if err := runImp(root, *ignoreFlag, *writeFlag); err != nil {
fmt.Println(err)
}
return runImp(root, *ignoreFlag, *writeFlag, *gofumptFlag, *gofumptExtraFlag)
}
type module struct {
Path string
GoVersion string
}
func (m *module) UnmarshalJSON(data []byte) error {
type mod struct {
Module struct {
Path string
}
Go string
}
var mo mod
if err := json.Unmarshal(data, &mo); err != nil {
return err
}
*m = module{
Path: mo.Module.Path,
GoVersion: mo.Go,
}
return nil
}
func modInfo(dir string) module {
cmd := exec.Command("go", "mod", "edit", "--json")
cmd.Dir = dir
out, err := cmd.Output()
if err != nil {
return module{}
}
var m module
_ = json.Unmarshal(out, &m)
return m
}