pacman

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: Apache-2.0 Imports: 36 Imported by: 2 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

pacman

Part of pkgformat.

Go Reference

A Go library to build, read, index and download Arch Linux packages and repositories, in pure Go. It needs no makepkg, no pacman, no repo-add and no PKGBUILD: a package is described with plain Go structs.

Install

go get github.com/M0Rf30/pkgformat/pacman

Requires Go 1.27 or later.

What it does

Area API
Write .pkg.tar.zst, .xz, .gz Spec, PkgInfo, BuildInfo, Scriptlets, File, ScanDir, Spec.Write, Spec.WriteFile
Read packages ReadPackage, ParsePkgInfo, ParseBuildInfo
Sync databases ReadDB, ReadFileLists, WriteDB, NewDBEntry, DBEntry
Versions and dependencies Vercmp, ParseDependency, Dependency.Allows
Signatures SignDetached, NormalizeSignature, verification through gpg
pacman.conf and mirrorlists ParseConfig, ParseMirrorlist, ParseConfigFile, ExpandServer
Repository client Client: FetchDB, SyncDB, Sync, DownloadPackage
Search and resolution Index: Lookup, Providers, Resolve, ResolveDeps

The writer produces what makepkg does: .PKGINFO, .BUILDINFO, a gzipped .MTREE with SHA-256 digests, .INSTALL with the six hooks, .CHANGELOG, and a payload sorted by path with its parent directories. With WriteOptions.ClampMTime the archive is reproducible from the build date.

Examples

Build a package, read it back, publish it in a database and resolve against it:

spec := &pacman.Spec{
	Info: pacman.PkgInfo{
		Name: "hello", Version: "1.0-1", Description: "A greeting", Arch: "x86_64",
		BuildDate: 1700000000, Depends: []string{"glibc"},
	},
	Scriptlets: &pacman.Scriptlets{PostInstall: "echo installed"},
	Files: []pacman.File{
		{Path: "usr/bin/hello", Mode: 0o755, Data: []byte("#!/bin/sh\necho hello\n")},
	},
}

var pkg bytes.Buffer
err := spec.Write(&pkg, pacman.WriteOptions{Compression: pacman.CompressionZstd, ClampMTime: true})

entry, err := pacman.NewDBEntry(spec.FileName(pacman.CompressionZstd), bytes.NewReader(pkg.Bytes()), nil)

var db bytes.Buffer
err = pacman.WriteDB(&db, []pacman.DBEntry{*entry}, false)

var index pacman.Index
err = index.AddDatabase("local", &db)

dep, _ := pacman.ParseDependency("hello>=0.9")
best, err := index.Resolve(dep)

Package a directory tree:

files, err := pacman.ScanDir("pkgroot")
spec := &pacman.Spec{Info: info, Files: files}
err = spec.WriteFile("out/"+spec.FileName(pacman.CompressionZstd), pacman.WriteOptions{})

Sync databases from the mirrors of a pacman.conf and download a package, verifying signatures against a keyring:

keyring, err := gpg.LoadKeyringFile("archlinux.gpg")
client, err := pacman.NewClient(pacman.ClientOptions{
	Keyring:           keyring,
	DBSignatures:      pacman.VerifyRequired,
	PackageSignatures: pacman.VerifyRequired,
})

cfg, err := pacman.ParseConfigFile("pacman.conf")
n, err := client.Sync(ctx, cfg.Repos, "sync")

db, err := client.FetchDB(ctx, cfg.Repos[0])
entries, err := db.Entries()
path, err := client.DownloadPackage(ctx, cfg.Repos[0], &entries[0], "cache")

Security notes

  • Packages and databases are untrusted input. Decompressed size, entry count, path length, file-list size, and the zstd and xz windows all have explicit limits (MaxUncompressedBytes, MaxFileEntries, MaxDBBytes, ...); hitting one returns an error wrapping a sentinel such as ErrPackageTooLarge.
  • Paths inside packages are validated; an unsafe one fails with ErrUnsafeEntry. ScanDir opens files below its root and does not follow links out of it.
  • The writer rejects line breaks, NUL bytes and invalid UTF-8 in metadata fields, and paths that could clash with the metadata files, so a field value cannot inject another .PKGINFO line.
  • The client checks a package against the size and SHA-256 (or MD5) of its database entry, and against its signature when PackageSignatures is set. A signature that cannot be fetched is an error, not "unsigned". A failed database or package is discarded and the next mirror is tried.
  • The library never reads a host path on its own: configuration, keyrings and directories are passed in.
  • .MTREE carries SHA-256 digests only.

License

Apache License 2.0, see LICENSE.

Documentation

Overview

Package pacman builds, reads and indexes Arch Linux packages and repositories in pure Go, without makepkg, pacman or repo-add.

Writing packages

