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.
The local database ¶
OpenLocalDB, NewLocalDB and FindLocalDB read the installed packages of /var/lib/pacman/local, read-only: LocalDB.Packages yields an InstalledPackage for each package directory, from its desc and files members, named by its %NAME%. LocalDB.InstalledNames and LocalDB.InstalledProvides list the installed names and capabilities.
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 ¶
- Constants
- Variables
- func ArchFromGOARCH(goarch string) string
- func ExpandServer(server, repo, arch string) string
- func FileNameMatches(filename string, info *PkgInfo, ext string) bool
- func FileSums(data io.Reader) (md5sum, sha256sum string, err error)
- func FindLocalDB(root string) (string, error)
- func NormalizeSignature(data []byte) ([]byte, error)
- func PackageFileName(name, version, arch, ext string) string
- func ParseMirrorlist(r io.Reader) ([]string, error)
- func ReadFileLists(r io.Reader, want func(dir string) bool) (map[string][]string, error)
- func SignDetached(signer gpg.Signer, data io.Reader) ([]byte, error)
- func SplitPackageFileName(filename string) (string, string, bool)
- func ValidArch(s string) bool
- func ValidFileName(s string) bool
- func ValidFileNameChars(s string) bool
- func ValidName(s string) bool
- func ValidRepoName(s string) bool
- func ValidVersion(s string) bool
- func Vercmp(a, b string) int
- func WriteDB(w io.Writer, entries []DBEntry, withFiles bool) error
- type BackupFile
- type BuildInfo
- type Client
- func (c *Client) DownloadPackage(ctx context.Context, repo Repo, entry *DBEntry, dir string) (string, error)
- func (c *Client) FetchDB(ctx context.Context, repo Repo) (*DBFile, error)
- func (c *Client) Sync(ctx context.Context, repos []Repo, dir string) (int, error)
- func (c *Client) SyncDB(ctx context.Context, repo Repo, dir string) (*DBFile, error)
- type ClientOptions
- type Config
- type DBEntry
- type DBFile
- type Dependency
- type File
- type FileKind
- type IncludeResolver
- type Index
- func (x *Index) Add(repo string, entries []DBEntry) error
- func (x *Index) AddDatabase(repo string, r io.Reader) error
- func (x *Index) Len() int
- func (x *Index) Lookup(name string) (*IndexedPackage, bool)
- func (x *Index) Packages() []*IndexedPackage
- func (x *Index) Providers(dep Dependency) []*IndexedPackage
- func (x *Index) Resolve(dep Dependency) (*IndexedPackage, error)
- func (x *Index) ResolveDeps(roots []string, opts ResolveOptions) ([]*IndexedPackage, error)
- type IndexedPackage
- type InstalledPackage
- type LocalDB
- func (db *LocalDB) Close() error
- func (db *LocalDB) InstalledNames(ctx context.Context) ([]string, error)
- func (db *LocalDB) InstalledProvides(ctx context.Context) ([]string, error)
- func (db *LocalDB) List(ctx context.Context) ([]*InstalledPackage, error)
- func (db *LocalDB) Packages(ctx context.Context) iter.Seq2[*InstalledPackage, error]
- type LocalDBOptions
- type Package
- type PkgInfo
- type Reason
- type Repo
- type ResolveOptions
- type Scriptlets
- type Spec
- type VerifyMode
- type WriteOptions
Examples ¶
Constants ¶
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.
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.
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.
const ( // DefaultMaxLocalPackages bounds the package directories of a database. DefaultMaxLocalPackages = MaxDBEntries // DefaultMaxLocalFiles bounds the file records of one package. DefaultMaxLocalFiles = 1 << 21 )
Default limits of the local-database reader, applied where a LocalDBOptions field is zero.
const ( CompressionZstd = "zst" CompressionXZ = "xz" CompressionGzip = "gz" )
Package compressions, the extension of the package file after ".pkg.tar.".
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.
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.
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.
const ArchAny = "any"
ArchAny is the architecture of a package that runs on every architecture.
const MaxBuildInfoBytes = 1 << 20
MaxBuildInfoBytes bounds a .BUILDINFO.
const MaxIndexPackages = 2_000_000
MaxIndexPackages bounds the packages an Index holds.
const MaxInstallBytes = 4 << 20
MaxInstallBytes bounds the .INSTALL scriptlet of a package.
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 ¶
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.
var ( ErrNotDatabase = errors.New("pacman: not a pacman database") ErrDBTooLarge = errors.New("pacman: database exceeds the limit") )
Errors reading a database.
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.
var ( // ErrLocalDBNotFound means [FindLocalDB] met no local database under the // root. ErrLocalDBNotFound = errors.New("pacman: no local database found") // ErrInvalidLocalDB means a directory is not a local database, or cannot // be read as one. ErrInvalidLocalDB = errors.New("pacman: invalid local database") // ErrLocalDBTooLarge means a local database is over one of the limits of // [LocalDBOptions]. ErrLocalDBTooLarge = errors.New("pacman: local database exceeds a limit") // ErrUnsupportedLocalDB means the ALPM_DB_VERSION file names a layout this // package does not read. ErrUnsupportedLocalDB = errors.New("pacman: unsupported local database version") )
Errors of the local-database reader. Test with errors.Is.
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.
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.
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.
var ErrInvalidConfig = errors.New("pacman: invalid configuration")
ErrInvalidConfig reports a pacman.conf or mirrorlist that cannot be parsed or exceeds a limit.
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 ¶
ArchFromGOARCH maps a GOARCH value to the architecture name Arch Linux (and its ports) use. Unknown values are returned unchanged.
func ExpandServer ¶
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 ¶
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 ¶
FileSums returns the MD5 and SHA-256 of data as hex, the sums a database entry carries.
func FindLocalDB ¶ added in v0.3.1
FindLocalDB looks for the local database under root, the directory that holds the system's /var: "/" for the running host, or the root of an image or an install directory. Symbolic links are followed only inside root. It returns ErrLocalDBNotFound when there is no directory.
func NormalizeSignature ¶
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 ¶
PackageFileName returns the file name makepkg gives a package: name-version-arch.pkg.tar.ext, the colon of an epoch included.
func ParseMirrorlist ¶
ParseMirrorlist returns the Server entries of a mirrorlist, in order.
func ReadFileLists ¶
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 ¶
SignDetached signs data with signer and returns the binary detached signature, the form pacman reads from a .sig file and from %PGPSIG%.
func SplitPackageFileName ¶
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 ValidFileName ¶
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 ¶
ValidFileNameChars accepts the characters of package and database file names.
func ValidName ¶
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 ¶
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 ¶
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 ¶
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.
Types ¶
type BackupFile ¶ added in v0.3.1
type BackupFile struct {
// Path is relative to the root of the system: "etc/pacman.conf".
Path string
// MD5 is the hex digest of the file as installed. pacman writes the text
// "(null)" where it has none; it is kept as it is.
MD5 string
}
BackupFile is a "%BACKUP%" line: a file pacman keeps a checksum of so that it can tell a user's edit from the packaged file on upgrade.
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 ¶
ParseBuildInfo parses the text of a .BUILDINFO. Unknown keys are ignored. A malformed number or a value over the limits is an error.
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 ¶
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 ¶
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).
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 ¶
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 ¶
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 ¶
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 ¶
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) FilesEntry ¶
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.
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 ¶
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.
The kinds of file a repository directory holds.
func ClassifyFile ¶
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 ¶
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) AddDatabase ¶
AddDatabase reads a sync database (as ReadDB does) and adds it as repo.
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 ¶
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 InstalledPackage ¶ added in v0.3.1
type InstalledPackage struct {
// Dir is the name of the package's directory, "<name>-<version>" in a
// database pacman wrote. The package's name is Name, not a part of Dir.
Dir string
Name string
Base string
Version string
Description string
URL string
Arch string
Packager string
// BuildDate and InstallDate are Unix seconds, zero when absent.
BuildDate int64
InstallDate int64
// Size is the installed size in bytes.
Size int64
Reason Reason
Groups []string
Licenses []string
Validation []string
Replaces []string
Conflicts []string
Provides []string
Depends []string
OptDepends []string
// XData holds the "%XDATA%" lines, "key=value" ("pkgtype=pkg").
XData []string
// Files are the "%FILES%" of the package, relative to the root of the
// system. A directory has a trailing slash: "usr/bin/".
Files []string
// Backup are the "%BACKUP%" entries of the files member.
Backup []BackupFile
}
InstalledPackage is an entry of the local database: the desc and files members of one package directory.
type LocalDB ¶ added in v0.3.1
type LocalDB struct {
// contains filtered or unexported fields
}
LocalDB is the pacman local database: the directory /var/lib/pacman/local. It is read-only and safe for concurrent use: every call reads the directory again.
Example ¶
Read the packages a pacman system has installed. On a host, FindLocalDB("/") and OpenLocalDB give the real database.
package main
import (
"context"
"fmt"
"log"
"testing/fstest"
"github.com/M0Rf30/pkgformat/pacman"
)
func main() {
fsys := fstest.MapFS{
"ALPM_DB_VERSION": {Data: []byte("9\n")},
"acl-2.4.0-1/desc": {Data: []byte("%NAME%\nacl\n\n%VERSION%\n2.4.0-1\n\n%REASON%\n1\n\n%PROVIDES%\nlibacl.so=1-64\n\n")},
"acl-2.4.0-1/files": {Data: []byte("%FILES%\nusr/\nusr/bin/\nusr/bin/chacl\n")},
}
db := pacman.NewLocalDB(fsys, pacman.LocalDBOptions{})
for pkg, err := range db.Packages(context.Background()) {
if err != nil {
log.Fatal(err)
}
fmt.Println(pkg.Name, pkg.Version, pkg.Reason == pacman.ReasonDependency, pkg.Files)
}
provides, _ := db.InstalledProvides(context.Background())
fmt.Println(provides)
}
Output: acl 2.4.0-1 true [usr/ usr/bin/ usr/bin/chacl] [acl libacl.so]
func NewLocalDB ¶ added in v0.3.1
func NewLocalDB(fsys fs.FS, opts LocalDBOptions) *LocalDB
NewLocalDB reads the local database that fsys holds at its top level: the package directories and ALPM_DB_VERSION. Close does nothing.
func OpenLocalDB ¶ added in v0.3.1
func OpenLocalDB(dir string, opts LocalDBOptions) (*LocalDB, error)
OpenLocalDB opens the local database in dir. The directory is only read and not locked, so pacman can run at the same time; each call reads it as of that moment. Links inside the database that point out of dir are not followed.
func (*LocalDB) Close ¶ added in v0.3.1
Close releases the directory of a database opened with OpenLocalDB.
func (*LocalDB) InstalledNames ¶ added in v0.3.1
InstalledNames returns the names of the installed packages, sorted and without duplicates. It does not read the files members.
func (*LocalDB) InstalledProvides ¶ added in v0.3.1
InstalledProvides returns the names the installed packages answer to: their own and what they provide, without version constraints ("libacl.so=1-64" gives "libacl.so"), sorted and without duplicates. It does not read the files members.
func (*LocalDB) List ¶ added in v0.3.1
func (db *LocalDB) List(ctx context.Context) ([]*InstalledPackage, error)
List returns every installed package: LocalDB.Packages collected into a slice.
func (*LocalDB) Packages ¶ added in v0.3.1
Packages iterates over the installed packages, in the order of their directory names. A package whose directory has no valid desc, whose name or version is not valid, whose desc or files member is over its limit or has a malformed value is skipped and reported at debug level to LocalDBOptions.Logger. The name of a package is the %NAME% of its desc, whatever its directory is called. The iteration ends with an error when the directory is over its limit, cannot be read, has a version this package does not read, or when ctx is done; the error is the last pair it yields. Stopping early releases everything.
type LocalDBOptions ¶ added in v0.3.1
type LocalDBOptions struct {
// Logger receives debug messages about skipped packages. Optional: nil
// discards them.
Logger *slog.Logger
// MaxPackages bounds the entries of the database directory; one with more
// fails with [ErrLocalDBTooLarge]. Zero selects [DefaultMaxLocalPackages].
MaxPackages int
// MaxFiles bounds the file records of one package; a package with more is
// skipped. Zero selects [DefaultMaxLocalFiles].
MaxFiles int
// SkipFiles leaves the files members unread: the packages come without
// Files and Backup.
SkipFiles bool
}
LocalDBOptions configures OpenLocalDB and NewLocalDB. The zero value is usable.
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.
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 ¶
ParsePkgInfo parses the text of a .PKGINFO. The name, version and architecture are required and validated; everything else is optional.
func (*PkgInfo) Render ¶
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.
type Reason ¶ added in v0.3.1
type Reason int
Reason is why a package was installed: the "%REASON%" of its desc.
type Repo ¶
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 ¶
FileName returns the file name the package is published under: name-version-arch.pkg.tar.ext.
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.