godeps

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Aug 23, 2026 License: MIT Imports: 19 Imported by: 0

README

godeps

Embeddable, zero-token external binary dependency manager and self-update library for Go CLI applications.

godeps enables Go command-line tools to declare external binary prerequisites (such as yt-dlp, ffmpeg, or custom CLI helpers), verify version constraints across SemVer and CalVer, auto-install missing/outdated binaries into managed application directories without GitHub API rate limits, and sanitize error outputs from external processes.


What It Does

  • Declarative Prerequisites: Declare required external CLI tools with minimum versions and install strategies.
  • Multi-Format Version Checking: Compares standard SemVer (1.4.0), CalVer (2024.08.01), and development builds (dev, git-master), stripping tool output banners automatically.
  • Managed Directory & Runtime PATH Injection: Downloads binaries into isolated user data directories ($XDG_DATA_HOME/<app>/bin / ~/.local/share/<app>/bin) and prepends the directory to the runtime process $PATH.
  • Rate-Limit-Free GitHub Release Resolution: Resolves latest releases via HTTP HEAD redirect headers without consuming GitHub API rate limits.
  • Built-in Archive Extractors: Unpacks .tar.gz, .zip, and raw executable files with automatic permission management (0755).
  • External Stderr Sanitizer: Strips raw multiline Python tracebacks, Go panics, and Node.js stack frames, surfacing clean error messages.
  • In-Place Self-Updates: Upgrades the running CLI application directly from GitHub release assets.
  • Agent-Ready & Safe Prompts: Automatically disables interactive prompts when AGENT=1 is set, and defaults interactive prompts to [y/N] rejection on Enter/EOF.

Installation

go get github.com/alexgorbatchev/godeps

Quick Start

1. Declare Dependencies and Ensure at Startup
package main

import (
	"context"
	"log"

	"github.com/alexgorbatchev/godeps"
)

var depsManager = godeps.New(godeps.Config{
	AppName: "mycli",
	Dependencies: []godeps.Dependency{
		{
			Name:       "fetch-track",
			MinVersion: "1.4.0",
			InstallURL: "https://github.com/alexgorbatchev/fetch-track-cli",
			Installer:  godeps.GitHubReleaseGoBinary("alexgorbatchev", "fetch-track-cli", "fetch-track"),
		},
		{
			Name:       "yt-dlp",
			MinVersion: "2024.08.01",
			InstallURL: "https://github.com/yt-dlp/yt-dlp",
			Installer:  godeps.YtDlp(),
		},
		{
			Name:       "ffmpeg",
			MinVersion: "4.4",
			InstallURL: "https://ffmpeg.org/download.html",
			VersionArgs: []string{"-version"},
			Installer:  godeps.SystemPackageManager("ffmpeg"),
		},
	},
})

func main() {
	ctx := context.Background()

	// Injects ~/.local/share/mycli/bin to process PATH and verifies all prerequisites
	if err := depsManager.Ensure(ctx, godeps.EnsureOptions{
		AutoInstall: false, // Set true to bypass interactive [y/N] prompt
	}); err != nil {
		log.Fatalf("Prerequisites error: %v", err)
	}

	// Dependencies are operational and available in PATH
}
2. Verify Dependencies and Print Reports
reports, err := depsManager.Verify(ctx)
for _, r := range reports {
	if r.Satisfied {
		fmt.Println("OK:", r.Summary())
	} else {
		fmt.Println("FAIL:", r.Summary())
	}
}
3. In-Place Self-Upgrade
// Upgrades the current executable to the latest release on GitHub
newVersion, err := godeps.UpgradeSelf(ctx, "alexgorbatchev", "mycli", "1.0.0")
if err != nil {
	log.Fatalf("Self-update failed: %v", err)
}
fmt.Printf("Upgraded to version %s\n", newVersion)
4. Clean Stderr / Stack-Trace Sanitization
cleanError := godeps.SanitizeStderr(rawStderrOutput)

Built-In Installer Strategies

