go-tool-base

module
v0.41.1 Latest Latest
Warning

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

Go to latest
Published: Sep 15, 2026 License: MIT

README ΒΆ

Go Tool Base (GTB)

pipeline status coverage report latest release

The Intelligent Application Lifecycle Framework for Go.

Flag parsing is the easy part. What costs you is everything after it: configuration that layers properly, a self-update path you trust, errors a user can act on, and the same six commands written again in every tool. GTB is a batteries-included micro-framework (think Rails or Laravel) for Go command-line applications, and it ships those already built.

βœ… What GTB IS / IS NOT

  • IS a full-lifecycle framework. Configuration, versioning, auto-updates, embedded TUI docs, error handling and structured logging, out of the box.
  • IS a dependency injection container. Services are passed explicitly through the Props container to every command constructor. Nothing reaches for a global.
  • IS an AI-ready foundation. Agentic loop orchestration and MCP exposure are built in.
  • NOT a web framework (like Gin/Fiber) or a microservice generator (like Sponge). GTB primarily bootstraps CLI utilities and background daemons, though you can easily build a serve command that boots an HTTP router via GTB's DI container!

[!IMPORTANT] Full Documentation: For detailed guides, component deep-dives, framework comparisons, and API references, please visit our documentation site: https://gtb.phpboyscout.uk

πŸ“¦ CLI Installation

To install the gtb automation CLI, use the recommended installation script for your platform:

macOS/Linux (bash/zsh):

curl -sSL "https://gitlab.com/phpboyscout/go-tool-base/-/raw/main/install.sh" | bash

Windows (PowerShell):

irm "https://gitlab.com/phpboyscout/go-tool-base/-/raw/main/install.ps1" | iex
Homebrew (macOS)

Every release publishes a cask to the GitLab-hosted tap at phpboyscout/homebrew, so Homebrew handles upgrades for you:

brew tap phpboyscout/homebrew https://gitlab.com/phpboyscout/homebrew.git
brew install --cask gtb

Upgrade later with brew upgrade --cask gtb.

[!NOTE] Pass the tap URL. The shorthand brew tap phpboyscout/homebrew resolves to github.com/phpboyscout/homebrew-homebrew, which does not exist. The tap is on GitLab, so the URL is required.

If you tapped the pre-migration GitHub tap before it was withdrawn, remove it with brew untap phpboyscout/homebrew, or brew update will fail against it.

[!NOTE] For developers building from source, you can still use go install gitlab.com/phpboyscout/go-tool-base/cli/cmd/gtb@latest. Note the /cli/cmd/gtb suffix: the CLI is a nested module and its main package is not at the repository root. A source build carries no pre-built documentation assets, so the docs command falls back to a limited source-build mode.

πŸš€ Key Advantages & Features

  • πŸ€– AI Agentic Workflows: Integrated support for Claude, Gemini, and OpenAI to power autonomous ReAct-style loops and built-in Q&A against your embedded docs.
  • πŸ”Œ Model Context Protocol (MCP): Expose your CLI commands automatically as MCP tools for use by IDEs and external AI agents.
  • πŸ“¦ Auto Updates & Lifecycle: Zero-config version checking and self-update, straight from GitHub/GitLab releases, via the built-in update command.
  • πŸ“• TUI Documentation: A built-in, interactive terminal browser for your markdown documentation. Forget generic man pages.
  • 🧱 Scaffold: Generate production-ready, interface-driven CLI tool skeletons in seconds.
  • βš™οΈ Robust Configuration: Configuration merged from files, environment variables and embedded assets, in a precedence you can inspect.
  • 🏒 Enterprise VCS: Deep integration with GitHub Enterprise and GitLab (including nested group paths) for auth, PR management, and assets.
  • 🩹 Error Handling: Structured, testable error management with logging, stack traces, and integrated help context routing to user-facing output.

πŸ—οΈ Core Architecture

The framework is built around a centralized Props container that provides type-safe access to all system dependencies.

Much of what GTB once implemented now lives in the standalone phpboyscout Go toolkit, small framework-free modules under gitlab.com/phpboyscout/go/, so a tool can take one without taking all of GTB. Where that happened, the pkg/ package that remains is a thin config adapter that wires the module from Props.

