pkg

package
v0.5.3 Latest Latest
Warning

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

Go to latest
Published: Jul 2, 2026 License: MIT Imports: 15 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Package Manager SDK

A Go library for driving Linux package managers (apt, dnf, pacman, zypper, flatpak) through a single Manager interface built over an injected exec.Runner — no global escalation state, fully unit-testable with exectest.FakeRunner (no host, no sudo, no container).

Installation

import (
    "github.com/manchtools/power-manage-sdk/pkg"
    "github.com/manchtools/power-manage-sdk/sys/exec"
)

Quick Start

// Build a Runner for the host's escalation backend, then a Manager for a backend.
r, err := exec.NewRunner(exec.Sudo) // or exec.Doas / exec.Direct (already root)
if err != nil {
    log.Fatal(err)
}
m, err := pkg.New(pkg.Apt, r)
if err != nil {
    log.Fatal(err)
}

ctx := context.Background()

// Install latest
err = m.Install(ctx, pkg.InstallOptions{}, "nginx", "curl")

// Install a pinned version (exactly one package when Version is set)
err = m.Install(ctx, pkg.InstallOptions{Version: "1.24.0-1"}, "nginx")

// Allow a downgrade
err = m.Install(ctx, pkg.InstallOptions{Version: "1.22.0-1", AllowDowngrade: true}, "nginx")

Mutating methods (Install/Remove/Update/Upgrade/Pin/Unpin/Repair/ Autoremove) return error only — a non-zero exit becomes an *exec.CommandError carrying the exit code and stderr (errors.As to inspect). Query methods return typed results.

Choosing a backend

New is pure — it does not probe the host. Use Detect to learn which backends are installed (it lists, in priority order; it never picks):

for _, b := range pkg.Detect(ctx) {
    fmt.Println(b) // "apt", "dnf", "flatpak", ...
}
m, err := pkg.New(pkg.Dnf, r)

An unknown backend or a nil runner is rejected (pkg.ErrUnknownBackend / "runner is required") — fail-closed, no silent default.

Mutations

m.Install(ctx, pkg.InstallOptions{}, "nginx")
m.InstallLocal(ctx, "/var/cache/pm/app.deb", pkg.InstallLocalOptions{}) // a downloaded .deb/.rpm/pacman/flatpak file, deps resolved
m.Remove(ctx, pkg.RemoveOptions{}, "nginx")
m.Remove(ctx, pkg.RemoveOptions{Purge: true}, "nginx") // also delete config/data where supported
m.Update(ctx)                                          // refresh metadata
m.Upgrade(ctx)                                         // full system upgrade (no names)
m.Upgrade(ctx, "nginx", "curl")                        // upgrade specific packages
m.Pin(ctx, "nginx")                                    // hold back from upgrades
m.Unpin(ctx, "nginx")
m.Autoremove(ctx)                                      // remove now-unneeded deps (no-op on zypper)
m.Repair(ctx)                                          // clear stale locks / fix broken state

Reads run unprivileged; mutations escalate through the Runner's backend (sudo -n / doas -n / bare for Direct).

Queries

ver, _ := m.Version(ctx)                 // package-manager tool version
packages, _ := m.List(ctx)               // installed packages
updates, _ := m.ListUpgradable(ctx)      // []PackageUpdate
p, _ := m.Show(ctx, "nginx")             // *Package
info, _ := m.ListVersions(ctx, "nginx")  // *VersionInfo
ok, _ := m.IsInstalled(ctx, "nginx")
v, _ := m.InstalledVersion(ctx, "nginx") // "" if absent
n, _ := m.InstalledCount(ctx)
has, _ := m.HasUpdates(ctx, false)       // true if any update; pass true for security-only (where supported)
pinned, _ := m.IsPinned(ctx, "nginx")
held, _ := m.ListPinned(ctx)
results, _ := m.Search(ctx, "nginx")

Flatpak

