获取 npm 命令,我们使用 Golang 标准库自带的 exec.LookPath 来查找。如果查找到了,就接着使用 exec.Command 来运行 npm run build,并且将输出 cmd.CombinedOutput,输出到控制台中;如果查找不到,就打印出错误信息。
package main
import "gobrief/cmd"
func main() {
cmd.Execute()
}
package cmd
import (
"fmt"
"github.com/spf13/cobra"
"os"
)
// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "go-brief",
Short: "go-brief [command]",
Long: "Please go-brief run",
// Uncomment the following line if your bare application
// has an action associated with it:
// Run: func(cmd *cobra.Command, args []string) { },
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("this is test run function")
if len(args) == 0 {
_ = cmd.Help()
return
}
},
}
// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
// 打印前端的命令
var buildFrontendCommand = &cobra.Command{
Use: "frontend",
Short: "使用npm编译前端",
RunE: func(c *cobra.Command, args []string) error {
// 获取path路径下的npm命令
path, err := exec.LookPath("npm")
if err != nil {
log.Fatalln("请安装npm在你的PATH路径下")
}
// 执行npm run build
cmd := exec.Command(path, "run", "build")
// 将输出保存在out中
out, err := cmd.CombinedOutput()
if err != nil {
fmt.Println("============= 前端编译失败 ============")
fmt.Println(string(out))
fmt.Println("============= 前端编译失败 ============")
return err
}
// 打印输出
fmt.Print(string(out))
fmt.Println("============= 前端编译成功 ============")
return nil
},
}
package console
import (
"github.com/gohade/hade/app/console/command/demo"
"github.com/gohade/hade/framework"
"github.com/gohade/hade/framework/cobra"
"github.com/gohade/hade/framework/command"
)
// RunCommand 初始化根Command并运行
func RunCommand(container framework.Container) error {
// 根Command
var rootCmd = &cobra.Command{
// 定义根命令的关键字
Use: "hade",
// 简短介绍
Short: "hade 命令",
// 根命令的详细介绍
Long: "hade 框架提供的命令行工具,使用这个命令行工具能很方便执行框架自带命令,也能很方便编写业务命令",
// 根命令的执行函数
RunE: func(cmd *cobra.Command, args []string) error {
cmd.InitDefaultHelpFlag()
return cmd.Help()
},
// 不需要出现cobra默认的completion子命令
CompletionOptions: cobra.CompletionOptions{DisableDefaultCmd: true},
}
// 为根Command设置服务容器
rootCmd.SetContainer(container)
// 绑定框架的命令
command.AddKernelCommands(rootCmd)
// 绑定业务的命令
AddAppCommand(rootCmd)
// 执行RootCommand
return rootCmd.Execute()
}
// 绑定业务的命令
func AddAppCommand(rootCmd *cobra.Command) {
rootCmd.AddCommand(demo.FooCommand)
// 每秒调用一次Foo命令
//rootCmd.AddCronCommand("* * * * * *", demo.FooCommand)
// 启动一个分布式任务调度,调度的服务名称为init_func_for_test,每个节点每5s调用一次Foo命令,抢占到了调度任务的节点将抢占锁持续挂载2s才释放
//rootCmd.AddDistributedCronCommand("foo_func_for_test", "*/5 * * * * *", demo.FooCommand, 2*time.Second)
}