This commit is contained in:
Rogee
2024-12-21 11:33:32 +08:00
parent f232f7cdff
commit f7504d57f9
3 changed files with 51 additions and 2 deletions

47
cmd/fmt.go Normal file
View File

@@ -0,0 +1,47 @@
package cmd
import (
"fmt"
"os"
"os/exec"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
func CommandFmt(root *cobra.Command) {
cmd := &cobra.Command{
Use: "fmt",
Short: "fmt codes",
RunE: commandFmtE,
}
root.AddCommand(cmd)
}
func commandFmtE(cmd *cobra.Command, args []string) error {
log.Info("开始格式化代码")
if _, err := exec.LookPath("gofumpt"); err != nil {
log.Info("gofumpt 不存在,正在安装...")
installCmd := exec.Command("go", "install", "mvdan.cc/gofumpt@latest")
installCmd.Stdout = os.Stdout
installCmd.Stderr = os.Stderr
if err := installCmd.Run(); err != nil {
return fmt.Errorf("安装 gofumpt 失败: %v", err)
}
if _, err := exec.LookPath("gofumpt"); err != nil {
return fmt.Errorf("gofumpt 已经安装,但是执行失败")
}
}
log.Info("运行 gofumpt...")
gofumptCmd := exec.Command("gofumpt", "-l", "-extra", "-w", ".")
gofumptCmd.Stdout = os.Stdout
gofumptCmd.Stderr = os.Stderr
if err := gofumptCmd.Run(); err != nil {
return fmt.Errorf("运行 gofumpt 失败: %v", err)
}
log.Info("格式化代码完成")
return nil
}

View File

@@ -4,8 +4,9 @@ import "github.com/spf13/cobra"
func CommandGen(root *cobra.Command) { func CommandGen(root *cobra.Command) {
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "gen", Use: "gen",
Short: "Generate code", Short: "Generate code",
PersistentPostRunE: commandFmtE,
} }
cmd.PersistentFlags().StringP("config", "c", "config.toml", "database config file") cmd.PersistentFlags().StringP("config", "c", "config.toml", "database config file")

View File

@@ -17,6 +17,7 @@ func main() {
cmd.CommandMigrate, cmd.CommandMigrate,
cmd.CommandGen, cmd.CommandGen,
cmd.CommandSwag, cmd.CommandSwag,
cmd.CommandFmt,
} }
for _, c := range cmds { for _, c := range cmds {