dyalpm

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Jan 22, 2026 License: MIT Imports: 11 Imported by: 0

README

dyalpm

A Go wrapper for the Arch Linux Package Manager (ALPM) library using purego.

Features

  • Lazy Loading: Functions are loaded and registered only when needed
  • Type-Safe Interfaces: Clean Go interfaces for all ALPM operations
  • Maintainable Structure: Well-organized codebase with clear separation of concerns
  • Error Handling: Comprehensive error types matching ALPM error codes

Requirements

  • Go 1.21 or later
  • libalpm.so.15 (Arch Linux package manager library)
  • Linux system with ALPM installed

Installation

go get github.com/Jguer/dyalpm

Usage

Basic Example
package main

import (
	"fmt"
	"log"

	alpm "github.com/Jguer/dyalpm"
)

func main() {
	// Initialize ALPM handle
	handle, err := alpm.Initialize("/", "/var/lib/pacman")
	if err != nil {
		log.Fatal(err)
	}
	defer handle.Release()

	// Get local database
	localDB, err := handle.LocalDB()
	if err != nil {
		log.Fatal(err)
	}

	// Get a package
	pkg := localDB.Pkg("pacman")
	if pkg == nil {
		log.Fatal(err)
	}

	fmt.Printf("Package: %s\n", pkg.Name())
	fmt.Printf("Version: %s\n", pkg.Version())
	fmt.Printf("Description: %s\n", pkg.Description())
}
Working with Sync Databases
// List registered sync databases
syncDBs, err := handle.SyncDBs()
if err != nil {
	log.Fatal(err)
}

for _, db := range syncDBs {
	fmt.Printf("%s\n", db.Name())
}
Transactions
// Create a transaction
trans := alpm.NewTransaction(handle)

// Initialize transaction
err := trans.Init(0)
if err != nil {
	log.Fatal(err)
}
defer trans.Release()

// Add a package to install
pkg, _ := syncDB.GetPkg("vim")
err = trans.AddPkg(pkg)
if err != nil {
	log.Fatal(err)
}

// Prepare the transaction
missing, err := trans.Prepare()
if err != nil {
	log.Fatal(err)
}

if len(missing) > 0 {
	fmt.Println("Missing dependencies:")
	for _, dep := range missing {
		fmt.Printf("  %s requires %s\n", dep.GetTarget(), dep.GetDepend().GetName())
	}
}

// Commit the transaction
conflicts, err := trans.Commit()
if err != nil {
	log.Fatal(err)
}

if len(conflicts) > 0 {
	fmt.Println("File conflicts detected!")
}

Lazy Loading

All C functions are loaded lazily - they are only resolved from the library when first needed. This improves startup time and allows the library to work even if some functions are unavailable.

Error Handling

Errors are represented using the errors.Errno type which matches ALPM's error codes. You can check for specific errors:

if errno := handle.Errno(); errno != errors.ErrOK {
	fmt.Printf("Error: %s\n", handle.StrError(errno))
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidDatabase          = errors.New("invalid database")
	ErrInvalidPackage           = errors.New("invalid package")
	ErrInvalidGroup             = errors.New("invalid group")
	ErrInvalidHandle            = errors.New("invalid handle")
	ErrPackageNotFound          = errors.New("package not found")
	ErrGroupNotFound            = errors.New("group not found")
	ErrDatabaseUpdateFailed     = errors.New("database update failed")
	ErrDatabaseUnregisterFailed = errors.New("database unregister failed")
	ErrTransactionInitFailed    = errors.New("transaction init failed")
	ErrTransactionPrepareFailed = errors.New("transaction prepare failed")
	ErrTransactionCommitFailed  = errors.New("transaction commit failed")
	ErrTransactionReleaseFailed = errors.New("transaction release failed")
	ErrAddPackageFailed         = errors.New("add package failed")
	ErrRemovePackageFailed      = errors.New("remove package failed")
	ErrSysupgradeFailed         = errors.New("sysupgrade failed")
	ErrPackageFreeFailed        = errors.New("package free failed")
	ErrPackageLoadFailed        = errors.New("package load failed")
	ErrInvalidDependency        = errors.New("invalid dependency")
)

Functions

func ComputeMD5Sum

func ComputeMD5Sum(filename string) (string, error)

ComputeMD5Sum computes the MD5 sum of a file

func ComputeSHA256Sum

func ComputeSHA256Sum(filename string) (string, error)

ComputeSHA256Sum computes the SHA256 sum of a file

func VerCmp

func VerCmp(v1, v2 string) int

