获取 npm 命令,我们使用 Golang 标准库自带的 exec.LookPath 来查找。如果查找到了,就接着使用 exec.Command 来运行 npm run build,并且将输出 cmd.CombinedOutput,输出到控制台中;如果查找不到,就打印出错误信息。
package mainimport "gobrief/cmd"func main() {cmd.Execute()}
package cmdimport ("fmt""github.com/spf13/cobra""os")// rootCmd represents the base command when called without any subcommandsvar 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 buildcmd := 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 consoleimport ("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 {// 根Commandvar 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)// 执行RootCommandreturn 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)}