New(pkg.Flatpak, r) returns a value that also satisfies FlatpakManager, adding remote (repository) management. Use WithUserScope() to operate on the per-user installation (--user, unprivileged) instead of the system one:

m, _ := pkg.New(pkg.Flatpak, r)                 // system scope (--system, escalated)
mu, _ := pkg.New(pkg.Flatpak, r, pkg.WithUserScope()) // per-user (--user, unprivileged)

if fm, ok := m.(pkg.FlatpakManager); ok {
    fm.AddRemote(ctx, "flathub", "https://dl.flathub.org/repo/flathub.flatpakrepo")
    remotes, _ := fm.ListRemotes(ctx)
    fm.RemoveRemote(ctx, "flathub")
}

AddRemote validates the alias (ValidateRemoteName) and the URL (ValidateRepoBaseURL, https only). Flatpak does not support traditional version pinning, so InstallOptions.Version is validated but ignored for it.

Types

type InstallOptions struct {
    Version        string // pins a single package; requires exactly one name
    AllowDowngrade bool
}

type InstallLocalOptions struct {
    AllowDowngrade bool // install a file older than the installed version
    AllowUnsigned  bool // skip the backend GPG check (dnf --nogpgcheck / zypper
                        // --allow-unsigned-rpm) for an out-of-band-verified file;
                        // secure-default-off. apt/flatpak: no-op; pacman: NOT
                        // honored (pacman -U always enforces SigLevel).
}

type RemoveOptions struct {
    Purge bool // also remove config/data (apt purge / pacman -Rns / flatpak --delete-data)
}

type Package struct {
    Name, Version, Architecture, Description, Status, Repository string
    Size                                                         int64 // bytes
    Pinned                                                       bool
}

type PackageUpdate struct {
    Name, CurrentVersion, NewVersion, Architecture, Repository string
}

type VersionInfo struct {
    Name      string
    Versions  []AvailableVersion
    Installed string
}

Supported Package Managers

Backend Systems Detect binary Pinning
pkg.Apt Debian, Ubuntu, Mint apt-get apt-mark hold/unhold
pkg.Dnf Fedora, RHEL 8+, CentOS Stream dnf dnf versionlock (plugin auto-installed)
pkg.Pacman Arch, Manjaro pacman IgnorePkg in /etc/pacman.conf
pkg.Zypper openSUSE, SLES zypper zypper addlock/removelock
pkg.Flatpak Cross-distro flatpak flatpak mask

Argument-Hardening Validators

