tools

package
v0.0.0-...-1b9f67d Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 14, 2025 License: MIT Imports: 25 Imported by: 0

Documentation

Overview

Package tools provides utilities and shared functionality for the `tools` command and its subcommands. It also includes reusable components that can be utilized by other commands or shared across multiple subcommands.

Index

Constants

This section is empty.

Variables

View Source
var BuiltinTools map[string]InstallToolsInfo

BuiltinTools 内部维护工具的名称和安装路径(既可 go install,也可 clone 构建)

View Source
var ToolsRunMsg = struct {
	Short string
	Long  string
}{
	Short: "Run a tool",
	Long: `
Run a tool by configured name or by explicit path and forward all remaining
arguments to the executed binary unchanged.

Basic usage:
  gocli tool run <tool> [args...]
  gox run <tool> [args...]

Examples:
  # Run a configured tool named "task"
  gocli tools run task
  gox run task

  # Execute a binary by path and forward flags/args
  gocli tools run task --list
  gox run task --list

Notes:
  - Use 'gocli tools list' to inspect available configured tools and their
    install paths.
  - If the first argument matches a configured tool name (case-insensitive),
    gocli will run the discovered binary for that tool.
  - If the argument looks like a path (contains path separators or is absolute),
    and the file exists, gocli will execute that path directly.
  - All flags and arguments after the tool name are forwarded verbatim to the
    invoked executable. Unknown flags are allowed so flags intended for the
    executed tool are not interpreted by cobra.
`,
}

ToolsRunMsg 用于显示 gocli tools run 的帮助信息

Functions

func BatchInstallConfiguredGlobalTools

func BatchInstallConfiguredGlobalTools(cfg *configs.Config, envFlags []string, verbose bool) error

BatchInstallConfiguredGlobalTools installs only global tools to ~/.gocli/tools

func BatchInstallConfiguredTools

func BatchInstallConfiguredTools(cfg *configs.Config, envFlags []string, verbose bool) error

BatchInstallConfiguredTools installs tools from a Config (deps and global)

func ClearToolsCache

func ClearToolsCache()

ClearToolsCache 清空缓存(可在工具安装/卸载或用户显式请求刷新时调用)

func CloneAndBuildInstall

func CloneAndBuildInstall(o CloneBuildOptions) (string, error)

CloneAndBuildInstall 克隆仓库并按指定构建方式构建,然后从 bin 目录收集产物

func DetermineGoBinDir

func DetermineGoBinDir() string

DetermineGoBinDir 尝试通过 `go env` 推断 GOBIN 或 GOPATH/bin

func ExecuteInstallCommand

func ExecuteInstallCommand(opts InstallCommandOptions, outputWriter io.Writer) error

ExecuteInstallCommand 执行install命令的封装函数

func ExecuteSearchCommand

func ExecuteSearchCommand(opts SearchCommandOptions, outputWriter io.Writer) error

ExecuteSearchCommand 执行搜索命令

func ExecuteToolRun

func ExecuteToolRun(args []string, out io.Writer, verbose bool, gocliToolsPath string) error

ExecuteToolRun finds and executes a tool by name or path. This is an exported wrapper so external binaries (like the `gox` shim) can reuse the same logic as the main `gocli tools run` implementation in cmd.

func ExecuteUninstallCommand

func ExecuteUninstallCommand(opts UninstallCommandOptions, out io.Writer) error

ExecuteUninstallCommand 执行工具卸载命令的封装函数 它会基于传入的选项查找已安装的二进制并按交互/批量规则删除它们 ExecuteUninstallCommand 执行卸载操作的主入口

  1. 根据 opts.Args(工具名)查找候选的工具定义(通过配置或已知工具列表)
  2. 对每个候选的 binary name,扫描可能的目录(GOPATH/bin、gocli 工具目录、用户目录) 以收集实际存在的可执行文件路径(可能存在多个同名二进制在不同目录)
  3. 根据 opts.All / opts.Yes / opts.Dry 的组合决定交互方式和实际删除行为: - 如果 --all 且同时提供 --yes:直接删除找到的所有匹配项(不可逆) - 如果 --all 且未提供 --yes:对每个匹配的文件逐一交互确认(更安全) - 如果未指定 --all:默认行为为逐文件交互(除非 --yes) - 如果 --dry:不做实际删除,仅打印将要删除的路径

该函数同时处理去重(相同 binary name 不重复询问)以及在删除成功后清理内部工具缓存

func InstallConfiguredToolsFromList

func InstallConfiguredToolsFromList(list []configs.Tool, targetPath, category string, envFlags []string, verbose bool) (int, int)

InstallConfiguredToolsFromList installs a list of configs.Tool entries

func InstallGoTool

