Skip to content

Commit

Permalink
Merge pull request #25 from metal3d/develop
Browse files Browse the repository at this point in the history
Refactorization, fixes, adaptations...

fixes constructors that can not be ordered
remove deprecated ioutil
fixes error messages
  • Loading branch information
metal3d authored May 7, 2024
2 parents a84165a + 191fa7e commit f14db9a
Show file tree
Hide file tree
Showing 13 changed files with 131 additions and 1,806 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/go.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ jobs:
- name: Set up Go
uses: actions/setup-go@v3
with:
go-version: 1.18
go-version: 1.21

- name: Build
run: go build -v ./...
Expand Down
31 changes: 14 additions & 17 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -142,23 +142,20 @@ The released binaries are signed with GPG. If you want to verify that the releas
```bash
## Optional, you can get and trust the owner GPG key
# this is the repo owner key:
_KEY="F3702E3FAD8F76DC"
# You can get it with this command:
_KEY=$(curl -s https://api.github.com/users/metal3d/gpg_keys | \
awk -F'"' '/"key_id"/{print $4; exit}')
echo ${_KEY}
# you can import the repository owner key from keyserver
gpg --keyserver hkps://keys.openpgp.org/ --recv-keys ${_KEY}
# optoinal, trust owner key
_FPR=$(gpg -k --with-colons --fingerprint "${_KEY}" | awk -F: '/fpr/{print $10; exit}')
echo ${_FPR}:6: | gpg --import-ownertrust
unset _KEY _FPR
## Verification
# get the signature of the right binary
# import the key from github
# install jq before (apt install -y jq, dnf install -y jq, ...)
gpg --import <(curl -s https://api.github.com/users/metal3d/gpg_keys | jq -r '.[0].raw_key')
# or use keyserver
_KEY="483493B2DD0845DA8F21A26DF3702E3FAD8F76DC"
gpg --keyserver hkps://keys.openpgp.org/ --recv-keys ${_KEY~15}
## optional, trust owner key
_KEY="483493B2DD0845DA8F21A26DF3702E3FAD8F76DC"
echo ${_KEY}:6: | gpg --import-ownertrust
## Binary signature verification
# get the signature file (.asc) of the right binary
_REL="goreorder-linux-amd64"
_SIGNURL=https://github.com/metal3d/goreorder/releases/download/${_REL}.asc
curl ${_SIGNURL} -o /tmp/goreorder.asc
Expand Down
14 changes: 7 additions & 7 deletions cmd/goreorder/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,11 @@ import (
"path/filepath"
"strings"

logger "github.com/metal3d/goreorder/log"
"github.com/metal3d/goreorder/ordering"
"github.com/spf13/cobra"
"github.com/spf13/viper"

logger "github.com/metal3d/goreorder/log"
"github.com/metal3d/goreorder/ordering"
)

var (
Expand Down Expand Up @@ -89,7 +90,7 @@ to write to the file, use the -write flag.`
return initializeViper(cmd, args...)
},
RunE: func(cmd *cobra.Command, args []string) error {
return fmt.Errorf("You need to specify a command or an option")
return fmt.Errorf("you need to specify a command or an option")
},
}

Expand Down Expand Up @@ -129,10 +130,9 @@ func buildReorderCommand(config *ReorderConfig) *cobra.Command {
Use: "reorder [flags] [file.go|directory|stdin]",
Short: "Reorder vars, consts, stucts/types/interaces, methods/functions and constructors in a Go source file.",
RunE: func(cmd *cobra.Command, args []string) error {

stat, _ := os.Stdin.Stat()
if len(args) == 0 && (stat.Mode()&os.ModeCharDevice) != 0 {
return errors.New("You should provide a file or a directory or stream content to stdin.")
return errors.New("you should provide a file or a directory or stream content to stdin")
}

// validate order flags
Expand All @@ -148,13 +148,13 @@ func buildReorderCommand(config *ReorderConfig) *cobra.Command {
}
}
if !found {
return fmt.Errorf("Invalid order name %v, valid order name are %v", v, ordering.DefaultOrder)
return fmt.Errorf("invalid order name %v, valid order name are %v", v, ordering.DefaultOrder)
}
}
}
// only allow gofmt or goimports
if config.FormatToolName != "gofmt" && config.FormatToolName != "goimports" {
return fmt.Errorf("Only gofmt or goimports are allowed")
return fmt.Errorf("only gofmt or goimports are allowed")
}

// check if the executable exists
Expand Down
3 changes: 1 addition & 2 deletions cmd/goreorder/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,13 +46,12 @@ func bindFlags(cmd *cobra.Command, v *viper.Viper) {
cmd.Flags().VisitAll(func(f *pflag.Flag) {
name := f.Name
if !f.Changed && v.IsSet(name) {
val := v.Get(name)
// ensure that the value is with the correct type
switch f.Value.Type() {
case "stringSlice":
cmd.Flags().Lookup(name).Value.Set(strings.Join(v.GetStringSlice(name), ","))
default:
val = v.GetString(name)
val := v.GetString(name)
cmd.Flags().Set(name, fmt.Sprintf("%v", val))
}
}
Expand Down
8 changes: 4 additions & 4 deletions cmd/goreorder/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ package main

import (
"bytes"
"io/ioutil"
"os"
"testing"

"github.com/metal3d/goreorder/ordering"
"gopkg.in/yaml.v3"

"github.com/metal3d/goreorder/ordering"
)

func init() {
Expand Down Expand Up @@ -79,13 +79,13 @@ order:
t.Fatal(err)
}
defer os.Chdir(currentDir)
tmpDir, err := ioutil.TempDir("", "goreorder-test")
tmpDir, err := os.MkdirTemp("", "goreorder-test")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpDir)
os.Chdir(tmpDir)
err = ioutil.WriteFile(".goreorder", []byte(yamlFile), 0644)
err = os.WriteFile(".goreorder", []byte(yamlFile), 0644)
if err != nil {
t.Fatal(err)
}
Expand Down
28 changes: 13 additions & 15 deletions cmd/goreorder/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
Expand All @@ -27,11 +26,11 @@ func main() {
// ReorderConfig is the configuration for the reorder command
type ReorderConfig struct {
FormatToolName string `yaml:"format"`
DefOrder []string `yaml:"order"`
Write bool `yaml:"write"`
Verbose bool `yaml:"verbose"`
ReorderTypes bool `yaml:"reorder-types"`
MakeDiff bool `yaml:"diff"`
DefOrder []string `yaml:"order"`
}

func reorder(config *ReorderConfig, args ...string) error {
Expand All @@ -43,9 +42,9 @@ func reorder(config *ReorderConfig, args ...string) error {
stat, _ := os.Stdin.Stat()
if (stat.Mode() & os.ModeCharDevice) == 0 {
// read from stdin
input, err = ioutil.ReadAll(os.Stdin)
input, err = io.ReadAll(os.Stdin)
if err != nil {
return fmt.Errorf("Error while reading stdin: %w", err)
return fmt.Errorf("error while reading stdin: %w", err)
}
filename = "stdin.go"
config.Write = false
Expand All @@ -54,11 +53,11 @@ func reorder(config *ReorderConfig, args ...string) error {
// read from file or directory
filename = args[0]
if filename == "" {
return fmt.Errorf("Filename is empty")
return fmt.Errorf("filename is empty")
}
_, err := os.Stat(filename)
if err != nil {
return fmt.Errorf("Error while getting file stat: %w", err)
return fmt.Errorf("error while getting file stat: %w", err)
}
}

Expand All @@ -70,7 +69,7 @@ func processFile(fileOrDirectoryName string, input []byte, config *ReorderConfig
return fmt.Errorf("Skipping test file: " + fileOrDirectoryName)
}

if input != nil && len(input) != 0 {
if len(input) != 0 {
// process stdin
content, err := ordering.ReorderSource(ordering.ReorderConfig{
Filename: fileOrDirectoryName,
Expand All @@ -80,26 +79,26 @@ func processFile(fileOrDirectoryName string, input []byte, config *ReorderConfig
Src: input,
})
if err != nil {
return fmt.Errorf("Error while reordering source: %w", err)
return fmt.Errorf("error while reordering source: %w", err)
}
fmt.Print(string(content))
return nil
}

stat, err := os.Stat(fileOrDirectoryName)
if err != nil {
return fmt.Errorf("Error while getting file stat: %w", err)
return fmt.Errorf("error while getting file stat: %w", err)
}
if stat.IsDir() {
// skip vendor directory
if strings.HasSuffix(fileOrDirectoryName, "vendor") {
return fmt.Errorf("Skipping vendor directory: " + fileOrDirectoryName)
return fmt.Errorf("skipping vendor directory: " + fileOrDirectoryName)
}
// get all files in directory and process them
log.Println("Processing directory: " + fileOrDirectoryName)
return filepath.Walk(fileOrDirectoryName, func(path string, info os.FileInfo, err error) error {
if err != nil {
return fmt.Errorf("Error while walking directory: %w", err)
return fmt.Errorf("error while walking directory: %w", err)
}
if strings.HasSuffix(path, ".go") {
processFile(path, nil, config)
Expand All @@ -118,15 +117,14 @@ func processFile(fileOrDirectoryName string, input []byte, config *ReorderConfig
Src: input,
})
if err != nil {
return fmt.Errorf("Error while reordering file: %w", err)
return fmt.Errorf("error while reordering file: %w", err)
}
if config.Write {
err = ioutil.WriteFile(fileOrDirectoryName, []byte(output), 0644)
err = os.WriteFile(fileOrDirectoryName, []byte(output), 0644)
if err != nil {
return fmt.Errorf("Error while writing to file: %w", err)
return fmt.Errorf("error while writing to file: %w", err)
}
} else {
//fmt.Println(output)
io.Copy(defaultOutpout, bytes.NewBufferString(output))
}
return nil
Expand Down
19 changes: 9 additions & 10 deletions cmd/goreorder/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package main

import (
"bytes"
"io/ioutil"
"os"
"path/filepath"
"testing"
Expand Down Expand Up @@ -45,7 +44,7 @@ func main() {}`)
cmd := buildMainCommand()
cmd.SetArgs([]string{"reorder", "--write", "./main.go"})
if err := cmd.Execute(); err != nil {
t.Error("Command error", err)
t.Error("command error", err)
}

// check file
Expand All @@ -68,7 +67,7 @@ func TestWithDir(t *testing.T) {
t.Fatal(err)
}
defer os.Chdir(currentDir)
tmpDir, err := ioutil.TempDir("", "goreorder-test")
tmpDir, err := os.MkdirTemp("", "goreorder-test")
if err != nil {
t.Fatal(err)
}
Expand Down Expand Up @@ -118,7 +117,7 @@ func TestHelp(t *testing.T) {
cmd := buildMainCommand()
cmd.SetArgs([]string{"--help"})
if err := cmd.Execute(); err != nil {
t.Error("Command error", err)
t.Error("command error", err)
}

}
Expand All @@ -128,7 +127,7 @@ func TestVersion(t *testing.T) {
cmd := buildMainCommand()
cmd.SetArgs([]string{"--version"})
if err := cmd.Execute(); err != nil {
t.Error("Version Command error", err)
t.Error("version Command error", err)
}

}
Expand All @@ -138,7 +137,7 @@ func TestNoArgs(t *testing.T) {
// no arguments
cmd.SetArgs([]string{})
if err := cmd.Execute(); err == nil {
t.Error("An error should occur with no argument", err)
t.Error("an error should occur with no argument", err)
}
}

Expand All @@ -147,28 +146,28 @@ func TestCompletionCommands(t *testing.T) {
cmd := buildMainCommand()
cmd.SetArgs([]string{"completion", shell})
if err := cmd.Execute(); err != nil {
t.Error("Command error", err)
t.Error("command error", err)
}
}

// try bash with --bashv1
cmd := buildMainCommand()
cmd.SetArgs([]string{"completion", "bash", "--bashv1"})
if err := cmd.Execute(); err != nil {
t.Error("Command error", err)
t.Error("command error", err)
}

// with no shell
cmd = buildMainCommand()
cmd.SetArgs([]string{"completion"})
if err := cmd.Execute(); err == nil {
t.Error("An error should occur with no shell argument", err)
t.Error("an error should occur with no shell argument", err)
}

// and with a bad shell
cmd = buildMainCommand()
cmd.SetArgs([]string{"completion", "badshell"})
if err := cmd.Execute(); err == nil {
t.Error("An error should occur with a bad shell argument", err)
t.Error("an error should occur with a bad shell argument", err)
}
}
28 changes: 23 additions & 5 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,12 +1,30 @@
module github.com/metal3d/goreorder

go 1.16
go 1.21

require (
github.com/spf13/cobra v1.7.0
github.com/spf13/cobra v1.8.0
github.com/spf13/pflag v1.0.5
github.com/spf13/viper v1.16.0
golang.org/x/sys v0.9.0 // indirect
golang.org/x/text v0.10.0 // indirect
github.com/spf13/viper v1.18.2
gopkg.in/yaml.v3 v3.0.1
)

require (
github.com/fsnotify/fsnotify v1.7.0 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/magiconair/properties v1.8.7 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/pelletier/go-toml/v2 v2.2.2 // indirect
github.com/sagikazarmark/locafero v0.4.0 // indirect
github.com/sagikazarmark/slog-shim v0.1.0 // indirect
github.com/sourcegraph/conc v0.3.0 // indirect
github.com/spf13/afero v1.11.0 // indirect
github.com/spf13/cast v1.6.0 // indirect
github.com/subosito/gotenv v1.6.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842 // indirect
golang.org/x/sys v0.20.0 // indirect
golang.org/x/text v0.15.0 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
)
Loading

0 comments on commit f14db9a

Please sign in to comment.