A Spec describes a package with plain Go values: the PkgInfo that becomes .PKGINFO, an optional BuildInfo for .BUILDINFO, Scriptlets for .INSTALL, a changelog and the File list. Spec.Write produces a .pkg.tar.zst, .xz or .gz, with .PKGINFO, .BUILDINFO, .MTREE, .INSTALL and .CHANGELOG in the order pacman expects and every directory entry the payload needs. With WriteOptions.ClampMTime the output is reproducible: file times never exceed PkgInfo.BuildDate, as makepkg does with SOURCE_DATE_EPOCH. ScanDir lists a directory tree as Files.

Reading packages and databases

ReadPackage returns the PkgInfo and the file list of a package, ParsePkgInfo and ParseBuildInfo parse the metadata files on their own, and ReadDB reads a sync database ("core.db") into DBEntry values. WriteDB writes one, the way repo-add does, from entries NewDBEntry builds out of package files. Vercmp compares versions like libalpm.

Repositories

ParseConfig and ParseMirrorlist read pacman.conf and mirrorlist text; they touch no file unless asked to (ParseConfigFile), and no path is built in. A Client fetches databases from the servers of a Repo, with mirror failover, optional OpenPGP verification (VerifyMode) and atomic writes (SyncDB, Sync), and downloads packages checked against their database entry (DownloadPackage). An Index holds the entries of several databases and resolves dependencies and provisions (Index.Resolve, Index.ResolveDeps).

Signatures

SignDetached signs a package or database with a gpg.Signer and returns the binary signature pacman expects in a ".sig" file; NormalizeSignature accepts an armored one too.

Untrusted input

Everything read is bounded: sizes, entry counts, path lengths and the zstd and xz windows have explicit limits, paths are validated, and failures are returned as errors wrapping the exported sentinels, never as panics. The writer rejects values that would corrupt a metadata file, such as a line break in a field.

Example
package main

import (
	"bytes"
	"fmt"
	"strings"
	"time"

	"github.com/M0Rf30/pkgformat/pacman"
)

func main() {
	spec := &pacman.Spec{
		Info: pacman.PkgInfo{
			Name: "hello", Version: "1.0-1", Description: "A greeting", Arch: "x86_64",
			BuildDate: 1700000000, Depends: []string{"glibc"},
		},
		Scriptlets: &pacman.Scriptlets{PostInstall: "echo installed"},
		Files: []pacman.File{
			{Path: "usr/bin/hello", Mode: 0o755, Data: []byte("#!/bin/sh\necho hello\n"), ModTime: time.Unix(1700000000, 0)},
		},
	}

	// Write the package, reproducibly.
	var pkg bytes.Buffer
	if err := spec.Write(&pkg, pacman.WriteOptions{Compression: pacman.CompressionZstd, ClampMTime: true}); err != nil {
		fmt.Println(err)

		return
	}

	// Read it back.
	read, err := pacman.ReadPackage(bytes.NewReader(pkg.Bytes()))
	if err != nil {
		fmt.Println(err)

		return
	}

	fmt.Println(spec.FileName(pacman.CompressionZstd), read.Info.Depends, read.Files)

	// Put it in a database and resolve a dependency against it.
	entry, err := pacman.NewDBEntry(spec.FileName(pacman.CompressionZstd), bytes.NewReader(pkg.Bytes()), nil)
	if err != nil {
		fmt.Println(err)

		return
	}

	var db bytes.Buffer
	if err := pacman.WriteDB(&db, []pacman.DBEntry{*entry}, false); err != nil {
		fmt.Println(err)

		return
	}

	var index pacman.Index
	if err := index.AddDatabase("local", &db); err != nil {
		fmt.Println(err)

		return
	}

	dep, _ := pacman.ParseDependency("hello>=0.9")
	best, err := index.Resolve(dep)
	fmt.Println(best.Repo, best.Version, err, pacman.Vercmp("1.0-1", "1.0.1-1"))

	// A pacman.conf yields repositories whose server URLs expand per arch.
	cfg, _ := pacman.ParseConfig(strings.NewReader("[core]\nServer = https://mirror.example/$repo/os/$arch\n"), nil)
	fmt.Println(pacman.ExpandServer(cfg.Repos[0].Servers[0], "core", "x86_64"))

}
Output:
hello-1.0-1-x86_64.pkg.tar.zst [glibc] [usr/ usr/bin/ usr/bin/hello]
local 1.0-1 <nil> -1
https://mirror.example/core/os/x86_64

Index

Examples

Constants

View Source
const (
	// DefaultMaxDBBytes bounds a downloaded database; the largest Arch ones are
	// well under 50 MiB.
	DefaultMaxDBBytes int64 = 256 << 20
	// DefaultMaxPackageBytes bounds a package whose database entry declares no
	// compressed size.
	DefaultMaxPackageBytes int64 = 16 << 30
	// DefaultSyncConcurrency is the number of repositories Sync refreshes at a
	// time.
	DefaultSyncConcurrency = 4
)

Sizes the client enforces on what it downloads.