func InstallGoTool(spec, installDir string, env []string, verbose bool, buildArgs []string) (string, string, error)

InstallGoTool 安装 Go 工具

  • spec: go install 的目标(模块路径或本地路径),可带 @version
  • installDir: 若不为空,作为目标安装目录(将通过 GOBIN 传入);支持 $ENV 与 ~ 展开
  • env: 额外环境变量(如 CGO_ENABLED=1)

返回:命令输出、最终绝对安装目录(若设置了 installDir)、错误

func LoadUserTools

func LoadUserTools(path string) error

LoadUserTools 从指定的 JSON 文件加载用户自定义的工具表并合并到全局 BuiltinTools 中 如果键存在则会覆盖已有条目

func ParseGoInstallSpec

func ParseGoInstallSpec(cmd string) (string, error)

ParseGoInstallSpec extracts spec from "go install ..." command string

func PrintInstallOutput

func PrintInstallOutput(output string, err error, verbose bool)

PrintInstallOutput prints install output depending on verbose/err level

func PrintSingleTool

func PrintSingleTool(bi *InstallToolsInfo, fmtFlag string, out io.Writer) error

PrintSingleTool prints a single tool info in requested format

func PrintToolsTable

func PrintToolsTable(w io.Writer, tools []ToolInfo, verbose bool) error

PrintToolsTable prints tools in table format to the provided writer. This is the pkg/tools exported replacement for the previous cmd.printToolsTable.

func RegisterBuildRunner

func RegisterBuildRunner(r BuildRunner)

RegisterBuildRunner 注册一个构建器

func RenameInstalledBinary

func RenameInstalledBinary(dir string, pre map[string]time.Time, targetName string, _ bool) error

RenameInstalledBinary 基于安装前后的快照在目录内查找新增/更新的可执行文件,并按需重命名

func ResolveTool

func ResolveTool(name string, paths []string) (*InstallToolsInfo, []InstallToolsInfo)

ResolveTool 查找工具:先精确查找配置表,若找不到则进行模糊搜索

func Search(name string, paths []string, interactive bool) (*InstallToolsInfo, []InstallToolsInfo, error)

Search executes a search with optional interactive selection.

func SetRunHelpFunc

func SetRunHelpFunc(cmd *cobra.Command)

SetRunHelpFunc configures a help printer for "run"-style commands that should hide inherited/global flags and only display usage, long text, local flags and available subcommands. This is used by both the `gocli tools run` command and the `gox` shim so help output is identical.

func ShowRunHelpIfRequested

func ShowRunHelpIfRequested(cmd *cobra.Command)

ShowRunHelpIfRequested inspects the original os.Args to determine if the user asked for help specifically for a run-style command (e.g. `gocli run --help` or `gox --help`) and prints help then exits. Prefer calling this in a command's PreRun to preserve flags intended for the executed tool.

func SnapshotExecutables

func SnapshotExecutables(dir string) map[string]time.Time

SnapshotExecutables quick snapshot of executable files modification time

func TestExists

func TestExists(tool string) (string, error)

TestExists 检查指定的工具是否存在于系统的 PATH 中; 若不存在且为内置工具,则尝试按其 InstallType 自动安装.

Types

type BuildContext

type BuildContext struct {
	RepoDir     string   // 仓库根目录
	BuildDir    string   // 实际执行构建的目录(可能等于 RepoDir 或其子目录)
	AbsBase     string   // 基础安装目录(用于默认 GOBIN 等)
	RepoURL     string   // 仓库 URL
	ResolvedRef string   // 实际检出的 ref(可能是具体 tag)
	DisplayRef  string   // 展示用 ref(如 latest)
	Env         []string // 环境变量
	Verbose     bool
}

BuildContext 提供构建时的上下文信息

type BuildParams

type BuildParams struct {
	// make 相关
	MakeTarget string
	// goreleaser 相关与通用附加参数
	GoreleaserConfig string
	BuildArgs        []string
}

BuildParams 是通用的构建参数载体

type BuildRunner

type BuildRunner interface {
	// Name 返回构建器名称(例如 "make"、"goreleaser")
	Name() string
	// DefaultBinDirs 返回该构建器典型的产物输出目录(相对 BuildDir)
	DefaultBinDirs() []string
	// Build 执行构建,返回标准输出/错误的合并文本
	Build(ctx BuildContext, params BuildParams) (string, error)
}

BuildRunner 定义不同构建方式的统一接口

func GetBuildRunner

func GetBuildRunner(name string) (BuildRunner, bool)

GetBuildRunner 获取构建器

type CloneBuildOptions

