cobra

Cobra 专家,Cobra 是用于构建现代 CLI 应用的流行 Go 库。帮助开发者创建带子命令、标志、参数验证、Shell 补全和帮助生成的命令行工具,适用于为类似 kubectl、Hugo、GitHub CLI 和 Docker 的工具提供动力的场景。

仓库最近推送
GitHub Stars
219
Forks
38
Issues / PRs
1

安装方式

先用 Prompt 核对来源与依赖。也可下载安装包。

用 AI 助手安装

复制提示词,让助手先核对固定版本和依赖。

查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "cobra":https://skillpi.com/zh/skills/deepskill-3e439666f84064c4c75a853e40d58731812eab253afa656e15027027085ccdb9。安装前核对上游来源和版本:https://github.com/TerminalSkills/skills。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。

来源与配置

github.com

配置方式待核实

请查看原始来源中的适用工具、依赖和权限要求。

安装实测待补充

Cobra 专家,Cobra 是用于构建现代 CLI 应用的流行 Go 库。帮助开发者创建带子命令、标志、参数验证、Shell 补全和帮助生成的命令行工具,适用于为类似 kubectl、Hugo、GitHub CLI 和 Docker 的工具提供动力的场景。

0 下载

介绍来源: third_party · TerminalSkills · 1.0.0 参考来源

SkillPi 解读

实测状态
未测试

文件浏览

在原站浏览文件 ↗

原始 SKILL.md

打开原文 ↗
Frontmatter
name: cobra
description: >-
  You are an expert in Cobra, the most popular Go library for building modern
  CLI applications. You help developers create command-line tools with
  subcommands, flags, argument validation, shell completions, and help
  generation — powering CLIs like kubectl, Hugo, GitHub CLI, and Docker.
license: Apache-2.0
compatibility: ''
metadata:
  author: terminal-skills
  version: 1.0.0
  category: Developer Tools
  tags:
    - go
    - cli
    - command-line
    - framework
    - flags
    - subcommands

Cobra — Go CLI Framework

You are an expert in Cobra, the most popular Go library for building modern CLI applications. You help developers create command-line tools with subcommands, flags, argument validation, shell completions, and help generation — powering CLIs like kubectl, Hugo, GitHub CLI, and Docker.

Core Capabilities

Application Structure

// cmd/root.go — Root command
package cmd

import (
    "fmt"
    "os"
    "github.com/spf13/cobra"
    "github.com/spf13/viper"
)

var cfgFile string
var verbose bool

var rootCmd = &cobra.Command{
    Use:   "myctl",
    Short: "My CLI tool for managing stuff",
    Long:  `A comprehensive CLI tool for managing deployments, configs, and services.`,
    PersistentPreRun: func(cmd *cobra.Command, args []string) {
        if verbose {
            fmt.Println("Verbose mode enabled")
        }
    },
}

func Execute() {
    if err := rootCmd.Execute(); err != nil {
        os.Exit(1)
    }
}

func init() {
    cobra.OnInitialize(initConfig)
    rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default $HOME/.myctl.yaml)")
    rootCmd.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "verbose output")
}

func initConfig() {
    if cfgFile != "" {
        viper.SetConfigFile(cfgFile)
    } else {
        home, _ := os.UserHomeDir()
        viper.AddConfigPath(home)
        viper.SetConfigName(".myctl")
    }
    viper.AutomaticEnv()
    viper.ReadInConfig()
}
// cmd/deploy.go — Subcommand with flags
package cmd

import (
    "fmt"
    "github.com/spf13/cobra"
)

var deployCmd = &cobra.Command{
    Use:   "deploy [service]",
    Short: "Deploy a service to the target environment",
    Long:  `Deploy a service to the specified environment with optional version override.`,
    Args:  cobra.ExactArgs(1),            // Require exactly 1 argument
    Example: `  myctl deploy api --env production --version v2.1.0
  myctl deploy worker --env staging --dry-run`,
    RunE: func(cmd *cobra.Command, args []string) error {
        service := args[0]
        env, _ := cmd.Flags().GetString("env")
        version, _ := cmd.Flags().GetString("version")
        dryRun, _ := cmd.Flags().GetBool("dry-run")

        if dryRun {
            fmt.Printf("DRY RUN: Would deploy %s@%s to %s\n", service, version, env)
            return nil
        }

        fmt.Printf("Deploying %s@%s to %s...\n", service, version, env)
        return performDeploy(service, env, version)
    },
}