View Source
const (
	// MaxConfigBytes bounds a pacman.conf or a mirrorlist.
	MaxConfigBytes = 4 << 20
	// MaxConfigRepos bounds the repositories of one configuration.
	MaxConfigRepos = 1000
	// MaxConfigServers bounds the servers of one repository.
	MaxConfigServers = 10000
)

Limits on the configuration files the parsers read.

View Source
const (
	// MaxDBBytes bounds the decompressed tar stream of a database.
	MaxDBBytes int64 = 2 << 30
	// MaxDBEntries bounds the entries of a database.
	MaxDBEntries = 500_000
	// MaxDescBytes bounds the "desc" (or "depends") member of one package.
	MaxDescBytes = 4 << 20
	// MaxDBFileListBytes bounds the file lists kept from one files database.
	MaxDBFileListBytes = 256 << 20
)

Limits on what reading one repository database may cost. A database is fetched from a mirror and is untrusted input.

View Source
const (
	CompressionZstd = "zst"
	CompressionXZ   = "xz"
	CompressionGzip = "gz"
)

Package compressions, the extension of the package file after ".pkg.tar.".

View Source
const (
	// MaxUncompressedBytes bounds the decompressed tar stream.
	MaxUncompressedBytes int64 = 32 << 30
	// MaxFileEntries bounds the entries of the archive.
	MaxFileEntries = 2_000_000
	// MaxFileListBytes bounds the bytes of the file list kept for the files database.
	MaxFileListBytes = 64 << 20
	// MaxEntryNameLen bounds one archive path.
	MaxEntryNameLen = 4096
)

Limits on what reading one package may cost. The package is untrusted input and a few KiB of zstd can decompress to gigabytes.

View Source
const (
	// MaxPkgInfoBytes bounds the .PKGINFO of a package.
	MaxPkgInfoBytes = 1 << 20
	// MaxNameLen bounds package names, versions, architectures and each
	// dependency-like value.
	MaxNameLen = 255
	// MaxValueLen bounds a free-text value (description, URL, packager).
	MaxValueLen = 4096
	// MaxListEntries bounds each multi-valued field.
	MaxListEntries = 5000
)

Field and size limits. They keep what a package can put into one database row and one desc entry bounded.

View Source
const (
	FilePkgInfo   = ".PKGINFO"
	FileBuildInfo = ".BUILDINFO"
	FileMtree     = ".MTREE"
	FileInstall   = ".INSTALL"
	FileChangelog = ".CHANGELOG"
)

Names of the metadata files a package carries at the top of its archive.

View Source
const ArchAny = "any"

ArchAny is the architecture of a package that runs on every architecture.

View Source
const MaxBuildInfoBytes = 1 << 20

MaxBuildInfoBytes bounds a .BUILDINFO.

View Source
const MaxIndexPackages = 2_000_000

MaxIndexPackages bounds the packages an Index holds.

View Source
const MaxInstallBytes = 4 << 20

MaxInstallBytes bounds the .INSTALL scriptlet of a package.

View Source
const MaxSignatureBytes = 16 << 10

MaxSignatureBytes bounds a detached signature (a few hundred bytes for an RSA 4096 or Ed25519 signature; the rest is room for hashed subpackets).

Variables

View Source
var (
	// ErrAllServersFailed wraps the failures of every server of a repository.
	ErrAllServersFailed = errors.New("pacman: all servers failed")
	// ErrNoServers reports a repository with no server.
	ErrNoServers = errors.New("pacman: repository has no servers")
	// ErrSignatureRequired reports a missing signature when the client is set
	// to require one.
	ErrSignatureRequired = errors.New("pacman: required signature is missing")
	// ErrNoKeyring reports a verification mode that needs a keyring, without one.
	ErrNoKeyring = errors.New("pacman: signature verification needs a keyring")
	// ErrChecksumMismatch reports a package that does not match the size or
	// digest its database entry declares.
	ErrChecksumMismatch = errors.New("pacman: package does not match its database entry")
	// ErrNoChecksum reports a database entry with neither a SHA-256 nor an MD5
	// sum, which makes the download unverifiable.
	ErrNoChecksum = errors.New("pacman: database entry has no checksum")
	// ErrInvalidRepoName reports a repository name that is not usable in a file
	// name.
	ErrInvalidRepoName = errors.New("pacman: invalid repository name")
)

Errors of the client. Test with errors.Is.

View Source
var (
	ErrNotDatabase = errors.New("pacman: not a pacman database")
	ErrDBTooLarge  = errors.New("pacman: database exceeds the limit")
)

Errors reading a database.

View Source
var (
	// ErrInvalidDependency reports a dependency expression that cannot be parsed.
	ErrInvalidDependency = errors.New("pacman: invalid dependency")
	// ErrUnresolved reports a dependency no package of the index satisfies.
	ErrUnresolved = errors.New("pacman: unresolvable dependency")
	// ErrIndexTooLarge reports an index that would exceed MaxIndexPackages.
	ErrIndexTooLarge = errors.New("pacman: index exceeds the package limit")
)

Errors of dependency parsing and resolution. Test with errors.Is.