type CloneBuildOptions struct {
	CloneURL          string
	InstallDir        string
	Env               []string
	Verbose           bool
	RecurseSubmodules bool
	BuildMethod       string // "make" | "goreleaser" | 其他通过注册表拓展
	MakeTarget        string
	BuildArgs         []string
	WorkDir           string
	GoreleaserConfig  string
	BinDirs           []string
	BinaryName        string
	Force             bool // 强制模型,如果目标目录已存在则覆盖,否则就复用
}

CloneBuildOptions 描述 clone 后的构建行为

type GoreleaserRunner

type GoreleaserRunner struct{}

GoreleaserRunner 实现 BuildRunner

func (GoreleaserRunner) Build

func (GoreleaserRunner) Build(ctx BuildContext, params BuildParams) (string, error)

Build 实现 BuildRunner 接口

func (GoreleaserRunner) DefaultBinDirs

func (GoreleaserRunner) DefaultBinDirs() []string

DefaultBinDirs 实现 BuildRunner 接口

func (GoreleaserRunner) Name

func (GoreleaserRunner) Name() string

Name 实现 BuildRunner 接口

type InstallCommandOptions

type InstallCommandOptions struct {
	// 命令行参数
	Args []string
	// 嵌入 InstallOptions 以复用安装相关字段
	InstallOptions

	// 额外命令行上下文字段
	// Global indicates --global was set on the install command
	Global         bool
	Quiet          bool
	GoCLIToolsPath string
	ToolsConfigDir []string

	// Yes: 非交互模式直接执行
	Yes bool
	// Input: 交互输入源(默认 os.Stdin)
	Input io.Reader
}

InstallCommandOptions 定义了install命令的选项和上下文

type InstallOptions

type InstallOptions struct {
	// go install 专用:模块/本地路径规范,如 github.com/owner/repo/cmd/foo@vX 或 ./path
	Spec string

	// clone+make 专用:仓库 URL,可带 #ref
	CloneURL   string
	MakeTarget string

	// 构建方式(在 clone 模式下有效):"make"(默认)、"goreleaser"、后续可扩展
	BuildMethod string
	// 传递给构建器的附加参数,例如 goreleaser 的 flags 或 make 的额外参数
	BuildArgs []string
	// 在仓库中的子目录进行构建(为空则使用仓库根目录)
	WorkDir string
	// goreleaser 可选配置文件路径(相对于仓库根或 WorkDir)
	GoreleaserConfig string

	// 指定安装目录,等价于设置 GOBIN;若为空,沿用默认规则
	Path string

	// 额外构建/运行环境变量,如 CGO_ENABLED=1
	Env []string

	// 当使用 clone+make 时,从这些目录收集可执行产物并复制到安装目录(可多次传入,或使用平台路径分隔符分隔)
	BinDirs []string

	// 是否 verbose
	Verbose bool
	// 预设构建模式
	ReleaseBuild bool
	DebugBuild   bool

	// BinaryName 指定生成的二进制文件名(可选)
	BinaryName string
	// Clone: 是否递归克隆子模块
	RecurseSubmodules bool

	// Force: 强制模型,如果目标目录已存在则覆盖,否则就复用
	Force bool

	// Tags: 构建标签,用于 go install 的 -tags 参数
	Tags []string
}

InstallOptions 用于统一描述工具安装的参数

type InstallResult

type InstallResult struct {
	// 原始命令输出(可能为多行)
	Output string
	// 明确的安装目录(当设置 Path 或 go install 传入 GOBIN 时)
	InstallDir string
	// 根据环境与 go env 推断的安装目录(即便 InstallDir 为空也会提供)
	ProbableInstallDir string
	// 执行模式:go_install 或 clone_make
	Mode string
}

InstallResult 统一返回值

func InstallTool

func InstallTool(opts InstallOptions) (InstallResult, error)

InstallTool 统一入口:根据是否传入 CloneURL 决定使用 go install 或 clone+make

type InstallToolsInfo

