gofimports/internal/cli/action.go

104 lines
2.2 KiB
Go
Raw Normal View History

2022-11-24 16:11:15 +00:00
package cli
import (
2022-11-24 17:10:14 +00:00
"fmt"
2023-01-17 11:10:07 +00:00
"os"
"runtime"
"runtime/pprof"
2022-11-24 17:10:14 +00:00
2022-11-24 16:11:15 +00:00
"github.com/urfave/cli/v2"
"github.com/haunt98/gofimports/internal/imports"
2022-11-24 16:11:15 +00:00
)
type action struct {
flags struct {
companyPrefix string
list bool
write bool
diff bool
verbose bool
2023-01-17 11:10:07 +00:00
profiler bool
stock bool
2022-11-24 16:11:15 +00:00
}
}
func (a *action) RunHelp(c *cli.Context) error {
return cli.ShowAppHelp(c)
}
func (a *action) getFlags(c *cli.Context) {
2023-01-17 11:10:07 +00:00
a.flags.companyPrefix = c.String(flagCompanyPrefixName)
2022-11-24 16:11:15 +00:00
a.flags.list = c.Bool(flagListName)
a.flags.write = c.Bool(flagWriteName)
a.flags.diff = c.Bool(flagDiffName)
a.flags.verbose = c.Bool(flagVerboseName)
2023-01-17 11:10:07 +00:00
a.flags.profiler = c.Bool(flagProfilerName)
a.flags.stock = c.Bool(flagStockName)
2023-01-17 09:09:35 +00:00
if a.flags.verbose {
fmt.Printf("flags: %+v\n", a.flags)
}
2022-11-24 16:11:15 +00:00
}
func (a *action) Run(c *cli.Context) error {
a.getFlags(c)
2022-11-24 17:10:14 +00:00
// No flag is set
if !a.flags.list &&
!a.flags.write &&
2022-11-24 16:11:15 +00:00
!a.flags.diff {
2022-11-24 17:10:14 +00:00
return a.RunHelp(c)
2022-11-24 16:11:15 +00:00
}
2022-11-24 17:40:00 +00:00
// Empty args
if c.Args().Len() == 0 {
return a.RunHelp(c)
}
2023-01-17 11:10:07 +00:00
if a.flags.profiler {
2023-01-17 11:17:28 +00:00
f, err := os.Create("cpu.prof")
2023-01-17 11:10:07 +00:00
if err != nil {
return fmt.Errorf("os: failed to create: %w", err)
}
defer f.Close()
if err := pprof.StartCPUProfile(f); err != nil {
return fmt.Errorf("pprof: failed to start cpu profile: %w", err)
}
defer pprof.StopCPUProfile()
}
ft, err := imports.NewFormmater(
2022-11-24 17:21:59 +00:00
imports.FormatterWithList(a.flags.list),
imports.FormatterWithWrite(a.flags.write),
imports.FormatterWithDiff(a.flags.diff),
imports.FormatterWithVerbose(a.flags.verbose),
imports.FormatterWithCompanyPrefix(a.flags.companyPrefix),
imports.FormatterWithStock(a.flags.stock),
2022-11-24 17:21:59 +00:00
)
if err != nil {
return fmt.Errorf("imports: failed to new formatter: %w", err)
}
2022-11-24 17:21:59 +00:00
args := c.Args().Slice()
if err := ft.Format(args...); err != nil {
return fmt.Errorf("imports formatter: failed to format %v: %w", args, err)
2022-11-24 17:21:59 +00:00
}
2022-11-24 17:10:14 +00:00
2023-01-17 11:10:07 +00:00
if a.flags.profiler {
2023-01-17 11:17:28 +00:00
f, err := os.Create("mem.prof")
2023-01-17 11:10:07 +00:00
if err != nil {
return fmt.Errorf("os: failed to create: %w", err)
}
defer f.Close()
runtime.GC()
if err := pprof.WriteHeapProfile(f); err != nil {
return fmt.Errorf("pprof: failed to write heap profile: %w", err)
}
}
2022-11-24 16:11:15 +00:00
return nil
}