This repository has been archived on 2023-11-08. You can view files and clone it, but cannot push or open issues/pull-requests.
imp/main.go

97 lines
1.8 KiB
Go

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 {
return err
}
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)
}
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
}