type InstallToolsInfo struct {
	Name string `mapstructure:"name" jsonschema:"title=Name,description=Tool identifier"`
	// URL: go install 的模块路径(可带 @version),与 CloneURL 互斥;保留兼容
	URL string `` /* 132-byte string literal not displayed */
	// CloneURL: 通过 git clone 构建时使用的仓库地址,可带 #ref(tag/branch/commit)
	CloneURL string `` /* 130-byte string literal not displayed */

	// Build: clone 模式下的构建方式,例如 "make"、"goreleaser"(默认 make)
	Build string `mapstructure:"build" jsonschema:"description=Build method for clone mode, e.g. make or goreleaser,nullable"`
	// MakeTarget: make 模式下要执行的目标名(可为空执行默认目标)
	MakeTarget string `mapstructure:"make_target" jsonschema:"description=Make target to run (empty for default),nullable"`
	// WorkDir: 在仓库中的子目录进行构建(为空则仓库根目录)
	WorkDir string `` /* 128-byte string literal not displayed */
	// BinDirs: 构建产物所在目录(相对 WorkDir/仓库根);为空则按构建器默认(goreleaser -> dist)
	BinDirs []string `` /* 140-byte string literal not displayed */
	// Env: 该工具需要的额外环境变量(如 CGO_ENABLED=1)
	Env []string `` /* 140-byte string literal not displayed */
	// GoreleaserConfig: goreleaser 构建时的配置文件路径(相对 WorkDir/仓库根)
	GoreleaserConfig string `` /* 129-byte string literal not displayed */

	InstallType *InstallType `` /* 135-byte string literal not displayed */
	// BinaryName 指定该工具生成的二进制文件名(可选);
	BinaryName string `` /* 155-byte string literal not displayed */
	// Tags: 构建标签,用于 go install 的 -tags 参数
	Tags []string `mapstructure:"tags" jsonschema:"description=Build tags to pass to go install,nullable,uniqueItems"`
}

InstallToolsInfo 定义了内置工具的信息

func FindToolsFuzzy

func FindToolsFuzzy(query string, paths []string) []InstallToolsInfo

FindToolsFuzzy 在内置工具表(以及用户合并的表)中进行模糊搜索

func InteractiveSelect

func InteractiveSelect(matches []InstallToolsInfo) (*InstallToolsInfo, error)

InteractiveSelect 使用 fuzzyfinder 在多个候选中交互选择一项

func SearchTools

func SearchTools(name string, path []string) *InstallToolsInfo

SearchTools 根据工具名称和路径查找工具信息

type InstallType

type InstallType struct {
	Name string `mapstructure:"name" jsonschema:"description=Install type name, e.g. go_install or clone,nullable"`
	OS   string `mapstructure:"os" jsonschema:"description=Restricted OS name, e.g. linux/darwin/windows,nullable"`
	Arch string `mapstructure:"arch" jsonschema:"description=Restricted CPU architecture, e.g. amd64/arm64,nullable"`
}

InstallType 定义了内置工具的安装类型

type MakeRunner

type MakeRunner struct{}

MakeRunner 实现 BuildRunner

func (MakeRunner) Build

func (MakeRunner) Build(ctx BuildContext, params BuildParams) (string, error)

Build 实现 BuildRunner 接口

func (MakeRunner) DefaultBinDirs

func (MakeRunner) DefaultBinDirs() []string

DefaultBinDirs 实现 BuildRunner 接口

func (MakeRunner) Name

func (MakeRunner) Name() string

Name 实现 BuildRunner 接口

type SearchCommandOptions

type SearchCommandOptions struct {
	Query     string
	Format    string
	JSON      bool
	YAML      bool
	Table     bool
	ConfigDir []string
}

SearchCommandOptions 定义了搜索命令的选项

type ToolInfo

type ToolInfo struct {
	Name   string         `json:"name"`
	Path   string         `json:"path"`
	Source toolSourceType `json:"source"`
	// 以下字段用于 verbose 展示
	Size    int64     `json:"size,omitempty"`
	ModTime time.Time `json:"modTime,omitzero"`
}

ToolInfo 描述一个可用的工具

func FindTools

func FindTools(verbose bool, gocliToolsPath string) []ToolInfo

FindTools 在内部使用按 key 的并发安全缓存(每个 key 使用 sync.Once 确保只初始化一次)

type UninstallCommandOptions

type UninstallCommandOptions struct {
	Args  []string
	Yes   bool
	Dry   bool
	Fuzzy bool
	All   bool

	Verbose bool
	Quiet   bool

	GoCLIToolsPath string
	ToolsConfigDir []string

	// Input reader for interactive prompts; if nil, os.Stdin is used
	Input io.Reader
}

UninstallCommandOptions 定义卸载命令的所有选项和上下文

说明(中文注释):

  • Args: 要卸载的工具名称列表
  • Yes: 是否跳过交互提示(等同于 --yes,自动确认删除)
  • Dry: 是否为模拟运行(--dry),不实际删除文件,仅打印会删除的项
  • Fuzzy: 是否模糊匹配工具名称(例如包含关系)
  • All: 是否删除所有匹配位置(比如 GOPATH/bin、~/.gocli/tools 等), 注意:All 与交互行为结合时会逐文件提示(除非 --yes)
  • Verbose / Quiet: 输出控制
  • GoCLIToolsPath: 可选的 gocli 工具目录覆盖(用于搜索)
  • ToolsConfigDir: 搜索工具配置文件的目录列表
  • Input: 用于测试或重定向输入的 io.Reader;若为 nil,使用 os.Stdin

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL