Skip to content

Commit

Permalink
Add workflow, remove fixtures, improve Go mod
Browse files Browse the repository at this point in the history
  • Loading branch information
Reinier Kors committed Aug 26, 2020
1 parent 31ff4ff commit 6661452
Show file tree
Hide file tree
Showing 9 changed files with 187 additions and 95 deletions.
28 changes: 28 additions & 0 deletions .github/workflows/golangci-lint.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
name: golangci-lint
on:
push:
tags:
- v*
branches:
- master
pull_request:
jobs:
golangci:
name: lint
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: golangci-lint
uses: golangci/golangci-lint-action@v1
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.30

# Optional: working directory, useful for monorepos
# working-directory: somedir

# Optional: golangci-lint command line arguments.
# args: --issues-exit-code=0

# Optional: show only new issues if it's a pull request. The default value is `false`.
# only-new-issues: true
21 changes: 21 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
on:
release:
types: [created]

jobs:
releases-matrix:
name: Release Go Binary
runs-on: ubuntu-latest
strategy:
matrix:
goos: [linux, windows, darwin]
goarch: [amd64]
steps:
- uses: actions/checkout@v2
- uses: wangyoucao577/go-release-action@master
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
goos: ${{ matrix.goos }}
goarch: ${{ matrix.goarch }}
goversion: "https://golang.org/dl/go1.15.linux-amd64.tar.gz"
binary_name: "goimportssort"
18 changes: 18 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
on: [push, pull_request]
name: Test
jobs:
test:
strategy:
matrix:
go-version: [1.14.x, 1.15.x]
os: [ubuntu-latest, macos-latest, windows-latest]
runs-on: ${{ matrix.os }}
steps:
- name: Install Go
uses: actions/setup-go@v2
with:
go-version: ${{ matrix.go-version }}
- name: Checkout code
uses: actions/checkout@v2
- name: Test
run: go test ./...
13 changes: 7 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,22 @@ This tool aims to automatically fix the order of golang imports. It will split y

## Installation
```
$ go get github.com/AanZee/goimportssort
$ go get -u github.com/AanZee/goimportssort
```

## Usage
```
usage: goimportssort [flags] [path ...]
-l write results to stdout
-l write results to stdout (default false)
-local string
put imports beginning with this string after 3rd-party packages; comma-separated list
-v verbose logging
-w write result to (source) file instead of stdout
put imports beginning with this string after 3rd-party packages; comma-separated list
(default tries to get module name of current directory)
-v verbose logging (default false)
-w write result to (source) file (default false)
```
Imports will be sorted according to their categories.
```
$ goimportssort -v -l --local "github.com/AanZee/goimportssort" example.go
$ goimportssort -v -w ./..
```

For example:
Expand Down
29 changes: 0 additions & 29 deletions _fixtures/sample2.txt

This file was deleted.

30 changes: 0 additions & 30 deletions _fixtures/sample3.txt

This file was deleted.

1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,6 @@ go 1.14
require (
github.com/dave/dst v0.23.1
github.com/stretchr/testify v1.5.1
golang.org/x/mod v0.2.0
golang.org/x/tools v0.0.0-20200326210457-5d86d385bf88
)
60 changes: 34 additions & 26 deletions goimportssort.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
/*
goimportssort sorts your Go import lines in three categories: inbuilt, external and local.
$ go get github.com/AanZee/goimportssort
Happy hacking!
$ go get -u github.com/AanZee/goimportssort
*/
package main

Expand All @@ -12,37 +11,38 @@ import (
"fmt"
"go/parser"
"go/token"
"golang.org/x/tools/go/packages"
"io"
"io/ioutil"
"log"
"os"
"os/exec"
"path/filepath"
"runtime"
"sort"
"strings"

"golang.org/x/mod/modfile"
"golang.org/x/tools/go/packages"

"github.com/dave/dst"
"github.com/dave/dst/decorator"
"github.com/dave/dst/dstutil"
)

var (
list = flag.Bool("l", false, "write results to stdout")
write = flag.Bool("w", false, "write result to (source) file instead of stdout")
localPrefix = flag.String("local", "", "put imports beginning with this string after 3rd-party packages; comma-separated list")
verbose bool // verbose logging
list = flag.Bool("l", false, "write results to stdout")
write = flag.Bool("w", false, "write result to (source) file instead of stdout")
localPrefix = flag.String("local", "", "put imports beginning with this string after 3rd-party packages; comma-separated list")
verbose bool // verbose logging
standardPackages = make(map[string]struct{})
)

// ImpModel is used for storing import information
// impModel is used for storing import information
type impModel struct {
path string
localReference string
}

// String is used to get a string representation of an import
// string is used to get a string representation of an import
func (m impModel) string() string {
if m.localReference == "" {
return m.path
Expand Down Expand Up @@ -79,7 +79,7 @@ func goImportsSortMain() error {
if *localPrefix == "" {
log.Println("no prefix found, using module name")

moduleName, _ := getModuleName()
moduleName := getModuleName()
if moduleName != "" {
localPrefix = &moduleName
} else {
Expand Down Expand Up @@ -218,8 +218,8 @@ func process(src []byte) (output []byte, err error) {
func replaceImports(newImports []byte, node *dst.File) ([]byte, error) {
var (
output []byte
err error
buf bytes.Buffer
err error
buf bytes.Buffer
)

// remove + update
Expand All @@ -239,8 +239,7 @@ func replaceImports(newImports []byte, node *dst.File) ([]byte, error) {
packageName := node.Name.Name
output = bytes.Replace(buf.Bytes(), []byte("package "+packageName), append([]byte("package "+packageName+"\n\n"), newImports...), 1)
} else {
fmt.Println("err not nil:")
fmt.Println(err)
log.Println(err)
}

return output, err
Expand Down Expand Up @@ -332,22 +331,31 @@ func isStandardPackage(pkg string) bool {
return ok
}

func getRootPath() (string, error) {
_, b, _, ok := runtime.Caller(0)
if !ok {
return "", errors.New("could not get root directory")
}
basepath := filepath.Dir(b)

return basepath, nil
}

// getModuleName parses the GOMOD name
func getModuleName() (string, error) {
gomodCmd := exec.Command("go", "env", "GOMOD") // TODO: Check if there's a better way to get GOMOD
gomod, err := gomodCmd.Output()
func getModuleName() string {
root, err := getRootPath()
if err != nil {
log.Println("could not run: go env GOMOD")
return "", err
log.Println("error when getting root path: ", err)
return ""
}
gomodStr := strings.TrimSpace(string(gomod))

moduleCmd := exec.Command("awk", "/module/ {print $2}", gomodStr) // TODO: Check if there's a better way
module, err := moduleCmd.Output()
goModBytes, err := ioutil.ReadFile(filepath.Join(root, "go.mod"))
if err != nil {
return "", err
log.Println("error when reading mod file: ", err)
return ""
}
moduleStr := strings.TrimSpace(string(module))

return moduleStr, nil
modName := modfile.ModulePath(goModBytes)

return modName
}
Loading

0 comments on commit 6661452

Please sign in to comment.