Strategy Description
godeps.GitHubReleaseGoBinary(owner, repo, binName) Downloads .tar.gz (Linux/macOS) or .zip (Windows) release assets from GitHub and extracts binName.
godeps.YtDlp() Downloads standalone OS/arch-specific binaries (yt-dlp_macos, yt-dlp_linux, yt-dlp_linux_aarch64, yt-dlp.exe) containing embedded Python runtimes.
godeps.SystemPackageManager(packageName) Invokes host package managers (brew, apt-get, pacman, dnf, winget, choco).
godeps.InstallerFunc(fn) Custom installation function implementing func(ctx context.Context, targetDir string) error.

Development

# Run tests with race detection and coverage verification
just test

# Static analysis
just vet

# Format code
just fmt

License

MIT License. See LICENSE for details.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CompareVersions

func CompareVersions(actual, min string) error

CompareVersions checks if actual meets or exceeds the minimum version requirement min. Returns nil if satisfied, or an error if actual is below min.

func DefaultRunner

func DefaultRunner(ctx context.Context, name string, args ...string) ([]byte, error)

DefaultRunner is the default CommandRunner using os/exec with sanitized stderr errors.

func DefaultVersionParser

func DefaultVersionParser(name, output string) string

DefaultVersionParser extracts a clean version string from raw tool output banners.

func DownloadAndExtractGoBinary

func DownloadAndExtractGoBinary(ctx context.Context, owner, repo, binName, targetDir string) error

DownloadAndExtractGoBinary downloads a release asset from GitHub, extracts it, and saves the binary.

func DownloadDirectBinary

func DownloadDirectBinary(ctx context.Context, downloadURL, binName, targetDir string) error

DownloadDirectBinary downloads a single executable file and writes it to targetDir/binName.

func EnsureManagedBinDir

func EnsureManagedBinDir(appName string) (string, error)

EnsureManagedBinDir creates the application's managed bin directory if not present and returns its path.

func GetManagedBinDir

func GetManagedBinDir(appName string) (string, error)

GetManagedBinDir returns the path to the application's isolated binary directory following XDG standards.

func InitManagedPath

func InitManagedPath(appName string) error

InitManagedPath ensures the managed bin directory is prepended to the current process PATH.

func InstallPackage

func InstallPackage(ctx context.Context, packageName string, runner CommandRunner) error

InstallPackage attempts to install a system package using host package managers (brew, apt, pacman, etc.).

func InstallYtDlp

func InstallYtDlp(ctx context.Context, targetDir string) error

InstallYtDlp downloads the OS/architecture-specific standalone yt-dlp binary into targetDir.

func InstallYtDlpForPlatform

func InstallYtDlpForPlatform(ctx context.Context, goos, goarch, targetDir string) error

InstallYtDlpForPlatform downloads the standalone yt-dlp binary for a specific OS and architecture.

func IsAgentMode

func IsAgentMode() bool

IsAgentMode checks if AGENT=1 or AGENT=true is set in the environment.

func ResolveLatestTag

func ResolveLatestTag(ctx context.Context, owner, repo string) (string, error)

ResolveLatestTag queries the latest release tag for a GitHub repository without using the GitHub API rate limits.

func ResolveLatestTagWithBaseURL

func ResolveLatestTagWithBaseURL(ctx context.Context, baseURL, owner, repo string) (string, error)

ResolveLatestTagWithBaseURL queries the latest release tag for a repository from a custom base URL.

func SanitizeStderr

func SanitizeStderr(stderr string) string

SanitizeStderr cleans raw stderr output from external CLI tools by stripping multiline stack traces (Python tracebacks, Go panics, Node traces, etc.) and extracting the actual error description.

func UpdateYtDlp

func UpdateYtDlp(ctx context.Context, runner CommandRunner, targetDir string) error

UpdateYtDlp attempts native yt-dlp -U update first, falling back to direct download.

func UpgradeSelf

func UpgradeSelf(ctx context.Context, owner, repo, currentVersion string) (string, error)

