golang实现Cobra命令闭环应用与oh-my-posh提示插件库console的使用
Golang实现Cobra命令闭环应用与oh-my-posh提示插件库console的使用
Console简介
Console是一个基于Cobra命令和readline shell构建的全功能控制台应用库。它提供现代用户界面,同时让开发者能专注于核心命令的开发。
主要特性
菜单与命令
- 绑定Cobra命令提供核心功能
- 多菜单系统,每个菜单有独立的命令树、提示引擎和特殊处理程序
- 可以自由修改所有Cobra设置
- 为每个菜单绑定特殊中断错误(如CtrlC/CtrlD)的处理程序
Shell接口
- 基于readline实例的Shell,支持完整inputrc配置和扩展功能
- 可配置的键绑定、命令和选项,提供合理的默认值
- 开箱即用的高级命令、标志和参数补全
- 命令语法高亮
其他功能
- 支持任意数量的历史记录源(每个菜单独立)
- 支持oh-my-posh提示,每个菜单可使用不同的配置文件
- 提供一组现成的命令(readline绑定/选项操作)
完整示例Demo
下面是一个使用Cobra和oh-my-posh的完整示例:
package main
import (
"fmt"
"os"
"github.com/reeflective/console"
"github.com/reeflective/console/example/commands"
"github.com/spf13/cobra"
)
func main() {
// 创建一个新的控制台实例
app := console.New("demo-app")
// 设置根命令
rootCmd := &cobra.Command{
Use: "demo",
Short: "Demo application with Cobra and oh-my-posh",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Welcome to the demo application!")
},
}
// 添加一些示例命令
rootCmd.AddCommand(commands.NewVersionCmd())
rootCmd.AddCommand(commands.NewEchoCmd())
// 将根命令绑定到控制台
app.ActiveMenu().SetRootCommand(rootCmd)
// 配置oh-my-posh提示
// 注意: 需要提前安装oh-my-posh并配置主题文件
app.ActiveMenu().SetPrompt(
console.PromptWithOMP("~/.poshthemes/mytheme.omp.json"),
console.PromptWithPrefix("demo-app"),
)
// 启动交互式控制台
if err := app.Start(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
命令示例
下面是一个更完整的命令实现示例:
package commands
import (
"fmt"
"github.com/spf13/cobra"
)
// NewVersionCmd 创建一个版本命令
func NewVersionCmd() *cobra.Command {
return &cobra.Command{
Use: "version",
Short: "Print the version number",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Demo App v1.0.0")
},
}
}
// NewEchoCmd 创建一个echo命令
func NewEchoCmd() *cobra.Command {
var repeat int
cmd := &cobra.Command{
Use: "echo [text]",
Short: "Echo the input text",
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
for i := 0; i < repeat; i++ {
fmt.Println(args[0])
}
},
}
cmd.Flags().IntVarP(&repeat, "repeat", "r", 1, "Number of times to repeat the text")
return cmd
}
使用oh-my-posh配置提示
要使用oh-my-posh提示,你需要:
- 安装oh-my-posh
- 下载或创建主题文件(.omp.json格式)
- 在控制台配置中指定主题文件路径
app.ActiveMenu().SetPrompt(
console.PromptWithOMP("/path/to/theme.omp.json"),
console.PromptWithPrefix("myapp"),
)
状态说明
该库目前处于预发布候选状态:
- 虽然简单小巧,但尚未经过大量测试
- 可能还有一些功能需要改进
- API已经相当稳定,未来版本不太可能有大的变化
欢迎提交PR或issue来改进项目,同时也欢迎其他贡献、bug修复和代码审查。
更多关于golang实现Cobra命令闭环应用与oh-my-posh提示插件库console的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html
更多关于golang实现Cobra命令闭环应用与oh-my-posh提示插件库console的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
Golang实现Cobra命令闭环应用与oh-my-posh提示插件
下面我将介绍如何使用Golang的Cobra库创建命令行应用,并结合oh-my-posh实现美观的命令行提示。
1. Cobra基础应用实现
首先创建一个基本的Cobra命令行应用:
package main
import (
"fmt"
"os"
"github.com/spf13/cobra"
)
var rootCmd = &cobra.Command{
Use: "myapp",
Short: "MyApp is a demo CLI application",
Long: `A longer description of my demo CLI application built with Cobra.`,
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Hello from MyApp!")
},
}
var versionCmd = &cobra.Command{
Use: "version",
Short: "Print the version number of MyApp",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("MyApp v1.0.0")
},
}
func init() {
rootCmd.AddCommand(versionCmd)
// 添加全局flag
rootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "", "config file (default is $HOME/.myapp.yaml)")
}
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func main() {
Execute()
}
2. 添加oh-my-posh集成
oh-my-posh是一个强大的命令行提示工具,我们可以通过以下方式在Go应用中集成它的主题:
import (
"os/exec"
"runtime"
)
func setupPrompt() {
// 检测oh-my-posh是否安装
_, err := exec.LookPath("oh-my-posh")
if err != nil {
fmt.Println("oh-my-posh not found. Please install it first.")
return
}
// 根据操作系统设置不同的提示主题
var theme string
switch runtime.GOOS {
case "windows":
theme = "jandedobbeleer.omp.json"
case "darwin", "linux":
theme = "agnoster.omp.json"
default:
theme = "default.omp.json"
}
// 设置提示
cmd := exec.Command("oh-my-posh", "--init", "--shell", "bash", "--config", theme)
err = cmd.Run()
if err != nil {
fmt.Printf("Failed to setup oh-my-posh: %v\n", err)
}
}
然后在main函数中调用:
func main() {
setupPrompt()
Execute()
}
3. 完整示例:带配置的Cobra应用
下面是一个更完整的示例,包含配置读取和oh-my-posh集成:
package main
import (
"fmt"
"log"
"os"
"os/exec"
"runtime"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var cfgFile string
type Config struct {
Theme string `mapstructure:"theme"`
Debug bool `mapstructure:"debug"`
Server struct {
Host string `mapstructure:"host"`
Port int `mapstructure:"port"`
} `mapstructure:"server"`
}
var appConfig Config
var rootCmd = &cobra.Command{
Use: "myapp",
Short: "MyApp with Cobra and oh-my-posh",
PersistentPreRun: func(cmd *cobra.Command, args []string) {
initConfig()
setupPrompt()
},
Run: func(cmd *cobra.Command, args []string) {
if appConfig.Debug {
log.Println("Debug mode enabled")
}
fmt.Printf("Server: %s:%d\n", appConfig.Server.Host, appConfig.Server.Port)
},
}
func initConfig() {
if cfgFile != "" {
viper.SetConfigFile(cfgFile)
} else {
home, err := os.UserHomeDir()
cobra.CheckErr(err)
viper.AddConfigPath(home)
viper.AddConfigPath(".")
viper.SetConfigType("yaml")
viper.SetConfigName(".myapp")
}
viper.AutomaticEnv()
if err := viper.ReadInConfig(); err == nil {
fmt.Println("Using config file:", viper.ConfigFileUsed())
}
if err := viper.Unmarshal(&appConfig); err != nil {
log.Fatalf("Unable to decode config, %v", err)
}
}
func setupPrompt() {
if _, err := exec.LookPath("oh-my-posh"); err != nil {
log.Println("oh-my-posh not found. Skipping prompt setup.")
return
}
theme := appConfig.Theme
if theme == "" {
switch runtime.GOOS {
case "windows":
theme = "jandedobbeleer.omp.json"
default:
theme = "agnoster.omp.json"
}
}
cmd := exec.Command("oh-my-posh", "--init", "--shell", "bash", "--config", theme)
if err := cmd.Run(); err != nil {
log.Printf("Failed to setup oh-my-posh: %v\n", err)
}
}
func main() {
rootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "", "config file (default is $HOME/.myapp.yaml)")
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
4. 配置示例
创建配置文件 ~/.myapp.yaml
:
theme: "powerlevel10k_rainbow.omp.json"
debug: true
server:
host: "localhost"
port: 8080
5. 构建与使用
- 安装依赖:
go get github.com/spf13/cobra
go get github.com/spf13/viper
- 构建应用:
go build -o myapp
- 运行应用:
./myapp --config ~/.myapp.yaml
总结
通过Cobra我们可以创建功能强大的命令行应用,而oh-my-posh则为终端提供了美观的提示。两者的结合可以提升开发者的命令行体验。在实际项目中,你可以根据需要添加更多命令和功能,以及定制更适合自己工作流的oh-my-posh主题。