VerCmp compares two version strings according to libalpm version comparison rules. Returns <0 if v1 < v2, 0 if v1 == v2, >0 if v1 > v2.

func Version

func Version() string

Version returns the library version string

Types

type Backup

type Backup interface {
	Name() string
	Hash() string
}

Backup represents a backup file

type CapabilitiesMask

type CapabilitiesMask int

CapabilitiesMask represents the library capabilities bitmask

const (
	CapNLS        CapabilitiesMask = 1 << 0
	CapDownloader CapabilitiesMask = 1 << 1
	CapSignatures CapabilitiesMask = 1 << 2
)

func Capabilities

func Capabilities() (CapabilitiesMask, error)

Capabilities returns the library capabilities

type Conflict

type Conflict interface {
	GetPackage1() string
	GetPackage2() string
	GetReason() Dependency
	Free()
}

Conflict represents a package conflict

type Database

type Database interface {
	Name() string
	Pkg(name string) Package
	PkgCache() PackageIterator
	Search(needles []string) PackageIterator
	SetServers(servers []string) error
	SetUsage(usage int) error
}

Database represents an ALPM database (minimal surface used by yay).

type DepMissing

type DepMissing interface {
	GetTarget() string
	GetDepend() Dependency
	GetCausingPkg() string
	Free()
}

DepMissing represents a missing dependency

type DepMod

type DepMod int

DepMod represents dependency version comparison mode

const (
	DepModAny DepMod = iota + 1
	DepModEQ
	DepModGE
	DepModLE
	DepModGT
	DepModLT
)

type Depend

type Depend struct {
	Name        string
	Version     string
	Description string
	NameHash    uint64
	Mod         DepMod
}

Depend is a value type representation of a dependency for consumer code.

func (Depend) String

func (d Depend) String() string

String returns the computed string representation of the dependency.

type Dependency

type Dependency interface {
	GetName() string
	GetVersion() string
	GetMod() DepMod
	ComputeString() string
	Free()
}

Dependency represents a package dependency

func DepFromString

func DepFromString(depstring string) (Dependency, error)

DepFromString creates a dependency from a string

type DownloadCallback

type DownloadCallback func(ev DownloadEvent)

DownloadCallback corresponds to alpm_cb_download, with decoded data when possible.

type DownloadCompletedData

type DownloadCompletedData struct {
	Total  int64
	Result int32
}

type DownloadEvent

type DownloadEvent struct {
	Filename string
	Type     DownloadEventType
	Data     DownloadEventData
	RawData  uintptr
}

DownloadEvent is passed to DownloadCallback.

type DownloadEventData

type DownloadEventData interface {
	// contains filtered or unexported methods
}

DownloadEventData is an optional decoded view of the download event payload.

type DownloadEventType

type DownloadEventType int32

DownloadEventType corresponds to alpm_download_event_type_t.

const (
	DownloadInit      DownloadEventType = 0 // ALPM_DOWNLOAD_INIT
	DownloadProgress  DownloadEventType = 1 // ALPM_DOWNLOAD_PROGRESS
	DownloadRetry     DownloadEventType = 2 // ALPM_DOWNLOAD_RETRY
	DownloadCompleted DownloadEventType = 3 // ALPM_DOWNLOAD_COMPLETED
)

type DownloadInitData

type DownloadInitData struct {
	Optional bool
}

type DownloadProgressData

type DownloadProgressData struct {
	Downloaded int64
	Total      int64
}

type DownloadRetryData

type DownloadRetryData struct {
	Resume bool
}

type Event

type Event struct {
	Type int32
	Ptr  uintptr
}

Event is a minimal wrapper around alpm_event_t*. For advanced use, consult alpm.h and decode based on Type and Ptr.

type EventCallback

type EventCallback func(ev Event)

EventCallback corresponds to alpm_cb_event.

type FetchCallback

type FetchCallback func(url string, localpath string, force bool) int

FetchCallback corresponds to alpm_cb_fetch. Return values: 0 success, 1 up-to-date, -1 error.

type File

type File interface {
	Name() string
	Size() int64
	Mode() uint32
}

File represents a file in a package

type FileConflict

type FileConflict interface {
	GetTarget() string
	GetType() FileConflictType
	GetFile() string
	GetCTarget() string
	Free()
}

FileConflict represents a file conflict

type FileConflictType

type FileConflictType int

FileConflictType represents the type of file conflict

const (
	FileConflictTarget     FileConflictType = 1
	FileConflictFilesystem FileConflictType = 2
)

type Group

type Group interface {
	GetName() string
	GetPackages() ([]Package, error)
}

Group represents a package group

type Handle