UpgradeSelf checks for a newer GitHub release of the running application and replaces the executable in-place.

func UpgradeSelfToPath

func UpgradeSelfToPath(ctx context.Context, owner, repo, currentVersion, destPath string) (string, error)

UpgradeSelfToPath downloads the latest release binary for owner/repo and replaces the binary at destPath.

Types

type Cache

type Cache interface {
	Get(key string, target any) bool
	Put(key string, val any) error
	Delete(key string) error
}

Cache defines optional key-value caching for dependency verification.

type CommandRunner

type CommandRunner func(ctx context.Context, name string, args ...string) ([]byte, error)

CommandRunner executes an external command.

type Config

type Config struct {
	AppName      string
	Dependencies []Dependency
	Runner       CommandRunner
	Cache        Cache
}

Config defines the setup for a Manager instance.

type Dependency

type Dependency struct {
	Name         string
	MinVersion   string
	InstallURL   string
	VersionArgs  []string
	ParseVersion func(name, output string) string
	Installer    Installer
}

Dependency defines a prerequisite tool requirement.

type DependencyReport

type DependencyReport struct {
	Name            string `json:"name"`
	MinVersion      string `json:"minVersion"`
	DetectedVersion string `json:"detectedVersion"`
	Installed       bool   `json:"installed"`
	Satisfied       bool   `json:"satisfied"`
	Error           string `json:"error,omitempty"`
}

DependencyReport summarizes the status of a checked dependency.

func (DependencyReport) Summary

func (r DependencyReport) Summary() string

Summary returns a human-readable summary of the dependency state.

type EnsureOptions

type EnsureOptions struct {
	AutoInstall bool
}

EnsureOptions configures the Ensure execution.

type Installer

type Installer interface {
	Install(ctx context.Context, targetDir string) error
	Update(ctx context.Context, targetDir string) error
}

Installer defines how a dependency is installed and updated.

func GitHubReleaseGoBinary

func GitHubReleaseGoBinary(owner, repo, binName string) Installer

GitHubReleaseGoBinary creates an Installer for standard Go binary releases on GitHub (tar.gz/zip).

func SystemPackageManager

func SystemPackageManager(packageName string) Installer

SystemPackageManager creates an Installer that uses the host system package manager (brew, apt, pacman, etc.).

func YtDlp

func YtDlp() Installer

YtDlp creates an Installer for standalone yt-dlp executables with bundled Python runtime.

type InstallerFunc

type InstallerFunc func(ctx context.Context, targetDir string) error

InstallerFunc allows using plain functions as an Installer.

func (InstallerFunc) Install

func (f InstallerFunc) Install(ctx context.Context, targetDir string) error

func (InstallerFunc) Update

func (f InstallerFunc) Update(ctx context.Context, targetDir string) error

type Manager

type Manager struct {
	// contains filtered or unexported fields
}

Manager orchestrates dependency checks, managed PATH injection, and installations.

func New

func New(cfg Config) *Manager

New creates a new Manager instance.

func (*Manager) Ensure

func (m *Manager) Ensure(ctx context.Context, opts ...EnsureOptions) error

Ensure checks dependencies, injects managed PATH, and handles auto-installation prompts.

func (*Manager) Install

func (m *Manager) Install(ctx context.Context, depName string) error

Install installs a single dependency by name using its declared Installer.

func (*Manager) InstallUnsatisfied

func (m *Manager) InstallUnsatisfied(ctx context.Context) ([]string, error)

InstallUnsatisfied installs all currently unsatisfied dependencies.

func (*Manager) Update

func (m *Manager) Update(ctx context.Context, depName string) error

Update updates a single dependency by name using its declared Installer.

func (*Manager) UpdateAll

func (m *Manager) UpdateAll(ctx context.Context) ([]string, error)

UpdateAll updates all declared dependencies.

func (*Manager) Verify

func (m *Manager) Verify(ctx context.Context) ([]DependencyReport, error)

Verify runs version checks across all declared dependencies.

Jump to

Keyboard shortcuts

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