View Source
var (
	ErrNotPackage      = errors.New("pacman: not a pacman package")
	ErrNoPkgInfo       = errors.New("pacman: package has no .PKGINFO")
	ErrPackageTooLarge = errors.New("pacman: package expands beyond the limit")
	ErrUnsafeEntry     = errors.New("pacman: unsafe path in package")
)

Errors reading a package.

View Source
var (
	ErrPkgInfoTooLarge = errors.New("pacman: .PKGINFO too large")
	ErrMissingField    = errors.New("pacman: .PKGINFO misses a required field")
	ErrInvalidField    = errors.New("pacman: invalid .PKGINFO field")
)

Validation errors.

View Source
var (
	// ErrInvalidFile reports a File that cannot be stored: a bad path, a
	// duplicate, a path below a regular file, or a body that does not match.
	ErrInvalidFile = errors.New("pacman: invalid package file")
	// ErrUnsupportedFile reports a file type a package cannot hold (device,
	// socket, named pipe).
	ErrUnsupportedFile = errors.New("pacman: unsupported file type")
	// ErrReservedName reports a payload path whose first element starts with a
	// dot: pacman treats those as package metadata.
	ErrReservedName = errors.New("pacman: reserved package path")
	// ErrUnsupportedCompression reports a compression other than zst, xz, gz.
	ErrUnsupportedCompression = errors.New("pacman: unsupported compression")
)

Errors writing a package.

View Source
var ErrInvalidConfig = errors.New("pacman: invalid configuration")

ErrInvalidConfig reports a pacman.conf or mirrorlist that cannot be parsed or exceeds a limit.

View Source
var ErrInvalidSignature = errors.New("pacman: not a detached OpenPGP signature")

ErrInvalidSignature reports a detached signature that is not exactly one OpenPGP binary-document signature.

Functions

func ArchFromGOARCH

func ArchFromGOARCH(goarch string) string

ArchFromGOARCH maps a GOARCH value to the architecture name Arch Linux (and its ports) use. Unknown values are returned unchanged.

func ExpandServer

func ExpandServer(server, repo, arch string) string

ExpandServer returns the URL of a server entry for a repository and an architecture: $repo and $arch are replaced and trailing slashes dropped.

func FileNameMatches

func FileNameMatches(filename string, info *PkgInfo, ext string) bool

FileNameMatches reports whether filename is the name the package described by info and ext must be published under: the one makepkg writes, or the same with the colon of an epoch written as a hyphen (the spelling of tools that avoid colons in file names).

func FileSums

func FileSums(data io.Reader) (md5sum, sha256sum string, err error)

FileSums returns the MD5 and SHA-256 of data as hex, the sums a database entry carries.

func NormalizeSignature

func NormalizeSignature(data []byte) ([]byte, error)

NormalizeSignature returns the binary form of a detached package signature given either as binary packets or ASCII-armored (gpg --armor), after checking it is a single OpenPGP signature over a binary document. The signature is not verified here: that needs a keyring (see gpg.VerifyDetached).

func PackageFileName

func PackageFileName(name, version, arch, ext string) string

PackageFileName returns the file name makepkg gives a package: name-version-arch.pkg.tar.ext, the colon of an epoch included.

func ParseMirrorlist

func ParseMirrorlist(r io.Reader) ([]string, error)

ParseMirrorlist returns the Server entries of a mirrorlist, in order.

func ReadFileLists

func ReadFileLists(r io.Reader, want func(dir string) bool) (map[string][]string, error)

ReadFileLists reads the "files" members of a files database: the file list of every package whose database directory (name-version, see DBEntry.DirName) want accepts, keyed by that directory. Other packages' lists are never retained, so reading the files database of a large repository costs memory in proportion to what is wanted.

func SignDetached

func SignDetached(signer gpg.Signer, data io.Reader) ([]byte, error)

SignDetached signs data with signer and returns the binary detached signature, the form pacman reads from a .sig file and from %PGPSIG%.

func SplitPackageFileName

func SplitPackageFileName(filename string) (string, string, bool)

SplitPackageFileName returns the extension ("zst", "xz", "gz") of a package file name and the part before ".pkg.tar.". ok is false for any other name.

func ValidArch

func ValidArch(s string) bool

ValidArch reports whether s is a legal architecture ("any", "x86_64", ...).

func ValidFileName

func ValidFileName(s string) bool

ValidFileName reports whether s is acceptable as the name of a package file in a repository: a name ending in ".pkg.tar.{zst,xz,gz}" made of the characters makepkg produces, never a path separator, a control byte or a leading dot.

func ValidFileNameChars

func ValidFileNameChars(s string) bool

ValidFileNameChars accepts the characters of package and database file names.

func ValidName

func ValidName(s string) bool

ValidName reports whether s is a legal package name: lowercase letters, digits and "@._+-", not starting with a hyphen or a dot (the makepkg rule).

func ValidRepoName

func ValidRepoName(s string) bool