Component Implementation Responsibility
pkg/props GTB Central dependency injection container for logger, config, assets, filesystem, version and error handling.
config go/config Layered, snapshot-coherent configuration: provenance-aware reads, comment-preserving writes, explicit hot reload, and published mocks.
pkg/chat go/chat + provider modules Unified multi-provider AI client (Claude, OpenAI, Gemini, Claude Local). pkg/chat owns the GTB config-key schema and registers the providers.
controls go/controls Service lifecycle: startup ordering, health probes, graceful shutdown.
pkg/http, pkg/grpc, pkg/gateway go/transport Hardened HTTP/gRPC servers and the REST gateway; the pkg/ packages are the config adapters.
pkg/setup GTB Bootstrap logic: auth, key management, command middleware, and pluggable self-updating.
pkg/vcs go/forge + go/repo GitHub/GitLab/Gitea/Bitbucket releases and auth; pkg/vcs wires them from resolved config.
errorhandling go/errorhandling Structured errors with user-facing hints, exit codes, stack traces and log integration.
pkg/docs, output GTB / go/output Interactive TUI documentation browser; structured text/JSON/YAML/CSV output.

πŸ› οΈ Built-in Commands

Every tool built on GTB inherits these essential capabilities:

  • init: Bootstraps local environments, configures GitHub/GitLab auth, and manages SSH keys.
  • version: Reports the current version and checks for available updates.
  • update: Downloads and installs the latest release binary from GitHub or GitLab.
  • mcp: Exposes CLI commands as Model Context Protocol (MCP) tools for use in IDEs.
  • docs: Interactive terminal browser for documentation with built-in AI Q&A.
  • doctor: Runs diagnostic checks to validate configuration, connectivity, and runtime environment.
  • changelog: Shows the tool's version history.
  • telemetry (opt-in): Manages pseudonymous usage telemetry.
  • config (opt-in): Reads and writes the tool's configuration.
  • man (opt-in): Generates roff man pages for the command tree.

Commands can be selectively enabled or disabled at bootstrap time via feature flags. See Feature Flags below.

πŸ€– AI Providers

GTB reaches every provider the go/chat module family registers, through a unified pkg/chat adapter. A provider is a module a tool blank-imports from its main; gtb itself links all of them.

Provider Constant Module Notes
Anthropic Claude ProviderClaude go/chat-anthropic Requires ANTHROPIC_API_KEY
Claude Local ProviderClaudeLocal go/chat-anthropic The claude CLI on this machine; no key
OpenAI ProviderOpenAI go/chat-openai Requires OPENAI_API_KEY
OpenAI-Compatible ProviderOpenAICompatible go/chat-openai Any OpenAI-shaped endpoint (Ollama, xAI)
Codex Local ProviderCodexLocal go/chat-openai The codex CLI on this machine; no key
Google Gemini ProviderGemini go/chat-gemini Requires GEMINI_API_KEY
Gemini on Vertex AI ProviderGeminiVertex go/chat-gemini Google application default credentials
Agy Local ProviderAgyLocal go/chat-gemini The agy CLI on this machine; no key, no tools
AWS Bedrock ProviderBedrock go/chat-bedrock The AWS credential chain
Azure OpenAI ProviderAzureOpenAI go/chat-openai-azure A deployment endpoint; api-key or Entra token

Set the active provider with the AI_PROVIDER environment variable or in your tool's configuration. GTB's own init wizard sets up credentials for the API-key providers; the local CLIs need none, and Vertex, Bedrock and Azure are configured through go/chat's own settings.

🏁 Quick Start

The fastest way to create a new GTB-based tool is with the scaffold command:

gtb generate project

This launches an interactive wizard to configure your project. For automation:

gtb generate project --name mytool --repo myorg/mytool --description "My CLI tool" --path ./mytool

For a GitLab-hosted project with nested groups:

gtb generate project --name mytool --repo myorg/mygroup/mytool --git-backend gitlab --host gitlab.mycompany.com --path ./mytool
Generated Project Structure

The scaffold produces a fully wired project. The key entry points are:

cmd/mytool/main.go. The entry point, reading version from internal/version. Execute runs the tree with a signal-aware context: SIGINT/SIGTERM cancel cmd.Context() for graceful shutdown, a second signal force-exits, and a signal-terminated run exits 128+signum:

func main() {
    rootCmd, p := root.NewCmdRoot(version.Get())
    gtbRoot.Execute(rootCmd, p)
}

pkg/cmd/root/cmd.go. Wires the Props container and the root command:

//go:embed assets/*
var assets embed.FS

func NewCmdRoot(v version.Info) (*setup.Command, *props.Props) {
    l := logger.NewCharm(os.Stderr, logger.WithTimestamp(true))

    p := &props.Props{
        Tool: props.Tool{
            Name:        "mytool",
            Description: "My CLI tool",
            EnvPrefix:   "MYTOOL",
            ReleaseSource: props.ReleaseSource{
                Type:  "gitlab",
                Host:  "gitlab.com",
                Owner: "myorg",
                Repo:  "mytool",
            },
        },
        Logger:  l,
        FS:      afero.NewOsFs(),
        Version: v,
        Assets:  props.NewAssets(props.AssetMap{"root": &assets}),
    }
    p.ErrorHandler = errorhandling.New(logger.ToSlog(l), p.Tool.Help)

    return gtbRoot.NewCmdRoot(p, NewCmdServe(p)), p
}

[!NOTE] Command constructors return *setup.Command, not *cobra.Command. It embeds *cobra.Command and carries the feature the command belongs to, so it behaves as a cobra command everywhere; .Command exposes the raw pointer when a cobra API needs one. Register child commands with parent.Register(child) rather than AddCommand, so the feature middleware chain is applied.

internal/version/version.go. Populated from GoReleaser ldflags at release, or from runtime/debug VCS info in development:

var (
    version = "dev"
    commit  = "none"
    date    = "unknown"
)

🏳️ Feature Flags

Commands can be selectively disabled or opt-in features enabled via the Tool configuration:

Feature Default Description
update enabled Self-update capability
init enabled Environment bootstrap command
mcp enabled Model Context Protocol server
docs enabled Documentation browser
doctor enabled Diagnostic health checks
changelog enabled Version history command
ai disabled AI-powered features (opt-in)
config disabled Configuration read/write command
telemetry disabled Pseudonymous usage telemetry
man disabled roff man-page generation

version is always present and is not gated. Only builtin features may be default-enabled; a plugin feature that declares itself default-on is rejected with ErrPluginDefaultOn.

p := &props.Props{
    Tool: props.Tool{
        // ...
        Features: props.SetFeatures(
            props.Disable(props.UpdateCmd), // disable self-update
            props.Enable(props.AiCmd),      // opt-in to AI features
        ),
    },
}

πŸ“‚ Project Layout

Standard layout for GTB projects:

.
β”œβ”€β”€ cmd/
β”‚   └── mytool/
β”‚       └── main.go              # Entry point
β”œβ”€β”€ pkg/
β”‚   └── cmd/
β”‚       └── root/
β”‚           β”œβ”€β”€ cmd.go           # Root command and Props setup
β”‚           └── assets/
β”‚               └── init/
β”‚                   └── config.yaml  # Default configuration
β”œβ”€β”€ internal/
β”‚   └── version/
β”‚       └── version.go           # Version info (ldflags + runtime/debug)
β”œβ”€β”€ go.mod
└── README.md

Directories ΒΆ

