gofimports/internal/cli/action.go

55 lines
989 B
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"
2022-11-24 17:21:59 +00:00
"github.com/haunt98/gofimports/internal/imports"
2022-11-24 16:11:15 +00:00
"github.com/urfave/cli/v2"
)
type action struct {
flags struct {
list bool
write bool
diff bool
}
}
func (a *action) RunHelp(c *cli.Context) error {
return cli.ShowAppHelp(c)
}
func (a *action) getFlags(c *cli.Context) {
a.flags.list = c.Bool(flagListName)
a.flags.write = c.Bool(flagWriteName)
a.flags.diff = c.Bool(flagDiffName)
}
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)
}
2022-11-24 17:21:59 +00:00
f := imports.NewFormmater(
imports.FormatterWithList(a.flags.list),
imports.FormatterWithWrite(a.flags.write),
imports.FormatterWithDiff(a.flags.diff),
)
if err := f.Format(c.Args().Slice()...); err != nil {
return fmt.Errorf("imports formatter: failed to format %v: %w", c.Args().Slice(), err)
}
2022-11-24 17:10:14 +00:00
2022-11-24 16:11:15 +00:00
return nil
}