ValidRepoName reports whether s can name a repository: it is used as a file name, so it must hold no path separator and not start with a dot.

func ValidVersion

func ValidVersion(s string) bool

ValidVersion reports whether s is a legal "[epoch:]pkgver-pkgrel": no whitespace, slashes or control characters, a numeric epoch when present and a release.

func Vercmp

func Vercmp(a, b string) int

Vercmp compares two package versions the way libalpm's alpm_pkg_vercmp does: "[epoch:]pkgver[-pkgrel]". It returns -1, 0 or 1. The release is compared only when both versions carry one.

func WriteDB

func WriteDB(w io.Writer, entries []DBEntry, withFiles bool) error

WriteDB writes a repository database as a gzip-compressed tar: one directory per package holding its "desc" and, when withFiles is set, its "files" entry. Entries are written in the order of name and version so the output does not depend on the input order.

Types

type BuildInfo

type BuildInfo struct {
	// Format is the .BUILDINFO format; zero means 2, the one makepkg writes.
	Format         int
	PkgName        string
	PkgBase        string
	PkgVer         string // [epoch:]pkgver-pkgrel
	PkgArch        string
	PkgbuildSHA256 string // hex SHA-256 of the build recipe
	Packager       string
	BuildDate      int64
	BuildDir       string
	StartDir       string
	BuildTool      string
	BuildToolVer   string
	BuildEnv       []string
	Options        []string
	// Installed lists the packages present in the build environment, each
	// "name-version-arch".
	Installed []string
}

BuildInfo is the .BUILDINFO of a package: how and where it was built.

func ParseBuildInfo

func ParseBuildInfo(r io.Reader) (*BuildInfo, error)

ParseBuildInfo parses the text of a .BUILDINFO. Unknown keys are ignored. A malformed number or a value over the limits is an error.

func (*BuildInfo) Render

func (b *BuildInfo) Render() ([]byte, error)

Render returns the text of the .BUILDINFO in the order makepkg writes it. Empty optional values are left out.

type Client

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

Client fetches sync databases and packages from pacman mirrors. It is safe for concurrent use.

func NewClient

func NewClient(opts ClientOptions) (*Client, error)

NewClient returns a Client. It fails with ErrNoKeyring when a verification mode is set without a keyring.

func (*Client) DownloadPackage

func (c *Client) DownloadPackage(ctx context.Context, repo Repo, entry *DBEntry, dir string) (string, error)

DownloadPackage downloads the package described by entry from the servers of repo into dir and returns its path. The file is checked against the size and SHA-256 (or, failing that, MD5) of the entry and, per the verification mode, against its signature: the one the entry carries, else "<file>.sig" from the server. A package already in dir that passes the checks is reused. Servers are tried in order; a package that fails a check is discarded and the next server is tried.

func (*Client) FetchDB

func (c *Client) FetchDB(ctx context.Context, repo Repo) (*DBFile, error)

FetchDB downloads the database of repo from the first server that serves it (and, per the verification mode, a valid signature for it).

func (*Client) Sync

func (c *Client) Sync(ctx context.Context, repos []Repo, dir string) (int, error)