type Handle interface {
	// Release releases the handle and cleans up resources
	Release() error

	LocalDB() (Database, error)
	SyncDBs() ([]Database, error)
	SyncDBListByDBName(name string) ([]Database, error)
	SyncDBByName(name string) (Database, error)

	// Transaction methods
	TransInit(flags TransactionFlag) error
	TransRelease() error
	SyncSysupgrade(enableDowngrade bool) error
	TransGetAdd() PackageIterator

	// RegisterSyncDB registers a sync database
	RegisterSyncDB(name string, siglevel int) (Database, error)

	// Root returns the root path
	Root() string

	// DBPath returns the database path
	DBPath() string

	// Errno returns the current error code
	Errno() dyerrors.Errno

	// StrError returns the error string for an error code
	StrError(errno dyerrors.Errno) string

	// Options
	SetLogFile(path string) error
	LogFile() string
	SetGPGDir(path string) error
	GPGDir() string
	SetUseSyslog(enable bool) error
	UseSyslog() bool
	SetCheckSpace(enable bool) error
	CheckSpace() bool
	SetDBExt(ext string) error
	DBExt() string
	SetDefaultSigLevel(level int) error
	DefaultSigLevel() int
	SetLocalFileSigLevel(level int) error
	LocalFileSigLevel() int
	SetRemoteFileSigLevel(level int) error
	RemoteFileSigLevel() int
	SetParallelDownloads(num int) error
	ParallelDownloads() int

	// Architecture
	Architectures() ([]string, error)
	SetArchitectures(archs []string) error
	AddArchitecture(arch string) error
	RemoveArchitecture(arch string) error

	// List Options
	CacheDirs() ([]string, error)
	SetCacheDirs(dirs []string) error
	AddCacheDir(dir string) error
	RemoveCacheDir(dir string) error

	HookDirs() ([]string, error)
	SetHookDirs(dirs []string) error
	AddHookDir(dir string) error
	RemoveHookDir(dir string) error

	NoUpgrades() ([]string, error)
	SetNoUpgrades(paths []string) error
	AddNoUpgrade(path string) error
	RemoveNoUpgrade(path string) error
	MatchNoUpgrade(path string) (int, error)

	NoExtracts() ([]string, error)
	SetNoExtracts(paths []string) error
	AddNoExtract(path string) error
	RemoveNoExtract(path string) error
	MatchNoExtract(path string) (int, error)

	IgnorePkgs() ([]string, error)
	SetIgnorePkgs(pkgs []string) error
	AddIgnorePkg(pkg string) error
	RemoveIgnorePkg(pkg string) error

	IgnoreGroups() ([]string, error)
	SetIgnoreGroups(groups []string) error
	AddIgnoreGroup(group string) error
	RemoveIgnoreGroup(group string) error

	OverwriteFiles() ([]string, error)
	SetOverwriteFiles(globs []string) error
	AddOverwriteFile(glob string) error
	RemoveOverwriteFile(glob string) error

	SetSandboxUser(user string) error
	SandboxUser() string
	SetDisableDLTimeout(disable bool) error
	SetDisableSandbox(disable bool) error

	// LoadPackage loads a package from a file
	LoadPackage(filename string, full bool, siglevel int) (Package, error)

	// DB Management
	UnregisterAllSyncDBs() error

	// Utils
	LogAction(prefix, message string) error
	Unlock() error
	FetchPkgURL(url string) (string, error)
	FindGroupPkgs(dbs []Database, name string) ([]Package, error)
	ExtractKeyID(identifier string, sig []byte) ([]string, error)
	InterruptTransaction() error
	SandboxSetupChild(user, dir string) error

	// Assume Installed
	AssumeInstalled() ([]Dependency, error)
	SetAssumeInstalled(deps []Dependency) error
	AddAssumeInstalled(dep Dependency) error
	RemoveAssumeInstalled(dep Dependency) error

	// Dependency Resolution
	CheckDeps(pkgs []Package, remPkgs []Package, upgradePkgs []Package, reverseDeps bool) ([]DepMissing, error)
	CheckConflicts(pkgs []Package) ([]Conflict, error)
	FindDBSatisfier(dbs []Database, depstring string) Package

	// Callbacks (raw pointers)
	//
	// NOTE: libalpm's log callback (`alpm_cb_log`) uses a `va_list`, which cannot be
	// safely bridged to a Go function without a C shim. This wrapper therefore
	// exposes logcb as raw pointers only.
	LogCallback() (cb uintptr, ctx uintptr)
	SetLogCallback(cb uintptr, ctx uintptr) error

	DownloadCallback() (cb uintptr, ctx uintptr)
	SetDownloadCallback(cb uintptr, ctx uintptr) error
	SetDownloadCallbackFunc(cb DownloadCallback) error

	FetchCallback() (cb uintptr, ctx uintptr)
	SetFetchCallback(cb uintptr, ctx uintptr) error
	SetFetchCallbackFunc(cb FetchCallback) error

	EventCallback() (cb uintptr, ctx uintptr)
	SetEventCallback(cb uintptr, ctx uintptr) error
	SetEventCallbackFunc(cb EventCallback) error

	QuestionCallback() (cb uintptr, ctx uintptr)
	SetQuestionCallback(cb uintptr, ctx uintptr) error
	SetQuestionCallbackFunc(cb QuestionCallback) error

	ProgressCallback() (cb uintptr, ctx uintptr)
	SetProgressCallback(cb uintptr, ctx uintptr) error
	SetProgressCallbackFunc(cb ProgressCallback) error
}