Every value that reaches a package-manager argv is validated against its intent before the command runs. Package names and versions are checked inside each method (there is no opt-out). The remaining exported validators are mandatory at the argv boundaries they protect (the agent's executors call them, and positionals are passed after an explicit -- end-of-options separator built with exec.SeparatePositionals, so a flag-shaped value can never be reparsed as an option):

Validator Guards Rule
ValidatePackageName / ValidatePackageNames apt/dnf/pacman/zypper/flatpak names first char alphanumeric, then [a-zA-Z0-9._+:/@~-], ≤256
ValidatePackageVersion <name>=<version> argv cross-distro EVR grammar, empty = "no pin"
ValidateRpmPackageName rpm -q / rpm -e <NAME> (NAME read off a crafted .rpm) first char alphanumeric, then [a-zA-Z0-9._+-], ≤256
ValidateRepoBaseURL dnf baseurl / zypper url / pacman server / flatpak remote URL https only, host required, control-char free (template vars $releasever/$arch allowed). apt is excluded — its security is the gpg-signed Release file.
ValidateGpgKeyRef dnf/zypper gpgkey passed to rpm --import https URL, file:///abs path, or absolute path; no .., no leading -, no http://, no ext::
ValidateRemoteName flatpak remote alias first char alphanumeric, then [a-zA-Z0-9._-], ≤128
ValidateLocalPackagePath InstallLocal file operand (apt-get/dnf/pacman -U/zypper/flatpak install) absolute path (never flag-shaped), no .., no control chars; a space is allowed
ValidateSearchQuery the free-text Search query must not start with - (a search term cannot be ---guarded because dnf5 rejects --), no control chars; empty allowed

In addition, pacman's Pin runs a stricter [a-zA-Z0-9][a-zA-Z0-9._+-]* gate before a name is written to IgnorePkg, blocking config-injection even for names that ValidatePackageName would accept.

A self-discovering test (TestEveryManagerMethodNeutralizesFlagShapedOperands) reflects over the whole Manager surface and fails if any method lets a flag-shaped operand reach argv as an option, so a new method that forgets to validate its operand cannot pass CI.

Testing

Because the Manager is built with an injected Runner, tests pass an exectest.FakeRunner, script command results, and assert on the exact exec.Commands the Manager built (argv, escalation, stdin) — no real package manager is invoked:

f := exectest.New(exec.Direct)
f.Push(exec.Result{Stdout: "..."}, nil)
m, _ := pkg.New(pkg.Apt, f)
m.Install(ctx, pkg.InstallOptions{}, "nginx")
// f.Calls()[0] is the recorded `apt install -y --fix-broken nginx`

Notes

  • Non-interactive mode: apt commands run with DEBIAN_FRONTEND=noninteractive; the C locale (LANG=C/LC_ALL=C) is forced on every command for stable English-only output parsing.
  • Version formats: apt 1.24.0-1ubuntu1, dnf 1.24.0-1.fc39, pacman 1.24.0-1, zypper 1.24.0-1.1. Flatpak addresses bundles by application ID (e.g. org.mozilla.firefox) and has no version pin.
  • Pinning setup: dnf auto-installs python3-dnf-plugin-versionlock on first use; pacman edits /etc/pacman.conf (root). apt/zypper need no setup.

Documentation

Overview

Package pkg provides a uniform package-manager abstraction for Linux.

A Manager is built for an explicit Backend over an injected exec.Runner — the SDK keeps no global escalation state and every Manager is unit-testable with exectest.FakeRunner (no host, no sudo, no container):

r, _ := exec.NewRunner(exec.Sudo)
m, err := pkg.New(pkg.Apt, r)
if err != nil { ... }
if err := m.Install(ctx, pkg.InstallOptions{}, "vim", "git"); err != nil { ... }

Reads (Search/List/Show/IsInstalled/…) run unprivileged; mutations (Install/InstallLocal/Remove/Update/Upgrade/Pin/Unpin/Repair/Autoremove) run through the Runner's privilege backend. Every package-name, version, and local-file-path argument is validated before it can reach argv — there is no opt-out.

Use Detect to discover which backends are installed; it lists and never picks, so the caller decides (a host can have both a native manager and flatpak).

Index

Constants

This section is empty.

Variables

View Source
var ErrSecurityOnlyUnsupported = errors.New("pkg: security-only upgrade not supported by this backend")

ErrSecurityOnlyUnsupported is returned by UpgradeAll when UpgradeOptions. SecurityOnly is set on a backend that has no security-only upgrade path: pacman (a rolling release with no security/non-security distinction) and flatpak (no security channel). Fail-closed: the SDK never silently performs a full upgrade when only security updates were requested.

View Source
var ErrUnknownBackend = errors.New("pkg: unknown package-manager backend")

ErrUnknownBackend is returned by New for a Backend the SDK does not implement (including the zero value). Fail-closed: no silent default.

Functions

func ValidateGpgKeyRef

func ValidateGpgKeyRef(ref string) error

ValidateGpgKeyRef validates a dnf/zypper Gpgkey reference before it reaches `rpm --import`. Accepted iff it is (a) an https URL with a host, (b) a file:// absolute path (file:///… — empty host, no `..`), or (c) a bare absolute filesystem path (no `..`). Everything else is refused: a leading '-' (option injection into `rpm --import`), plaintext http (MITM of the trust anchor itself), rpm's `ext::` external transport (which executes a command), and relative or traversing paths.

func ValidateLocalPackagePath

func ValidateLocalPackagePath(path string) error

ValidateLocalPackagePath validates a filesystem path before it reaches a package manager as the operand of a local-file install (apt-get install <file>, dnf install <file>, pacman -U <file>, zypper install <file>, flatpak install <bundle>). It is NOT a package name, so the package-name grammar does not apply; what matters is that the path cannot masquerade as an option and cannot smuggle a config/log-injecting control character:

  • absolute (a leading '/'): a relative path is ambiguous w.r.t. the privileged process's working directory, and an absolute path can never be flag-shaped. Callers pass a concrete file location (typically a temp file they downloaded and checksum-verified), so this costs them nothing.
  • no ".." segment: defence-in-depth against a traversing path, mirroring ValidateGpgKeyRef.
  • no control characters (incl. NUL, newline, tab) or DEL: a space is left alone (it is argv-safe and legal in a path), but control characters are refused so a crafted path can neither break a log line nor confuse a tool.

Existence is NOT checked: the Manager has no host access (it drives an injected Runner), and a missing file surfaces cleanly as the tool's own non-zero exit. The absolute-path requirement — not a "--" end-of-options separator — is what keeps the path from being read as an option, because some tools (dnf5) reject "--" for their install/search subcommands entirely.

func ValidatePackageName

func ValidatePackageName(name string) error

ValidatePackageName returns a non-nil error when name would be unsafe to pass as a positional argument to any of the supported package managers. Callers MUST invoke this (or ValidatePackageNames) at the top of every public method that accepts a package name, before any exec.CommandContext call.

func ValidatePackageNames

func ValidatePackageNames(names []string) error

ValidatePackageNames runs ValidatePackageName against every entry. Returns the first rejection; does not try to be exhaustive — actions are signed and a rejection here is a caller bug, not an adversarial probe to enumerate.

func ValidatePackageVersion

func ValidatePackageVersion(version string) error

ValidatePackageVersion checks a version string before it lands in `<name>=<version>` (apt) or similar argv constructs. Empty version is treated as "no version pinned" and accepted; any non-empty version must match the cross-distro grammar in validPackageVersion.

func ValidateRemoteName

func ValidateRemoteName(name string) error

ValidateRemoteName returns a non-nil error when name is not a safe flatpak remote alias to pass as an operand to `flatpak install`. A flag-shaped remote (`--from=…`) would otherwise be parsed as an option.

func ValidateRepoBaseURL

func ValidateRepoBaseURL(rawURL string) error

ValidateRepoBaseURL validates a dnf baseurl / zypper url / pacman server. A repository base URL is where the package manager fetches ROOT-installed packages, so it must be https (no http/ftp/file — the transport is the only thing standing between a MITM and arbitrary root code), a real URL with a host, and free of control characters. Package-manager template variables ($releasever, $arch, $basearch) survive url.Parse and are intentionally allowed.

NOTE: apt is deliberately NOT validated through here — apt's security model is the gpg-signed Release file, so an http transport with a trusted key is a legitimate, long-standing configuration.

func ValidateRpmPackageName

func ValidateRpmPackageName(name string) error

ValidateRpmPackageName returns a non-nil error when name is not a safe RPM %{NAME} to pass to `rpm -q`/`rpm -e`. The name a crafted .rpm reports is untrusted; callers MUST validate it before it reaches argv. Mirrors ValidatePackageName / the deb-side validDebPkgName.

func ValidateSearchQuery

func ValidateSearchQuery(query string) error

ValidateSearchQuery guards the free-text query passed to a package-manager search. A search term is not a fixed grammar (it may carry '+', '.', glob characters, etc.), so it is deliberately NOT run through validPackageName; the one thing that must be refused is a value that could be reparsed as an OPTION. A leading '-' is rejected — a search term never legitimately starts with a dash, and a "--" end-of-options separator is NOT portable here (dnf5's `search` subcommand rejects "--"), so validation is the honest defense. Control characters are rejected too. An empty query is allowed (a backend may list everything).

Types

type AvailableVersion

type AvailableVersion struct {
	Version    string
	Repository string
	Size       int64
}

AvailableVersion represents a specific version available for installation.

type Backend

type Backend int

Backend identifies a supported package manager. The zero value is invalid (New rejects it); valid values start at 1.

const (
	// Apt is the Debian/Ubuntu package manager (apt / apt-get / dpkg).
	Apt Backend = iota + 1
	// Dnf is the Fedora/RHEL package manager (dnf / rpm).
	Dnf
	// Pacman is the Arch Linux package manager.
	Pacman
	// Zypper is the openSUSE/SLES package manager (zypper / rpm).
	Zypper
	// Flatpak is the cross-distro application bundle manager.
	Flatpak
)

func Detect

func Detect(ctx context.Context) []Backend

Detect returns the package-manager backends whose primary binary resolves on PATH, in priority order (native managers before flatpak). The result may be empty (no supported manager) or hold several entries (e.g. a native manager plus flatpak). It lists; it never picks — the caller chooses.

func (Backend) String

func (b Backend) String() string

String returns the canonical lowercase backend name.

type FlatpakManager

type FlatpakManager interface {
	Manager
	// AddRemote registers a flatpak remote. name must be a valid remote alias
	// and url an https repository URL.
	AddRemote(ctx context.Context, name, url string) error
	// RemoveRemote deletes a flatpak remote.
	RemoveRemote(ctx context.Context, name string) error
	// ListRemotes returns the configured flatpak remote names.
	ListRemotes(ctx context.Context) ([]string, error)
}

FlatpakManager is the Manager returned by New(Flatpak, …); it adds remote (repository) management, which has no analogue on the native managers. Callers reach it with a type assertion:

if fm, ok := m.(pkg.FlatpakManager); ok { fm.AddRemote(ctx, "flathub", url) }

type InstallLocalOptions

type InstallLocalOptions struct {
	// AllowDowngrade permits installing a package file whose version is lower
	// than the one currently installed. Honored on apt (--allow-downgrades),
	// dnf (retried as an explicit downgrade when the install is rejected) and
	// zypper (--oldpackage). pacman -U downgrades regardless, and a flatpak
	// bundle has no version-ordering concept, so it is a no-op on those two.
	AllowDowngrade bool
	// AllowUnsigned skips the backend's GPG signature check for the local file.
	// It is secure-default-OFF: with the default (false) an unsigned local .rpm
	// is rejected by dnf/zypper. Set it ONLY when the file's authenticity is
	// established out of band — e.g. an HTTPS transport plus a verified SHA256
	// checksum — so the package manager's per-file GPG check is redundant. Per
	// backend:
	//   - dnf:    adds --nogpgcheck
	//   - zypper: adds --allow-unsigned-rpm (per-package; never the global
	//             --no-gpg-checks, which would also drop repo-metadata checks)
	//   - apt:    no-op — a local .deb carries no per-file signature to skip
	//   - pacman: NOT honored — `pacman -U` enforces the repo SigLevel and has no
	//             per-invocation bypass; the install stays signature-checked
	//   - flatpak: no-op — a bundle's signing is not a per-file GPG check
	AllowUnsigned bool
}

InstallLocalOptions configures an InstallLocal call.

type InstallOptions

type InstallOptions struct {
	// Version pins the install to a specific version. When set, exactly one
	// package name must be given (a version applies to a single package).
	Version string
	// AllowDowngrade permits installing a lower version than the one installed.
	AllowDowngrade bool
	// Remote names the flatpak remote to install FROM (e.g. "flathub"). It is
	// honored only by the flatpak backend — where it disambiguates which remote
	// provides the app instead of relying on flatpak's auto-resolution — and is
	// ignored by the native package managers. Empty selects flatpak's default
	// resolution.
	Remote string
}

InstallOptions configures an Install call.

type LocalPackage

type LocalPackage struct {
	Name    string
	Version string
	Arch    string
}

LocalPackage is the identity read out of a LOCAL package file (a .deb, .rpm or pacman package on disk) by Manager.LocalPackageInfo. Name is the canonical package name — validated against the backend's package-name grammar before it is returned, because the value is read out of an attacker-influenced file. Version and Arch are best-effort extra fields (a backend that cannot report one leaves it empty).

type Manager

type Manager interface {
	// Backend reports which package-manager backend this Manager drives.
	Backend() Backend

	// Version returns the package-manager tool version string.
	Version(ctx context.Context) (string, error)
	// Search returns packages whose name/summary matches query.
	Search(ctx context.Context, query string) ([]SearchResult, error)
	// List returns the installed packages.
	List(ctx context.Context) ([]Package, error)
	// ListUpgradable returns packages with an available upgrade.
	ListUpgradable(ctx context.Context) ([]PackageUpdate, error)
	// Show returns detailed information about a single package.
	Show(ctx context.Context, name string) (*Package, error)
	// ListVersions returns the versions available for a package.
	ListVersions(ctx context.Context, name string) (*VersionInfo, error)
	// IsInstalled reports whether name is currently installed.
	IsInstalled(ctx context.Context, name string) (bool, error)
	// LocalPackageInfo reads a package's canonical name (and, where the backend
	// reports them, version and architecture) from a LOCAL package file already on
	// disk — a .deb, .rpm or pacman package — WITHOUT installing it. path must be
	// an absolute filesystem path (ValidateLocalPackagePath). The name a crafted
	// file embeds is untrusted, so it is validated against the backend's
	// package-name grammar before being returned; a flag-shaped or
	// metacharacter-bearing name is rejected. The flatpak backend has no clean
	// local name-introspection command and returns a not-supported error.
	LocalPackageInfo(ctx context.Context, path string) (*LocalPackage, error)
	// InstalledVersion returns the installed version of name, or "" if absent.
	InstalledVersion(ctx context.Context, name string) (string, error)
	// InstalledCount returns the number of installed packages.
	InstalledCount(ctx context.Context) (int, error)
	// HasUpdates reports whether any update is available. When securityOnly is
	// true only security updates are considered (where the backend supports it).
	HasUpdates(ctx context.Context, securityOnly bool) (bool, error)
	// IsPinned reports whether name is held back from upgrades.
	IsPinned(ctx context.Context, name string) (bool, error)
	// ListPinned returns the packages held back from upgrades.
	ListPinned(ctx context.Context) ([]Package, error)

	// Install installs the named packages. opts.Version pins a single package
	// (exactly one name required when set); opts.AllowDowngrade permits a lower
	// version than installed.
	Install(ctx context.Context, opts InstallOptions, packages ...string) (pmexec.Result, error)
	// InstallLocal installs a package from a local file already on disk — a
	// downloaded .deb, .rpm, pacman package, or flatpak bundle — rather than by
	// name from a configured repository, resolving dependencies from the
	// configured repositories where the backend supports it (apt/dnf/zypper/
	// pacman). path must be an ABSOLUTE filesystem path to the package file;
	// fetching and verifying the artifact (https transport, checksum) is the
	// caller's responsibility. opts.AllowDowngrade permits a lower version than
	// the one currently installed; opts.AllowUnsigned skips the backend's GPG
	// check (dnf --nogpgcheck / zypper --allow-unsigned-rpm) for a file whose
	// authenticity is established out of band — secure-default-off.
	InstallLocal(ctx context.Context, path string, opts InstallLocalOptions) (pmexec.Result, error)
	// Remove removes the named packages. opts.Purge also deletes configuration
	// where the backend distinguishes it (apt/pacman/flatpak); elsewhere Purge
	// is equivalent to a plain remove.
	Remove(ctx context.Context, opts RemoveOptions, packages ...string) (pmexec.Result, error)
	// Update refreshes the package metadata/database.
	Update(ctx context.Context) (pmexec.Result, error)
	// Upgrade upgrades the named packages. With NO names it is a no-op (not a
	// full upgrade) — an accidentally-empty list must never upgrade the whole
	// system. Use UpgradeAll for that.
	Upgrade(ctx context.Context, packages ...string) (pmexec.Result, error)
	// UpgradeAll performs a full system upgrade (apt dist-upgrade / dnf upgrade /
	// pacman -Syu / zypper dist-upgrade / flatpak update). With
	// opts.SecurityOnly it upgrades only security updates where the backend
	// supports it (apt/dnf/zypper); pacman and flatpak return
	// ErrSecurityOnlyUnsupported.
	UpgradeAll(ctx context.Context, opts UpgradeOptions) (pmexec.Result, error)
	// Pin holds the named packages back from upgrades.
	Pin(ctx context.Context, packages ...string) (pmexec.Result, error)
	// Unpin releases the named packages so they upgrade again.
	Unpin(ctx context.Context, packages ...string) (pmexec.Result, error)
	// Repair attempts to fix a wedged package-manager state (stale locks,
	// interrupted transactions, broken dependencies). It runs several recovery
	// commands; the returned Result is that of the final (or first failing) step.
	Repair(ctx context.Context) (pmexec.Result, error)
	// Autoremove removes packages installed only as now-unneeded dependencies.
	// It is a no-op (zero Result, nil error) on backends with no native equivalent.
	Autoremove(ctx context.Context) (pmexec.Result, error)
}

Manager is the uniform package-manager surface. Every method takes a context so the caller controls timeout/cancellation. Query methods return typed results; mutating methods return the command's output (an exec.Result carrying exit code, stdout and stderr) so callers can surface what the package manager actually did, plus an error — a non-zero exit becomes an *exec.CommandError carrying the exit code and stderr while the Result still carries the full stdout/stderr. The Result is populated on both the success and non-zero-exit paths; it is the zero Result only when the command could not be run at all (the error is then a plain runner error) or when the call is a validated no-op (e.g. an empty package list).

func New

func New(b Backend, runner pmexec.Runner, opts ...Option) (Manager, error)

New builds a Manager for backend b driven by runner. A nil runner or an unknown backend is rejected (fail-closed). New is pure — it does not probe the host; use Detect to learn which backends are installed.

type Option

type Option func(*config)

Option customizes a Manager at construction.

func WithUserScope

func WithUserScope() Option

WithUserScope makes a flatpak Manager operate on the per-user installation (--user, unprivileged) instead of the system installation. It has no effect on the native package managers.

type Package

type Package struct {
	Name         string
	Version      string
	Architecture string
	Description  string
	Status       string // installed, available, upgradable, pinned
	Size         int64  // installed size in bytes
	Repository   string
	Pinned       bool // whether the package is pinned (hold)
}

Package represents an installed or available package.

type PackageUpdate

type PackageUpdate struct {
	Name           string
	CurrentVersion string
	NewVersion     string
	Architecture   string
	Repository     string
}

PackageUpdate represents an available update for a package.

type RemoveOptions

type RemoveOptions struct {
	// Purge also removes configuration/data where the backend distinguishes it
	// (apt purge / pacman -Rns / flatpak --delete-data). On backends with no
	// such distinction it is equivalent to a plain remove.
	Purge bool
}

RemoveOptions configures a Remove call.

type SearchResult

type SearchResult struct {
	Name        string
	Version     string
	Description string
	Repository  string
}

SearchResult represents a package search result.

type UpgradeOptions

type UpgradeOptions struct {
	// SecurityOnly restricts the upgrade to security updates. Supported on apt
	// (simulate dist-upgrade, then upgrade only packages from a security suite),
	// dnf (--security) and zypper (patch --category security). pacman and flatpak
	// return ErrSecurityOnlyUnsupported.
	SecurityOnly bool
}

UpgradeOptions configures UpgradeAll.

type VersionInfo

type VersionInfo struct {
	Name      string
	Versions  []AvailableVersion
	Installed string // currently installed version, empty if not installed
}

VersionInfo represents available versions of a package.

Jump to

Keyboard shortcuts

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