Sync refreshes the databases of repos into dir, up to DefaultSyncConcurrency at a time. A repository that fails does not stop the others: it returns how many succeeded and the joined failures (each wrapping its repository name's ErrAllServersFailed or the cause).

func (*Client) SyncDB

func (c *Client) SyncDB(ctx context.Context, repo Repo, dir string) (*DBFile, error)

SyncDB downloads the database of repo into dir as "<repo>.db", with its signature as "<repo>.db.sig"; a stale signature from an earlier sync is removed when the server has none, since it would not match the new database. Both files are replaced atomically.

type ClientOptions

type ClientOptions struct {
	// HTTP fetches databases and signatures, with its retry policy and size
	// caps; packages are downloaded through it too. Nil builds a default client.
	HTTP *httpclient.Client
	// Arch replaces $arch in server URLs; empty selects ArchFromGOARCH of the
	// running system.
	Arch string
	// Keyring holds the public keys signatures are checked against.
	Keyring *gpg.Keyring
	// DBSignatures and PackageSignatures set the verification of databases
	// and of packages. Anything but VerifyNone needs Keyring.
	DBSignatures      VerifyMode
	PackageSignatures VerifyMode
	// MaxDBBytes bounds a database; zero selects DefaultMaxDBBytes.
	MaxDBBytes int64
	// Progress, when set, receives the progress of package downloads: the
	// file name, the bytes on disk and the expected total (-1 when unknown).
	// It may be called from several goroutines.
	Progress func(name string, done, total int64)
	// Logger receives one debug line per server tried. Nil is silent.
	Logger *slog.Logger
}

ClientOptions configures a Client. The zero value is valid: no verification, the default HTTP client and the architecture of the running system.

type Config

type Config struct {
	// Architecture is the value of the Architecture option, such as "auto" or
	// "x86_64"; empty when the option is absent.
	Architecture string
	// Repos are the repositories in the order the file lists them, which is
	// the order pacman searches them.
	Repos []Repo
}

Config is the part of a pacman.conf a repository client needs: the architecture and the repositories with their servers.

func ParseConfig

func ParseConfig(r io.Reader, resolve IncludeResolver) (*Config, error)

ParseConfig parses the text of a pacman.conf. The [options] section yields the Architecture; every other section is a repository, whose Server lines are collected and whose Include lines are expanded through resolve (nil leaves Include lines out). Other options and sections' keys are ignored.

func ParseConfigFile

func ParseConfigFile(path string) (*Config, error)

ParseConfigFile reads the pacman.conf at path. Include values are mirrorlist paths; a value with glob characters is expanded, as pacman does. The path is the caller's: no location is built in.

type DBEntry

type DBEntry struct {
	Filename    string
	Name        string
	Base        string
	Version     string
	Description string
	Groups      []string
	CSize       int64
	ISize       int64
	MD5         string
	SHA256      string
	// PGPSig is the base64 of the binary detached signature of the package file,
	// empty for an unsigned package.
	PGPSig       string
	URL          string
	Licenses     []string
	Arch         string
	BuildDate    int64
	Packager     string
	Replaces     []string
	Conflicts    []string
	Provides     []string
	Depends      []string
	OptDepends   []string
	MakeDepends  []string
	CheckDepends []string
	// Files is the file list written to the "files" entry of the files database.
	Files []string
}

DBEntry is one package of a repository database: what repo-add writes into the "desc" (and, for the files database, "files") entry of a package.

func NewDBEntry

func NewDBEntry(filename string, pkgFile io.ReadSeeker, sig []byte) (*DBEntry, error)

NewDBEntry builds the database entry of a package file read from r: the file's .PKGINFO and file list, its compressed size and its sums, as repo-add records them. sig, when not empty, is the binary detached signature of the file. Entries are meant for WriteDB.

func ReadDB

func ReadDB(r io.Reader) ([]DBEntry, error)

ReadDB reads a repository database (the "db" or "files" tarball, gzip, xz or zstd compressed) into its entries: the fields of each package's "desc" (and legacy "depends") member and, when the archive has them, its "files" member.

The database is untrusted. An entry whose identity is unusable (no valid name, version or package file name, or a malformed number or list) is left out; a database that is not a compressed tar, or exceeds a limit, is an error. Fields the database does not carry stay empty.

func (*DBEntry) Desc

func (e *DBEntry) Desc() []byte

Desc renders the "desc" entry exactly as repo-add writes it: one "%FIELD%" block per non-empty field, a blank line after each.

func (*DBEntry) DirName

func (e *DBEntry) DirName() string

DirName is the directory the package has in the database tarball.

func (*DBEntry) FilesEntry

func (e *DBEntry) FilesEntry() []byte

FilesEntry renders the "files" entry of the files database.

type DBFile

type DBFile struct {
	// Repo is the repository name.
	Repo string
	// URL is the address of the database that was fetched.
	URL string
	// Data is the compressed database as served.
	Data []byte
	// Sig is the binary detached signature, nil when the server has none.
	Sig []byte
	// Verified describes the signer when the signature was verified.
	Verified *gpg.Verified
}

DBFile is a downloaded sync database.

func (*DBFile) Entries

func (d *DBFile) Entries() ([]DBEntry, error)

Entries parses the database.

type Dependency

type Dependency struct {
	Name string
	// Op is "", "=", "<", "<=", ">" or ">=".
	Op string
	// Version is the compared version; empty exactly when Op is empty.
	Version string
}

Dependency is a parsed dependency, provision or conflict expression: "name", or "name" followed by a comparison operator and a version.

func ParseDependency

func ParseDependency(s string) (Dependency, error)

ParseDependency parses "name[(<=|>=|=|<|>)version]".

func (Dependency) Allows

func (d Dependency) Allows(version string) bool

Allows reports whether version satisfies the constraint of d. A dependency without constraint allows every version.

func (Dependency) String

func (d Dependency) String() string

String returns the expression ParseDependency accepts.

type File

type File struct {
	// Path is the slash-separated path below the root of the package, such as
	// "usr/bin/tool". A leading "./" and a trailing "/" are accepted. The first
	// element must not start with a dot (see ErrReservedName).
	Path string
	// Mode holds the permission bits, setuid, setgid and sticky, plus the type
	// bit fs.ModeDir or fs.ModeSymlink; a regular file has no type bit.
	Mode fs.FileMode
	// ModTime is the modification time, kept to the second. The zero time means
	// the build date of the package.
	ModTime time.Time
	// Linkname is the target of a symbolic link.
	Linkname string
	// Data is the content of a regular file. When Open is set, Data is ignored.
	Data []byte
	// Open returns the content of a regular file, for content too large to hold
	// in memory. It is called twice (once to checksum for the .MTREE, once to
	// write) and must return the same Size bytes both times.
	Open func() (io.ReadCloser, error)
	// Size is the length of the content Open returns.
	Size int64
}

File is one entry of the payload of a package: a regular file, a directory or a symbolic link. Ownership is always root:root.

func ScanDir

func ScanDir(root string) ([]File, error)

ScanDir lists the files below root as payload Files, in directory order. The top-level entries named like the generated metadata files (.PKGINFO, .BUILDINFO, .MTREE, .INSTALL, .CHANGELOG) are skipped, so a staging directory that was used before can be scanned again. Contents are opened lazily and never followed outside root.

type FileKind

type FileKind int

FileKind says what a file name in a repository directory names.

const (
	FileInvalid FileKind = iota
	FilePackage
	FilePackageSig
	FileDatabase
	FileDatabaseSig
)

The kinds of file a repository directory holds.

func ClassifyFile

func ClassifyFile(filename string) (FileKind, string)

ClassifyFile names the kind of file a URL file name is. For databases it also returns the generated document it maps to ("db.tar.gz" or "files.tar.gz").

type IncludeResolver

type IncludeResolver func(include string) ([]string, error)

IncludeResolver returns the servers named by an "Include = value" line of a repository section, typically by reading the mirrorlist the value points to and calling ParseMirrorlist. Library code never touches the file system on its own: the caller decides where includes come from.

type Index

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

Index is a set of sync databases that can be searched and whose dependencies can be resolved. The zero value is an empty index. Repositories are searched in the order they were added; an Index is not safe for concurrent modification, but is for concurrent reads.

func (*Index) Add

func (x *Index) Add(repo string, entries []DBEntry) error

Add appends the entries of repo to the index.

func (*Index) AddDatabase

func (x *Index) AddDatabase(repo string, r io.Reader) error

AddDatabase reads a sync database (as ReadDB does) and adds it as repo.

func (*Index) Len

func (x *Index) Len() int

Len returns the number of packages.

func (*Index) Lookup

func (x *Index) Lookup(name string) (*IndexedPackage, bool)

Lookup returns the package called name: of the first repository that has it, its newest version.

func (*Index) Packages

func (x *Index) Packages() []*IndexedPackage

Packages returns every package in the order it was added.

func (*Index) Providers

func (x *Index) Providers(dep Dependency) []*IndexedPackage

Providers returns the packages that satisfy dep other than by their own name: those with a matching provision.

func (*Index) Resolve

func (x *Index) Resolve(dep Dependency) (*IndexedPackage, error)

Resolve returns the package that satisfies dep. A package of that name with an acceptable version wins (the newest one of the first repository that has one); otherwise the first provider, in repository order, does. It fails with ErrUnresolved when nothing does.

func (*Index) ResolveDeps

func (x *Index) ResolveDeps(roots []string, opts ResolveOptions) ([]*IndexedPackage, error)

ResolveDeps returns the packages needed to install roots (dependency expressions such as "foo" or "bar>=2"), the roots included, with every package after the ones it depends on. A dependency cycle is tolerated: the package that closes it is placed before the one that needed it. A dependency nothing satisfies fails with an error wrapping ErrUnresolved that names the package that asked for it.

type IndexedPackage

type IndexedPackage struct {
	Repo string
	DBEntry
}

IndexedPackage is a package of an Index and the repository it comes from.

func (*IndexedPackage) Satisfies

func (p *IndexedPackage) Satisfies(dep Dependency) bool

Satisfies reports whether the package fulfils dep by its own name and version, or by one of its provisions. A provision without version fulfils only a dependency without constraint, as in libalpm.

type Package

type Package struct {
	Info        *PkgInfo
	Compression string
	// Files is the file list as the files database writes it: paths relative to
	// the root, directories with a trailing slash, dot files (.PKGINFO,
	// .BUILDINFO, .MTREE, .INSTALL) left out.
	Files []string
}

Package is what the repository database needs to know about a package file.

func ReadPackage

func ReadPackage(r io.Reader) (*Package, error)

ReadPackage reads a .pkg.tar.{zst,xz,gz} from r: its .PKGINFO and its file list. Compression is detected from the content, not the name.

type PkgInfo

type PkgInfo struct {
	Name        string
	Base        string
	Version     string // [epoch:]pkgver-pkgrel
	Description string
	URL         string
	Packager    string
	Arch        string
	BuildDate   int64
	InstalledSz int64

	Licenses     []string
	Groups       []string
	Replaces     []string
	Conflicts    []string
	Provides     []string
	Backup       []string // files pacman keeps as ".pacsave"/".pacnew" on upgrade
	Depends      []string
	OptDepends   []string
	MakeDepends  []string
	CheckDepends []string
	// XData holds the "xdata" lines, each "key=value" (makepkg writes
	// "pkgtype=pkg" there).
	XData []string
}

PkgInfo is the parsed .PKGINFO of a package.

func ParsePkgInfo

func ParsePkgInfo(r io.Reader) (*PkgInfo, error)

ParsePkgInfo parses the text of a .PKGINFO. The name, version and architecture are required and validated; everything else is optional.

func (*PkgInfo) Render

func (p *PkgInfo) Render(generator string) ([]byte, error)

Render returns the text of the .PKGINFO in the order makepkg writes it, after Validate. generator, when not empty, names the tool in the leading "# Generated by" comment.

func (*PkgInfo) Validate

func (p *PkgInfo) Validate() error

Validate checks that the PkgInfo can be written and read back: a valid name, version and architecture, a valid base name (the name when empty), values without line breaks and within the field limits. It fills an empty Base with the name, as ParsePkgInfo does.

type Repo

type Repo struct {
	Name    string
	Servers []string
}

Repo is a repository: a name and the servers that carry it. A server is a URL that may contain the $repo and $arch placeholders (see ExpandServer).

type ResolveOptions

type ResolveOptions struct {
	// Installed, when set, reports a dependency the system already satisfies;
	// such dependencies are not resolved further.
	Installed func(Dependency) bool
}

ResolveOptions tunes ResolveDeps.

type Scriptlets

type Scriptlets struct {
	PreInstall  string
	PostInstall string
	PreUpgrade  string
	PostUpgrade string
	PreRemove   string
	PostRemove  string

	// UpgradeFallback makes an undefined PreUpgrade run the PreInstall body and
	// an undefined PostUpgrade run the PostInstall body, so a package that only
	// declares install hooks sees them on upgrades too.
	UpgradeFallback bool

	// Preamble is shell text placed before the hooks, typically the helper
	// functions the hooks call. It is written verbatim.
	Preamble string
}

Scriptlets are the bodies of the six hooks pacman runs from a package's .INSTALL file. Each field holds the shell commands of one hook, without the "name() { ... }" wrapper; an empty field means the hook is not defined.

func (*Scriptlets) Empty

func (s *Scriptlets) Empty() bool

Empty reports whether no hook is defined (the package has no .INSTALL).

func (*Scriptlets) Hooks

func (s *Scriptlets) Hooks() string

Hooks renders the six function definitions, without the Preamble. It is what a caller scans to decide which helper functions the Preamble must carry.

func (*Scriptlets) Render

func (s *Scriptlets) Render() []byte

Render returns the content of the .INSTALL file: the Preamble followed by the hook functions. It is nil when no hook is defined.

type Spec

type Spec struct {
	// Info is the .PKGINFO. Name, Version and Arch are required. A zero
	// InstalledSz is replaced by the total size of the regular files, and an
	// empty Base by the name.
	Info PkgInfo
	// BuildInfo is the .BUILDINFO; nil leaves the file out. Its empty PkgName,
	// PkgBase, PkgVer, PkgArch, Packager and BuildDate are taken from Info.
	BuildInfo *BuildInfo
	// Scriptlets are the install hooks written to .INSTALL; nil or no hook
	// leaves the file out.
	Scriptlets *Scriptlets
	// Changelog is the content of .CHANGELOG; empty leaves the file out.
	Changelog []byte
	// Files is the payload. Parent directories that are not listed are added
	// with mode 0755.
	Files []File
}

Spec describes a package to write: everything the archive holds.

func (*Spec) FileName

func (s *Spec) FileName(compression string) string

FileName returns the file name the package is published under: name-version-arch.pkg.tar.ext.

func (*Spec) Write

func (s *Spec) Write(w io.Writer, opts WriteOptions) error

Write writes the package to w.

func (*Spec) WriteFile

func (s *Spec) WriteFile(path string, opts WriteOptions) error

WriteFile writes the package to path through a temporary file in the same directory, so a failed write leaves nothing behind.

type VerifyMode

type VerifyMode int

VerifyMode says how the client treats detached OpenPGP signatures.

const (
	// VerifyNone never verifies. Databases still fetch their ".sig" on a
	// best-effort basis so it can be stored beside the database for other
	// tools.
	VerifyNone VerifyMode = iota
	// VerifyIfPresent verifies a signature the server provides and fails on an
	// invalid one; a server that has none (HTTP 404 or 410) is accepted.
	VerifyIfPresent
	// VerifyRequired fails when a signature is missing or invalid.
	VerifyRequired
)

type WriteOptions

type WriteOptions struct {
	// Compression is the extension of the package: CompressionZstd (the
	// default), CompressionXZ or CompressionGzip.
	Compression string
	// Level is the compression level: a zstd level (1-22), or a gzip level
	// (1-9). Zero selects the default; xz has a single setting.
	Level int
	// ClampMTime limits every file time to the build date (Info.BuildDate), as
	// makepkg does under SOURCE_DATE_EPOCH, so the archive does not depend on
	// when the files were touched.
	ClampMTime bool
	// TarFormat is the tar flavour; the zero value selects tar.FormatPAX.
	TarFormat tar.Format
	// Generator, when not empty, names the tool in the "# Generated by" comment
	// of .PKGINFO.
	Generator string
}

WriteOptions tunes how a package is written. The zero value writes a zstd-compressed PAX tar.

Jump to

Keyboard shortcuts

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