Handle represents an ALPM handle

func Initialize

func Initialize(root, dbpath string) (Handle, error)

Initialize creates a new ALPM handle

type LogLevel

type LogLevel uint

LogLevel represents logging level

const (
	LogError   LogLevel = 1
	LogWarning LogLevel = 1 << 1
	LogDebug   LogLevel = 1 << 2
	LogFunc    LogLevel = 1 << 3
)

type Package

type Package interface {
	Name() string
	Version() string
	Description() string
	Architecture() string
	Size() int64
	ISize() int64
	DB() Database
	Depends() []Depend
	Provides() []Depend
	OptionalDepends() []Depend
	Groups() []string
	BuildDate() time.Time
	Reason() PkgReason
	Base() string
	ShouldIgnore() bool
}

Package represents an ALPM package (minimal surface used by yay).

func FindSatisfier

func FindSatisfier(pkgs []Package, depstring string) Package

FindSatisfier finds a package that satisfies a dependency in a list of packages

func PkgFind

func PkgFind(pkgs []Package, name string) Package

PkgFind finds a package in a list by name

type PackageIterator

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

PackageIterator provides lazy iteration over an ALPM package list.

func (PackageIterator) Collect

func (it PackageIterator) Collect() []Package

Collect returns all packages in the iterator as a slice.

func (PackageIterator) FindSatisfier

func (it PackageIterator) FindSatisfier(depstring string) (Package, error)

FindSatisfier finds the first package satisfying a depstring.

func (PackageIterator) ForEach

func (it PackageIterator) ForEach(fn func(Package) error) error

ForEach iterates over packages lazily. If the underlying list must be freed, it will be freed after iteration.

func (PackageIterator) SortBySize

func (it PackageIterator) SortBySize() []Package

SortBySize returns packages sorted by install size (descending).

type PkgFrom

type PkgFrom int

PkgFrom represents where the package came from

const (
	PkgFromFile    PkgFrom = 1
	PkgFromLocalDB PkgFrom = 2
	PkgFromSyncDB  PkgFrom = 3
)

type PkgReason

type PkgReason int

PkgReason represents why the package was installed

const (
	PkgReasonExplicit PkgReason = 0
	PkgReasonDepend   PkgReason = 1
	PkgReasonUnknown  PkgReason = 2
)

type PkgValidation

type PkgValidation int

PkgValidation represents package validation status

const (
	PkgValidationUnknown   PkgValidation = 0
	PkgValidationNone      PkgValidation = (1 << 0)
	PkgValidationMD5Sum    PkgValidation = (1 << 1)
	PkgValidationSHA256Sum PkgValidation = (1 << 2)
	PkgValidationSignature PkgValidation = (1 << 3)
)

type ProgressCallback

type ProgressCallback func(progress int32, pkg string, percent int, howmany uint64, current uint64)

ProgressCallback corresponds to alpm_cb_progress.

type Question

type Question struct {
	Type int32
	Ptr  uintptr
}

Question is a minimal wrapper around alpm_question_t*. You can generally answer by setting the second field of the union (an int) using SetAnswerInt, since all question structs begin with (type, answer/int).

func (Question) SetAnswerInt

func (q Question) SetAnswerInt(answer int)

SetAnswerInt sets the question's "answer" field. The meaning depends on q.Type.

type QuestionAny

type QuestionAny struct {
	Question Question
}

QuestionAny is a wrapper for question callback data (go-alpm/v2 compatibility)

func (QuestionAny) QuestionInstallIgnorepkg

func (qa QuestionAny) QuestionInstallIgnorepkg() (*QuestionInstallIgnorepkg, error)

QuestionInstallIgnorepkg returns a QuestionInstallIgnorepkg if this is an install-ignorepkg question

func (QuestionAny) QuestionSelectProvider

func (qa QuestionAny) QuestionSelectProvider() (*QuestionSelectProvider, error)

QuestionSelectProvider returns a QuestionSelectProvider if this is a select-provider question

type QuestionCallback

type QuestionCallback func(q Question)

QuestionCallback corresponds to alpm_cb_question.

type QuestionInstallIgnorepkg

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

QuestionInstallIgnorepkg is for handling install-ignorepkg questions

func (*QuestionInstallIgnorepkg) SetInstall

func (qi *QuestionInstallIgnorepkg) SetInstall(install bool)

SetInstall sets whether to install the ignored package

type QuestionSelectProvider

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

QuestionSelectProvider is for handling select-provider questions

func (*QuestionSelectProvider) Dep

func (qp *QuestionSelectProvider) Dep() string

Dep returns the dependency string being resolved

func (*QuestionSelectProvider) Providers

Providers returns the list of provider packages

func (*QuestionSelectProvider) SetUseIndex

func (qp *QuestionSelectProvider) SetUseIndex(index int)

SetUseIndex sets which provider index to use (1-based)

type SigList

type SigList struct {
	Results []SigResult
}

SigList represents a list of signature results

type SigResult

type SigResult struct {
	KeyID    string
	Status   SigStatus
	Validity SigValidity
}

SigResult represents a single signature result

type SigStatus

type SigStatus int

SigStatus represents the status of a signature

const (
	SigStatusValid SigStatus = iota
	SigStatusInvalid
	SigStatusSigExpired
	SigStatusKeyExpired
	SigStatusKeyUnknown
	SigStatusKeyDisabled
	SigStatusKeyRevoked
)

type SigValidity

type SigValidity int

SigValidity represents the validity of a signature

const (
	SigValidityFull SigValidity = iota
	SigValidityMarginal
	SigValidityNever
	SigValidityUnknown
)

type Transaction

type Transaction interface {
	// Init initializes the transaction
	Init(flags TransactionFlag) error

	// Prepare prepares the transaction
	Prepare() ([]DepMissing, error)

	// Commit commits the transaction
	Commit() ([]FileConflict, error)

	// Release releases the transaction
	Release() error

	// AddPkg adds a package to the transaction
	AddPkg(pkg Package) error

	// RemovePkg removes a package from the transaction
	RemovePkg(pkg Package) error

	// SyncSysupgrade adds packages to upgrade to the transaction
	SyncSysupgrade(enableDowngrade bool) error

	// GetFlags returns the transaction flags
	GetFlags() TransactionFlag

	// GetAdd returns the list of packages to be added
	GetAdd() ([]Package, error)

	// GetRemove returns the list of packages to be removed
	GetRemove() ([]Package, error)
}

Transaction represents an ALPM transaction

func NewTransaction

func NewTransaction(h Handle) Transaction

NewTransaction creates a new transaction for the given handle

type TransactionFlag

type TransactionFlag int

TransactionFlag represents transaction flags

const (
	TransFlagNoDeps       TransactionFlag = 1
	TransFlagNoSave       TransactionFlag = 1 << 2
	TransFlagNoDepVersion TransactionFlag = 1 << 3
	TransFlagCascade      TransactionFlag = 1 << 4
	TransFlagRecurse      TransactionFlag = 1 << 5
	TransFlagDBOnly       TransactionFlag = 1 << 6
	TransFlagNoHooks      TransactionFlag = 1 << 7
	TransFlagAllDeps      TransactionFlag = 1 << 8
	TransFlagDownloadOnly TransactionFlag = 1 << 9
	TransFlagNoScriptlet  TransactionFlag = 1 << 10
	TransFlagNoConflicts  TransactionFlag = 1 << 11
	TransFlagNeeded       TransactionFlag = 1 << 13
	TransFlagAllExplicit  TransactionFlag = 1 << 14
	TransFlagUnneeded     TransactionFlag = 1 << 15
	TransFlagRecurseAll   TransactionFlag = 1 << 16
	TransFlagNoLock       TransactionFlag = 1 << 17
)

type Usage

type Usage int

Usage type for database usage flags

const (
	UsageSync    Usage = 1 << 0
	UsageSearch  Usage = 1 << 1
	UsageInstall Usage = 1 << 2
	UsageUpgrade Usage = 1 << 3
	UsageAll     Usage = (1 << 4) - 1
)

type Validation

type Validation int

Validation represents package validation status

Directories

Path Synopsis
internal
lib

Jump to

Keyboard shortcuts

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