Path Synopsis
cli module
cmd
changelog command
docs command
framework-footprint-smoke command
Command framework-footprint-smoke is a compile-time fixture: a tool built on the framework that imports pkg/cmd/root and nothing else.
Command framework-footprint-smoke is a compile-time fixture: a tool built on the framework that imports pkg/cmd/root and nothing else.
internal
exectest
Package exectest provides reusable fakes for the process-execution seams (exec.LookPath, exec.CommandContext, os.Executable) that GTB code injects for testability.
Package exectest provides reusable fakes for the process-execution seams (exec.LookPath, exec.CommandContext, os.Executable) that GTB code injects for testability.
testutil
Package testutil provides shared test helpers for the go-tool-base module.
Package testutil provides shared test helpers for the go-tool-base module.
transportcfg
Package transportcfg holds config-resolution helpers shared by the pkg/grpc and pkg/http server adapters.
Package transportcfg holds config-resolution helpers shared by the pkg/grpc and pkg/http server adapters.
mocks
pkg
chat
Package chat is go-tool-base's framework-integration layer over the standalone multi-provider chat client gitlab.com/phpboyscout/go/chat.
Package chat is go-tool-base's framework-integration layer over the standalone multi-provider chat client gitlab.com/phpboyscout/go/chat.
cmd/changelog
Package changelog provides the `changelog` command for displaying version history from an embedded CHANGELOG.md, with optional version and since-tag filtering.
Package changelog provides the `changelog` command for displaying version history from an embedded CHANGELOG.md, with optional version and since-tag filtering.
cmd/config
Package config implements the "config" CLI command and its subcommands for programmatic read/write access to individual configuration keys.
Package config implements the "config" CLI command and its subcommands for programmatic read/write access to individual configuration keys.
cmd/docs
Package docs provides the Cobra `docs` command for browsing this tool's embedded documentation in a terminal (an interactive Bubble Tea browser), with two subcommands: `serve` (host the docs as a static HTTP site) and `ask` (AI-assisted Q&A grounded in the bundled docs at runtime).
Package docs provides the Cobra `docs` command for browsing this tool's embedded documentation in a terminal (an interactive Bubble Tea browser), with two subcommands: `serve` (host the docs as a static HTTP site) and `ask` (AI-assisted Q&A grounded in the bundled docs at runtime).
cmd/doctor
Package doctor provides a diagnostic command that validates configuration, checks environment health, and reports runtime details.
Package doctor provides a diagnostic command that validates configuration, checks environment health, and reports runtime details.
cmd/initialise
Package initialise provides the Cobra command for bootstrapping a new tool's configuration directory and default config file, running registered setup.Initialiser hooks in sequence.
Package initialise provides the Cobra command for bootstrapping a new tool's configuration directory and default config file, running registered setup.Initialiser hooks in sequence.
cmd/man
Package man implements the hidden, opt-in "man" command that emits roff man pages for a tool's own command tree at runtime β€” for packaging postinstall scripts or ad-hoc preview β€” without re-running the source-tree generator.
Package man implements the hidden, opt-in "man" command that emits roff man pages for a tool's own command tree at runtime β€” for packaging postinstall scripts or ad-hoc preview β€” without re-running the source-tree generator.
cmd/root
Package root provides the reusable root Cobra command constructor that wires configuration loading, logging setup, update checks, and feature-flagged subcommand registration (version, update, init, doctor, config, telemetry, changelog, man, MCP, docs).
Package root provides the reusable root Cobra command constructor that wires configuration loading, logging setup, update checks, and feature-flagged subcommand registration (version, update, init, doctor, config, telemetry, changelog, man, MCP, docs).
cmd/telemetry
Package telemetry provides the `telemetry` command group for managing pseudonymous usage telemetry: enable, disable, status, and reset subcommands.
Package telemetry provides the `telemetry` command group for managing pseudonymous usage telemetry: enable, disable, status, and reset subcommands.
cmd/update
Package update provides the Cobra command for self-updating the CLI binary to the latest released version from the configured release source (GitHub or GitLab), with support for private repositories via token authentication.
Package update provides the Cobra command for self-updating the CLI binary to the latest released version from the configured release source (GitHub or GitLab), with support for private repositories via token authentication.
cmd/version
Package version provides the Cobra command for displaying the CLI's current version, build date, and commit information.
Package version provides the Cobra command for displaying the CLI's current version, build date, and commit information.
credentialposture
Package credentialposture reports where a credential comes from, without ever reporting what it is.
Package credentialposture reports where a credential comes from, without ever reporting what it is.
docs
Package docs provides a documentation system with two subsystems: a generation engine that parses Cobra command trees into Markdown files with hierarchy-aware index management, and a TUI browser built on Bubbles with split-pane navigation, async search, and AI-powered Q&A via retrieval-augmented generation (RAG).
Package docs provides a documentation system with two subsystems: a generation engine that parses Cobra command trees into Markdown files with hierarchy-aware index management, and a TUI browser built on Bubbles with split-pane navigation, async search, and AI-powered Q&A via retrieval-augmented generation (RAG).
gateway
Package gateway is GTB's framework-integration layer over the extracted grpc-gateway module.
Package gateway is GTB's framework-integration layer over the extracted grpc-gateway module.
grpc
Package grpc is GTB's framework-integration layer over the extracted gRPC transport module.
Package grpc is GTB's framework-integration layer over the extracted gRPC transport module.
http
Package http is GTB's framework-integration layer over the extracted HTTP transport modules.
Package http is GTB's framework-integration layer over the extracted HTTP transport modules.
logger
Package logger provides GTB's logging boundary.
Package logger provides GTB's logging boundary.
osinfo
Package osinfo reports a human-readable operating-system version string.
Package osinfo reports a human-readable operating-system version string.
props
Package props defines the Props dependency container, the central type-safe dependency injection mechanism used throughout GTB.
Package props defines the Props dependency container, the central type-safe dependency injection mechanism used throughout GTB.
props/test
Package test provides a public test-fixture helper for constructing a fully-wired *props.Props with hermetic, safe defaults.
Package test provides a public test-fixture helper for constructing a fully-wired *props.Props with hermetic, safe defaults.
setup
Package setup provides initialisation helpers for GTB-based tools, including configuration directory bootstrapping, default config file creation, and self-update orchestration.
Package setup provides initialisation helpers for GTB-based tools, including configuration directory bootstrapping, default config file creation, and self-update orchestration.
setup/ai
Package ai provides the interactive AI-provider setup initialiser.
Package ai provides the interactive AI-provider setup initialiser.
setup/forge
Package forge provides a single, provider-parameterised interactive setup initialiser for git forges.
Package forge provides a single, provider-parameterised interactive setup initialiser for git forges.
setup/telemetry
Package telemetry registers the telemetry initialiser with the setup system.
Package telemetry registers the telemetry initialiser with the setup system.
telemetry
Package telemetry provides an opt-in telemetry framework with pluggable backends, privacy controls, bounded buffering, and GDPR-compliant data deletion for CLI tools built on GTB.
Package telemetry provides an opt-in telemetry framework with pluggable backends, privacy controls, bounded buffering, and GDPR-compliant data deletion for CLI tools built on GTB.
telemetry/datadog
Package datadog provides a telemetry backend that sends events to Datadog's HTTP Logs Intake API.
Package datadog provides a telemetry backend that sends events to Datadog's HTTP Logs Intake API.
telemetry/posthog
Package posthog provides a telemetry backend that sends events to PostHog's Capture API (batch payload form).
Package posthog provides a telemetry backend that sends events to PostHog's Capture API (batch payload form).
telemetrytypes
Package telemetrytypes holds the telemetry value types shared between GTB's dependency-injection container (pkg/props) and the collector implementation (pkg/telemetry).
Package telemetrytypes holds the telemetry value types shared between GTB's dependency-injection container (pkg/props) and the collector implementation (pkg/telemetry).
tls
Package tls is GTB's thin adapter over the standalone hardened-TLS module gitlab.com/phpboyscout/go/tls.
Package tls is GTB's thin adapter over the standalone hardened-TLS module gitlab.com/phpboyscout/go/tls.
utils
Package utils provides small shared utility functions used across the GTB framework: terminal-interactivity detection (IsInteractive).
Package utils provides small shared utility functions used across the GTB framework: terminal-interactivity detection (IsInteractive).
vcs
Package vcs holds the thin configuration adapters that bridge GTB's resolved configuration to the extracted version-control modules.
Package vcs holds the thin configuration adapters that bridge GTB's resolved configuration to the extracted version-control modules.
vcs/repo
Package repo adapts GTB's runtime configuration into the typed settings used by the standalone gitlab.com/phpboyscout/go/repo module.
Package repo adapts GTB's runtime configuration into the typed settings used by the standalone gitlab.com/phpboyscout/go/repo module.
version
Package version provides semantic version parsing, comparison, and development-build detection via the Version interface.
Package version provides semantic version parsing, comparison, and development-build detection via the Version interface.

Jump to

Keyboard shortcuts

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