framework1/framework/command/build.go

109 lines
2.5 KiB
Go
Raw Normal View History

2024-10-22 17:06:36 +08:00
package command
import (
"fmt"
"github.com/Superdanda/hade/framework/cobra"
2024-10-24 23:03:15 +08:00
"github.com/Superdanda/hade/framework/contract"
2024-10-22 17:06:36 +08:00
"log"
"os/exec"
"runtime"
)
func initBuildCommand() *cobra.Command {
buildCommand.AddCommand(buildSelfCommand)
buildCommand.AddCommand(buildBackendCommand)
buildCommand.AddCommand(buildFrontendCommand)
buildCommand.AddCommand(buildAllCommand)
return buildCommand
}
var buildSelfCommand = &cobra.Command{
Use: "self",
Short: "编译hade命令",
RunE: func(c *cobra.Command, args []string) error {
2024-10-24 23:03:15 +08:00
container := c.GetContainer()
config := container.MustMake(contract.ConfigKey).(contract.Config)
2024-10-22 17:06:36 +08:00
path, err := exec.LookPath("go")
if err != nil {
log.Fatalln("hade go: 请在Path路径中先安装go")
}
// 根据系统设置输出文件名
2024-10-24 23:03:15 +08:00
output := config.GetAppName()
2024-10-23 12:52:17 +08:00
env := []string{}
2024-10-22 17:06:36 +08:00
if runtime.GOOS == "windows" {
output += ".exe"
2024-10-23 12:52:17 +08:00
//env = append(env, "GOOS=windows", "GOARCH=amd64")
2024-10-22 17:06:36 +08:00
}
// 构建命令,设置环境变量
2024-10-23 12:52:17 +08:00
cmd := exec.Command(path, "build", "-o", output, "./")
cmd.Env = append(cmd.Env, env...) // 追加环境变量
2024-10-22 17:06:36 +08:00
// 执行编译命令并获取输出
out, err := cmd.CombinedOutput()
if err != nil {
fmt.Println("go build error:")
fmt.Println(string(out))
fmt.Println("--------------")
return err
}
fmt.Println(string(out))
2024-10-24 23:03:15 +08:00
fmt.Println("编译" + output + "项目成功")
2024-10-22 17:06:36 +08:00
return nil
},
}
2024-10-23 12:52:17 +08:00
var buildBackendCommand = &cobra.Command{
Use: "backend",
Short: "使用go编译后端",
RunE: func(c *cobra.Command, args []string) error {
return buildSelfCommand.RunE(c, args)
},
}
2024-10-22 17:06:36 +08:00
var buildCommand = &cobra.Command{
Use: "build",
Short: "编译相关命令",
RunE: func(c *cobra.Command, args []string) error {
if len(args) == 0 {
c.Help()
}
return nil
},
}
var buildFrontendCommand = &cobra.Command{
Use: "frontend",
Short: "使用npm编译前端",
RunE: func(c *cobra.Command, args []string) error {
err := npmCommand.RunE(c, []string{"run", "build"})
if err != nil {
fmt.Println("============= 前端编译失败 ============")
return err
}
fmt.Println("============= 前端编译成功 ============")
return nil
},
}
var buildAllCommand = &cobra.Command{
Use: "all",
Short: "同时编译前后端",
RunE: func(c *cobra.Command, args []string) error {
fmt.Println("============= 开始编译前后端 ============")
err := buildFrontendCommand.RunE(c, args)
if err != nil {
return err
}
err = buildBackendCommand.RunE(c, args)
if err != nil {
return err
}
return nil
},
}