go-tool-base

module
v0.33.0 Latest Latest
Warning

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

Go to latest
Published: Jul 24, 2026 License: MIT

README ΒΆ

Go Tool Base (GTB)

pipeline status coverage report latest release

The Intelligent Application Lifecycle Framework for Go.

Modern CLI tools, DevOps workflows, and developer utilities demand far more than basic flag parsing. GTB works as a "batteries-included" micro-framework (like Rails or Laravel), but meticulously tailored for Go command-line applications and beyond.

βœ… What GTB IS / IS NOT

  • IS a full-lifecycle framework β€” provides configuration, versioning, auto-updates, embedded TUI docs, error handling, and structured logging cleanly out-of-the-box.
  • IS a dependency injection container β€” services are explicitly passed via the decoupled Props container to every command constructor.
  • IS an AI-ready foundation β€” built-in agentic loop orchestration and MCP exposition.
  • 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

[!NOTE] For developers building from source, you can still use go install gitlab.com/phpboyscout/go-tool-base@latest. However, this method will not include pre-built documentation assets, and the docs command will operate in 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: Seamless, zero-config version checking and self-update capabilities directly 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: Overridable configurations seamlessly merging from files, environment variables, and embedded assets.
  • 🏒 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:

Component Responsibility
pkg/props Central dependency injection container for logger, config, and assets.
go/config Layered, snapshot-coherent configuration via the extracted go/config Store β€” provenance-aware reads, comment-preserving writes, hot reload, and published mocks.
pkg/chat Unified multi-provider AI client (Claude, OpenAI, Gemini, Claude Local).
pkg/controls Service lifecycle management and message-based coordination.
pkg/setup Bootstrap logic: auth, key management, and pluggable self-updating.
pkg/vcs Pluggable GitHub/GitLab API and Git operations abstraction.
pkg/errorhandling Structured errors with stack traces and log integration.

πŸ› οΈ 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.

Commands can be selectively enabled or disabled at bootstrap time via feature flags β€” see Feature Flags below.

πŸ€– AI Providers

GTB supports multiple AI providers via a unified pkg/chat interface:

Provider Constant Notes
Anthropic Claude ProviderClaude Requires ANTHROPIC_API_KEY
Claude Local ProviderClaudeLocal Uses a locally installed claude CLI binary
OpenAI ProviderOpenAI Requires OPENAI_API_KEY
OpenAI-Compatible ProviderOpenAICompatible Any OpenAI-compatible endpoint
Google Gemini ProviderGemini Requires GEMINI_API_KEY

Set the active provider with the AI_PROVIDER environment variable or in your tool's configuration.

🏁 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 β€” entry point, reads version from internal/version:

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

pkg/cmd/root/cmd.go β€” wires the Props container and root command:

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

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

    p := &props.Props{
        Tool: props.Tool{
            Name:        "mytool",
            Description: "My CLI tool",
            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(l, p.Tool.Help)

    return gtbRoot.NewCmdRoot(p), p
}

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
ai disabled AI-powered features (opt-in)
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
cmd
changelog command
docs command
e2e command
Package main provides a test-only CLI binary for E2E/BDD testing of framework features.
Package main provides a test-only CLI binary for E2E/BDD testing of framework features.
gtb command
gtb-no-aws-smoke command
Command gtb-no-aws-smoke is a compile-time fixture that proves internal/cmd/keys and internal/cmd/root do not pull the AWS SDK into the linked binary transitively.
Command gtb-no-aws-smoke is a compile-time fixture that proves internal/cmd/keys and internal/cmd/root do not pull the AWS SDK into the linked binary transitively.
internal
agent
Package agent provides tool definitions for the autonomous agentic verification loop used during code generation.
Package agent provides tool definitions for the autonomous agentic verification loop used during code generation.
cmd
Package cmd provides shared utilities for internal CLI commands.
Package cmd provides shared utilities for internal CLI commands.
cmd/disable
Package disable is the gtb-only `disable` command, the inverse of internal/cmd/enable.
Package disable is the gtb-only `disable` command, the inverse of internal/cmd/enable.
cmd/enable
Package enable is the gtb-only `enable` command.
Package enable is the gtb-only `enable` command.
cmd/generate
Package generate provides Cobra commands for scaffolding new CLI projects (project/skeleton), adding commands to existing projects, converting implementations to AI-generated code, and adding flags to commands β€” all driven by manifest definitions and interactive wizards.
Package generate provides Cobra commands for scaffolding new CLI projects (project/skeleton), adding commands to existing projects, converting implementations to AI-generated code, and adding flags to commands β€” all driven by manifest definitions and interactive wizards.
cmd/keys
Package keys is the gtb-only `keys` command group.
Package keys is the gtb-only `keys` command group.
cmd/regenerate
Package regenerate provides Cobra commands for regenerating project command registration files (cmd.go) and manifests from existing project structure, without overwriting implementation files unless explicitly forced.
Package regenerate provides Cobra commands for regenerating project command registration files (cmd.go) and manifests from existing project structure, without overwriting implementation files unless explicitly forced.
cmd/remove
Package remove provides the Cobra command for removing commands and their associated generated files from a project, updating the manifest accordingly.
Package remove provides the Cobra command for removing commands and their associated generated files from a project, updating the manifest accordingly.
cmd/root
Package root provides the internal root command for the gtb CLI itself, registering the generate, regenerate, and remove subcommand groups.
Package root provides the internal root command for the gtb CLI itself, registering the generate, regenerate, and remove subcommand groups.
cmd/sign
Package sign is the gtb-only `gtb sign` command.
Package sign is the gtb-only `gtb sign` command.
cmd/template
Package template is the gtb-only `template` command group.
Package template is the gtb-only `template` command group.
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.
generator
Package generator implements the code generation engine that powers project scaffolding, command generation, and regeneration from manifest definitions.
Package generator implements the code generation engine that powers project scaffolding, command generation, and regeneration from manifest definitions.
generator/templates
Package templates provides Go template definitions and data structures used by the generator to produce CLI command scaffolding, registration code (cmd.go), and implementation stubs (main.go).
Package templates provides Go template definitions and data structures used by the generator to produce CLI command scaffolding, registration code (cmd.go), and implementation stubs (main.go).
generator/verifier
Package verifier provides post-generation verification strategies that validate generated projects compile and pass tests.
Package verifier provides post-generation verification strategies that validate generated projects compile and pass tests.
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.
trustkeys
Package trustkeys exposes the public keys embedded in the gtb binary for self-update signature verification (Phase 2 of the remote-update-checksum-verification spec).
Package trustkeys exposes the public keys embedded in the gtb binary for self-update signature verification (Phase 2 of the remote-update-checksum-verification spec).
version
Package version holds the build-time version variable injected via ldflags for the gtb binary.
Package version holds the build-time version variable injected via ldflags for the gtb binary.
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.
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: PATH/executable resolution with install-instruction hints (GracefulGetPath) and terminal-interactivity detection (IsInteractive).
Package utils provides small shared utility functions used across the GTB framework: PATH/executable resolution with install-instruction hints (GracefulGetPath) and 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.
test
e2e/support
Package support provides shared test harness helpers for E2E/BDD tests.
Package support provides shared test harness helpers for E2E/BDD tests.

Jump to

Keyboard shortcuts

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