func init() {
    rootCmd.AddCommand(deployCmd)
    deployCmd.Flags().StringP("env", "e", "staging", "target environment")
    deployCmd.Flags().String("version", "latest", "version to deploy")
    deployCmd.Flags().Bool("dry-run", false, "simulate deployment")
    deployCmd.MarkFlagRequired("env")
}
// cmd/status.go — Another subcommand
var statusCmd = &cobra.Command{
    Use:     "status [service]",
    Short:   "Show service status",
    Aliases: []string{"st"},              // myctl st == myctl status
    Args:    cobra.MaximumNArgs(1),
    ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
        // Dynamic completion: list available services
        services := []string{"api", "worker", "scheduler", "web"}
        return services, cobra.ShellCompDirectiveNoFileComp
    },
    RunE: func(cmd *cobra.Command, args []string) error {
        if len(args) == 0 {
            return showAllStatus()
        }
        return showServiceStatus(args[0])
    },
}

Shell Completions

# Generate completions
myctl completion bash > /etc/bash_completion.d/myctl
myctl completion zsh > "${fpath[1]}/_myctl"
myctl completion fish > ~/.config/fish/completions/myctl.fish

# Cobra generates completions for all commands, flags, and arguments automatically

Installation

go get github.com/spf13/cobra
# Scaffolding tool
go install github.com/spf13/cobra-cli@latest
cobra-cli init
cobra-cli add deploy
cobra-cli add status

Best Practices

  1. Subcommands for organization — Group related functionality: myctl deploy, myctl status, myctl config
  2. Flags with Viper — Bind flags to Viper for unified config (CLI flags + env vars + config file)
  3. RunE over Run — Use RunE (returns error) instead of Run; Cobra handles error display and exit codes
  4. Argument validation — Use Args: cobra.ExactArgs(1) or custom validators; catch errors before execution
  5. Shell completions — Cobra generates bash/zsh/fish/powershell completions; add ValidArgsFunction for dynamic completion
  6. Help is automatic — Cobra generates --help, usage text, and subcommand lists; customize with Long and Example
  7. Aliases for convenience — Add short aliases: st for status, d for deploy
  8. Persistent flags — Use PersistentFlags() on root for flags that apply to all subcommands (--verbose, --config)

当前收录版本

1.0.0

核对来源版本 ↗

质量评测

满分100 · 来自 SkillPi LAB 实验室的评测报告。

场景价值85/100

亮点

  • Cobra 是 Go 生态中构建 CLI 工具的事实标准,Skill 提供完整的使用指南和最佳实践
  • 覆盖从基础结构到高级功能(子命令、标志、Shell 补全),满足开发者高频需求
触发精准95/100

亮点

  • description 清晰定义 Skill 为 Cobra 专家,触发词精准覆盖 CLI 构建场景
结构规范90/100

亮点

  • 文档结构清晰,分模块展示核心能力、安装方式和最佳实践
  • 提供完整可运行的代码示例,便于开发者直接参考使用
执行可靠90/100

亮点

  • 工具来源明确(github.com/spf13/cobra),参数和命令示例正确
  • 使用 RunE 进行错误处理,符合 Cobra 最佳实践
证据可验 (前四项均值)90/100

取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。

正文静态检测

100 / 100 · skillpi-20261123-no-r3-v1

正文未命中当前规则。

分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。

权限与使用前检查

根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。

未从主文档识别到上述常见操作,不能据此判断无需权限或没有风险。

本站展示提示不会授予权限。涉及文件改动、密钥、外部发送或费用时,仍由你使用的工具按需确认。

安全评级与访问范围

safe · 静态证据核验,不代表运行安全保证。

使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。