Documentation
¶
Overview ¶
Package apt is a client for Debian apt repositories that needs no apt installation: it refreshes package indexes, reads them, resolves dependencies and downloads packages with their integrity enforced.
Sources ¶
ParseSourcesList and ParseSources822 turn the text of sources.list and deb822 .sources files into Source values; LoadSources reads them from a file and a directory the caller names. The package never looks at /etc/apt on its own: every path is an option.
Updating ¶
Update fetches the Release of every source (InRelease, or Release with Release.gpg), verifies its signature with deb.Trust against the keyring named by the source's Signed-By option (a key file, a keyring directory entry, or an inline armored block) or UpdateOptions.DefaultKeyrings, and checks its dates the way apt does: Check-Valid-Until, Valid-Until-Min and Valid-Until-Max, Check-Date and Date-Max-Future. The Release is kept next to the indexes, so a later update refuses to replace a signed Release by an unsigned one (ErrDowngradeToInsecure) unless the source allows the downgrade, and Load can tell pins which suite an index came from.
Every index the source asks for is then fetched, its size and SHA-256 checked against the verified Release: Packages for each component and architecture, Translation files for the source's Languages (de_DE falls back to de), Contents when the Targets option names them, and Sources for a deb-src line. Flat repositories are supported. When the Release says Acquire-By-Hash the index is fetched from its by-hash path, with the plain path as the fallback (By-Hash=force makes by-hash the only one). When the lists directory already holds an older Packages file that the repository's Packages.diff knows, Update downloads the patches instead of the whole index if they are smaller than half of it, applies them and verifies the result against the Release; any failure falls back to the whole file. The indexes land in UpdateOptions.ListsDir under apt's own file names, so that apt itself can read them too.
Sources may use http, https, file: and copy: URLs, and mirror+http, mirror+https and mirror+file: URLs whose document lists the mirrors to try in turn. A cdrom: source is reported as ErrUnsupportedScheme, as are other schemes. Trusted, Allow-Insecure, Allow-Weak, By-Hash, PDiffs, Languages, Targets, Architectures and the date options of a source are honoured as Source documents them. A signature that is present and wrong is always an error; a missing trust anchor, an unknown signer or an unsigned repository is accepted only with Trusted, Allow-Insecure or UpdateOptions.AllowUnverified.
Without a Signed-By option on the source, the Signed-By field of the Release itself limits the keys that may have signed it to the listed fingerprints (ErrReleaseSignedBy otherwise), as in apt 2.3 and later. Indexes are checked by their SHA-256 (or SHA-512) digest; a Release that lists only MD5 or SHA-1 digests gives ErrWeakDigest, unless the source sets Allow-Weak, which makes Update verify by SHA-1 or MD5.
Reading ¶
Load builds a Cache from a lists directory, and optionally a dpkg status file, whose path the caller gives. A Cache keeps every version of every package the indexes carry, per name and architecture, and the versions the status file says are installed. Lookup answers with the highest version, Versions with all of them.
ResolveDeps works out what installing some packages would add, after apt's rules: version constraints (<<, <=, =, >=, >>) are honoured with deb.CompareVersions; alternatives are tried in order, an installed or already selected one first; a virtual package is met by its providers, a versioned dependency only by a versioned Provides; Pre-Depends count as Depends; a package that Conflicts with or Breaks an installed or selected one, or the other way round, is refused with a ConflictError; and Multi-Arch foreign, allowed and same decide which architecture meets a dependency, with "name:any", "name:native" and "name:arch" as apt reads them. An installed package whose version a dependency finds too old is upgraded if the indexes carry a newer one, else the dependency is unsatisfiable. The result is deterministic. Where it differs from apt (it never removes an installed package) is listed on ResolveDeps.
Pins and phased updates ¶
ParsePreferences and LoadPreferences read apt_preferences(5) files into Preferences; NewPolicy turns them, the release the user targets (apt -t) and the machine id into a Policy that gives every version its pin priority (Priority), selects the version to install (Candidate, or Cache.Candidate) and tells whether a phased update is withheld from a system (Phased). The rules are apt's: pins by release, version, source version and origin with fnmatch and regular expression patterns, NotAutomatic and ButAutomaticUpgrades, priority 100 for an installed-only version, and Phased-Update-Percentage decided by PhasedDraw, which reproduces apt's draw bit for bit.
Planning ¶
Cache.Plan predicts what apt-get would do to an installed system: the packages installed, upgraded, downgraded and removed, with the reason of each change, and the ones kept back. Installing a package that Conflicts with or Breaks an installed one removes or upgrades it, and what a change leaves broken is repaired the way apt's problem resolver repairs it. PlanRequest selects install and remove requests and the upgrade mode (upgrade, upgrade with new packages, dist-upgrade, autoremove); PlanOptions carries the Policy, Install-Recommends and Install-Suggests, the AutoRemove options and extra held packages. Recommends and Suggests of what is installed are followed as apt does, the automatic-installation marks of /var/lib/apt/extended_states (LoadOptions.ExtendedStatesFile) and the dpkg holds of the status file are read by Load, and a plan lists the packages it leaves manually or automatically installed. The steps are put in the order apt-get -s prints, by a port of apt's Pre-Depends and Depends ordering; a system apt cannot configure (two packages that Pre-Depend on each other) fails with an *OrderError that names the cycle. The plans are checked against recorded apt-get -s output (apt 3.0.4): see testdata/diff/README.md for the scenarios and for what is not modelled (the fallback to apt's second solver, the versioned-kernel protection of autoremove, purge as distinct from remove). Use ResolveDeps instead when nothing installed may be removed.
Downloading ¶
Cache.Download and Cache.DownloadClosure fetch .deb files into a directory. Each file is checked against the SHA-256 and size of the index while it is written, and a file that fails is not left behind. The result is a normal .deb for deb.ParseDebFileAt.
A package whose base URL is a mirror list is fetched from the mirrors in turn; file: and copy: bases are copied, with the same checks.
Transfers use the httpclient and download packages: size caps, retry with backoff, and a single retry over https when a plain http fetch fails transiently.
Index ¶
- Constants
- Variables
- func ArchFromGoarch(goarch string) string
- func BaseURLs(sources []Source) map[string]string
- func IsVerificationError(err error) bool
- func ListFileName(baseURL, suite, relPath string) string
- func ListFileNameFor(src *Source, relPath string) string
- func LoadKeyring(signedBy string, defaults []string) (*gpg.Keyring, error)
- func PhasedDraw(sourceName, sourceVersion, machineID string, model PhasedModel) int
- func Update(ctx context.Context, sources []Source, opts UpdateOptions) (int, error)
- type AutoMark
- type ByHashMode
- type Cache
- func (c *Cache) AddEntry(info *PackageInfo)
- func (c *Cache) Candidate(name string, pol *Policy) (PackageInfo, bool)
- func (c *Cache) CapabilityCount() int
- func (c *Cache) Download(ctx context.Context, destDir string, pkgs []string, opts DownloadOptions) error
- func (c *Cache) DownloadClosure(ctx context.Context, destDir string, seeds []string, opts DownloadOptions) (resolved []*PackageInfo, unresolved []string, err error)
- func (c *Cache) HostArch() string
- func (c *Cache) InstalledNames() map[string]bool
- func (c *Cache) Lookup(name string) (PackageInfo, bool)
- func (c *Cache) PackageCount() int
- func (c *Cache) Plan(req PlanRequest, opts PlanOptions) (*Plan, error)
- func (c *Cache) ResolveDeps(seeds []string) ([]*PackageInfo, []string, error)
- func (c *Cache) ResolveVirtual(name string) string
- func (c *Cache) Versions(name string) []PackageInfo
- type Change
- type ChangeKind
- type ConflictError
- type DownloadOptions
- type ExtendedStatesError
- type KeyNotFoundError
- type LoadOptions
- type OrderError
- type OrderKind
- type PackageInfo
- type PhasedModel
- type Pin
- type PinType
- type Plan
- type PlanError
- type PlanOptionError
- type PlanOptions
- type PlanRequest
- type Policy
- type PolicyOptions
- type Preferences
- type PreferencesError
- type Reason
- type ReasonKind
- type ReleaseInfo
- type Source
- func (s *Source) EffectiveArchitectures(defaultArch string) []string
- func (s *Source) EffectiveLanguages(defaults []string) []string
- func (s *Source) EffectiveTargets(defaultLanguages []string) []string
- func (s *Source) ExpandArch(arch string) Source
- func (s *Source) Flat() bool
- func (s *Source) IsSource() bool
- func (s *Source) Scheme() string
- type SourceError
- type SourceType
- type Switch
- type UnsatisfiedError
- type UpdateError
- type UpdateOptions
- type UpgradeMode
- type VirtualPackageError
Examples ¶
- Cache.Plan
- Cache.ResolveDeps
- ListFileNameFor
- LoadKeyring
- LoadPreferences
- NewPolicy
- OrderError
- PackageInfo (Held)
- ParsePreferences
- ParsePreferences (Error)
- ParseSources822
- ParseSourcesList
- ParseSourcesList (Errors)
- PlanOptions (InstallRecommends)
- PlanRequest (AutoRemove)
- Policy.Candidate
- Policy.Phased
- Source.EffectiveTargets
Constants ¶
const ( // PriorityDefault is the priority of a version from an ordinary archive. PriorityDefault = 500 // PriorityTarget is the priority of the releases named by // [PolicyOptions].DefaultRelease (apt-get -t). PriorityTarget = 990 // PriorityInstalled is the priority of the installed version, and of // those of a NotAutomatic archive that is also ButAutomaticUpgrades. PriorityInstalled = 100 // PriorityNotAutomatic is the priority of a NotAutomatic archive. PriorityNotAutomatic = 1 // PriorityDowngrade is the priority from which apt installs a version older // than the installed one. PriorityDowngrade = 1000 )
Pin priorities apt assigns without a pin, see apt_preferences(5).
const ( // MaxSourcesFileBytes caps one sources.list or deb822 .sources file read by // LoadSources, and the text given to ParseSourcesList and ParseSources822. MaxSourcesFileBytes = 1 << 20 // MaxSourceListValues caps the words of one list value: the components of // a line, the Suites or URIs of a stanza, the entries of an option. MaxSourceListValues = 1024 // MaxStanzaSources caps the sources one deb822 stanza expands to // (Types x URIs x Suites). MaxStanzaSources = 1024 // MaxSourcesPerFile caps the sources one file yields. MaxSourcesPerFile = 16384 )
Limits of the sources parsers, which bound what hostile input can allocate.
const DefaultPlanSteps = 200000
DefaultPlanSteps is the work budget of a plan when PlanOptions.MaxSteps is zero.
const MaxDebBytes int64 = 2 << 30
MaxDebBytes caps one .deb download. Real packages top out around 500 MB; 2 GiB leaves room while still stopping an unbounded mirror stream.
const MaxExtendedStatesBytes = 32 << 20
MaxExtendedStatesBytes bounds the extended states file Load reads. A system with tens of thousands of automatically installed packages writes well under a megabyte.
const MaxMirrorListBytes = 1 << 20
MaxMirrorListBytes caps a mirror list document.
const PriorityNever = math.MinInt16
PriorityNever is the pin priority of "Pin-Priority: never", which keeps a version from being selected at all and cannot be overridden by another pin.
Variables ¶
var ( // ErrTooLarge reports input over a size limit. ErrTooLarge = errors.New("apt: input too large") // ErrIntegrity reports a downloaded file whose size or digest differs from // what the verified Release or the package index declared. ErrIntegrity = errors.New("apt: integrity check failed") // ErrNoPackagesIndex reports a component and architecture that the Release // does not list. apt treats that as nothing to fetch. ErrNoPackagesIndex = errors.New("apt: no Packages index listed") // ErrNoSources reports an update without any source. ErrNoSources = errors.New("apt: no sources configured") // ErrNoListsDir reports an update without a lists directory. ErrNoListsDir = errors.New("apt: no lists directory given") // ErrPackageNotFound reports a package that is not in the index, or has no // downloadable file. ErrPackageNotFound = errors.New("apt: package not found in index") // ErrNoBaseURL reports an indexed package whose repository URL is unknown, // so it cannot be downloaded. ErrNoBaseURL = errors.New("apt: package has no repository URL") // ErrInvalidIndexEntry reports an index entry that cannot be downloaded // safely: a malformed SHA256, an out-of-range Size, or an unsafe Filename. ErrInvalidIndexEntry = errors.New("apt: invalid package index entry") // ErrDependencyDepth is returned by ResolveDeps for a dependency chain // deeper than maxResolveDepth, which only a hostile or corrupt index // produces. ErrDependencyDepth = errors.New("apt: dependency chain too deep") // ErrResolveLimit is returned by ResolveDeps when backtracking over // alternatives and versions exceeds its step budget, which only a hostile // or corrupt index produces. ErrResolveLimit = errors.New("apt: dependency resolution exceeded its step limit") // ErrUnsatisfiable is matched by an [UnsatisfiedError]: a dependency no // available package satisfies. ErrUnsatisfiable = errors.New("apt: unsatisfiable dependency") // ErrConflict is matched by a [ConflictError]: a package that conflicts // with, or breaks, an installed or selected one. ErrConflict = errors.New("apt: conflicting packages") )
var ( // ErrPreferences is matched by every [PreferencesError]. ErrPreferences = errors.New("apt: invalid preferences") // ErrNoPackageHeader reports a preferences record without a Package field. ErrNoPackageHeader = errors.New("apt: preferences record has no Package header") // ErrPinPriority reports a Pin-Priority that is missing, zero, not a number // or outside -32768..32767. ErrPinPriority = errors.New("apt: invalid Pin-Priority") // ErrNeverPin reports "Pin-Priority: never" in a record that is not // "Package: *". ErrNeverPin = errors.New("apt: Pin-Priority never needs Package: *") )
var ( // ErrUnresolvable is matched by a [PlanError]: the problem resolver // could not find a state in which every dependency holds. ErrUnresolvable = errors.New("apt: unable to correct problems") // ErrVirtualPackage is matched by a [VirtualPackageError]. ErrVirtualPackage = errors.New("apt: ambiguous virtual package") )
Sentinel errors of planning.
var ( // ErrUnsupportedScheme reports a source whose URI scheme the client has no // transport for (everything but http and https as far as Update goes). The // parsers accept every scheme apt knows (file:, copy:, cdrom:, ftp:, // mirror+http:, ssh:, ...) and keep it in Source.URL; Scheme tells which. ErrUnsupportedScheme = errors.New("apt: unsupported URI scheme") // ErrMalformedSource reports a sources entry that is not well formed: an // unknown type, a missing URI, suite or component, a URI without a scheme, // an option that is not key=value. ErrMalformedSource = errors.New("apt: malformed source entry") // ErrInvalidOption reports the value of a known source option that apt // does not accept: a yes/no option that is neither, a duration that is not // a number of seconds, a By-Hash other than yes, no and force. ErrInvalidOption = errors.New("apt: invalid source option value") // ErrInvalidSignedBy reports a Signed-By value that is none of the forms // apt accepts: a list of fingerprints, a list of absolute keyring paths // (or both), or one inline armored key block alone. ErrInvalidSignedBy = errors.New("apt: invalid Signed-By value") )
var DefaultNeverAutoRemove = []string{
"^firmware-linux.*",
"^linux-firmware$",
"^linux-image-[a-z0-9]*$",
"^linux-image-[a-z0-9]*-[a-z0-9]*$",
}
DefaultNeverAutoRemove is apt's APT::NeverAutoRemove of a stock install (/etc/apt/apt.conf.d/01autoremove): firmware and the kernel image packages, which auto-removal keeps even when nothing needs them.
var ErrDowngradeToInsecure = errors.New("apt: repository was signed before and is not any more")
ErrDowngradeToInsecure reports a repository whose Release was signed at the last update and is not now. The allow-downgrade-to-insecure source option accepts it.
var ErrEmptyMirrorList = errors.New("apt: mirror list holds no usable URL")
ErrEmptyMirrorList reports a mirror list without a single usable URL.
var ErrOrderLoop = errors.New("apt: dependency cycle: packages cannot be configured")
ErrOrderLoop is matched by a *OrderError for a plan whose packages cannot be configured in any order, such as a Pre-Depends cycle.
var ErrOrderRemoval = errors.New("apt: plan needs a temporary removal that apt refuses")
ErrOrderRemoval is matched by a *OrderError for a plan that would have to remove an essential package temporarily to break a Conflicts or Pre-Depends loop.
var ErrOrderSimulation = errors.New("apt: plan steps break a dependency")
ErrOrderSimulation is matched by a *OrderError for a plan whose steps, replayed in the order apt chooses, leave a Conflicts violated or configure a package whose dependencies do not hold yet.
var ErrPlanOption = errors.New("apt: invalid plan option")
ErrPlanOption is matched by a *PlanOptionError: a PlanOptions value that cannot be used.
var ErrReleaseFromFuture = errors.New("apt: release file is not valid yet")
ErrReleaseFromFuture reports a Release whose Date lies in the future by more than the Date-Max-Future of the source (10 seconds by default), which a replayed or misdated Release would show. The check-date source option disables it.
var ErrReleaseSignedBy = errors.New("apt: release signed by a key its Signed-By field does not allow")
ErrReleaseSignedBy is returned when the Signed-By field of a Release does not allow the key that signed it, or names keys the trusted keyrings lack.
var ErrTooManyExtendedStates = errors.New("apt: too many paragraphs in the extended states file")
ErrTooManyExtendedStates reports an extended states file with more than 1048576 paragraphs.
var ErrWeakDigest = errors.New("apt: index listed with weak digests only")
ErrWeakDigest is returned for an index that the Release lists with MD5 or SHA1 digests only: they cannot vouch for it unless the source sets Allow-Weak.
Functions ¶
func ArchFromGoarch ¶
ArchFromGoarch maps a runtime.GOARCH value to the Debian architecture name.
func BaseURLs ¶
BaseURLs maps the encoded host-and-path prefix of apt's list file names to the URL of the source. Of several sources with the same prefix the last wins.
func IsVerificationError ¶
IsVerificationError reports whether err is solely a signature verification failure (unknown signer or no trust anchor) and not a network or I/O error. A caller that already fetched enough indexes can downgrade such an error to a warning.
For the UpdateError that Update returns, "solely" means every failure in it is one: a network error next to a trust error is not downgraded.
func ListFileName ¶
ListFileName returns the name apt stores relPath of a repository under: ("https://archive.ubuntu.com/ubuntu/", "jammy", "main/binary-amd64/Packages.xz") gives "archive.ubuntu.com_ubuntu_dists_jammy_main_binary-amd64_Packages.xz". It is ListFileNameFor of a source with that URL and suite. It returns "" for a URL that does not parse.
func ListFileNameFor ¶ added in v0.4.0
ListFileNameFor returns the name apt (URItoFileName of the file's URI) stores a file of the source under in /var/lib/apt/lists. relPath is the path below the suite directory: "InRelease", "Release", "Release.gpg", "main/binary-amd64/Packages", "main/binary-amd64/Packages.xz", "main/i18n/Translation-en", "main/Contents-amd64.gz", "main/source/Sources".
The URI is the base URL, then "dists/<suite>/" (or the suite itself when it ends in a slash, nothing for the suite "/"), then relPath; user, password and scheme are dropped, host and port kept (a port is kept even when it is the default, 0 is dropped), and every byte apt quotes becomes "%xx" in lower case: "\|{}[]<>"^~_=!@#$%&*", blanks, controls and bytes over 0x7e. "/" becomes "_", so a file: URL, which has no host, starts with "_". The suite is quoted once for the request ("+", "~" and blank, as pkgAcquire::URIEncode does) and once more for the name, so "a+b" gives "a%252bb".
It returns "" for a URL that is none (without scheme, or with an unterminated "[" in its host).
Example ¶
package main
import (
"fmt"
"github.com/M0Rf30/pkgformat/deb/apt"
)
func main() {
src := apt.Source{URL: "https://user:secret@deb.example.org:8443/my_repo~1/", Suite: "stable"}
fmt.Println(apt.ListFileNameFor(&src, "InRelease"))
fmt.Println(apt.ListFileNameFor(&src, "main/binary-amd64/Packages.xz"))
flat := apt.Source{URL: "http://deb.example.org/flat/", Suite: "./"}
fmt.Println(apt.ListFileNameFor(&flat, "Packages"))
}
Output: deb.example.org:8443_my%5frepo%7e1_dists_stable_InRelease deb.example.org:8443_my%5frepo%7e1_dists_stable_main_binary-amd64_Packages.xz deb.example.org_flat_._Packages
func LoadKeyring ¶
LoadKeyring returns the trust anchor of a source: the public keys its Release may be signed by.
signedBy is the Signed-By option, in any form apt takes:
- empty: the union of every usable key found in defaults, which are keyring files or directories such as /etc/apt/trusted.gpg.d, as apt trusts them. Paths that do not exist or cannot be parsed are skipped; no key at all is deb.ErrNoTrustAnchor.
- a list of absolute keyring paths, separated by commas or blanks: exactly those keyring files, or directories of *.gpg and *.asc files. A path that is missing, or holds no key, fails. A value that is as a whole one existing absolute path is that path, even with blanks or commas in it.
- a list of fingerprints (40 hex digits, optionally ending in "!"): those keys, selected from the keyrings of defaults. A fingerprint selects the key and its subkeys, so signatures by a subkey verify; with "!" only the key itself. The fingerprint of a subkey selects that subkey. A fingerprint found in none of the keyrings fails with *KeyNotFoundError.
- paths and fingerprints together: the fingerprints select from the listed keyrings instead of the defaults, as in apt.
- an inline armored PGP public key block (the deb822 multi-line form, with " ." for empty lines). It cannot be mixed with other values.
Every failure wraps deb.ErrNoTrustAnchor; an unusable value also wraps ErrInvalidSignedBy.
A selection by fingerprint is rebuilt from the selected keys, so the result holds only those (and not, say, the other keys of the same file); it keeps every certificate and signature of them.
Example ¶
package main
import (
"errors"
"fmt"
"github.com/M0Rf30/pkgformat/deb/apt"
)
func main() {
// Signed-By may hold fingerprints, keyring paths or an inline key; here a
// fingerprint that no keyring holds.
_, err := apt.LoadKeyring("0123456789ABCDEF0123456789ABCDEF01234567", nil)
var nf *apt.KeyNotFoundError
fmt.Println(errors.As(err, &nf))
}
Output: true
func PhasedDraw ¶ added in v0.4.0
func PhasedDraw(sourceName, sourceVersion, machineID string, model PhasedModel) int
PhasedDraw is the number apt draws for a machine and a source package version: it seeds std::minstd_rand through std::seed_seq with "<source>-<source version>-<machine id>" and takes one value of a std::uniform_int_distribution over 0..99 (PhasedCurrent) or 0..100 (the other models), computed the way libstdc++ does. A version phased at percentage p is held back when the draw is at least p (PhasedCurrent) or above p (the others).
The bytes of the seed are widened as signed chars, as on x86; names and versions are ASCII.
func Update ¶
Update fetches the indexes every source asks for, verifies the Release signature and every index's size and SHA-256 against it, and writes the Release files and indexes to opts.ListsDir.
For a deb source the indexes are the Packages of every component and architecture (Architectures, Architectures-Add and -Remove), the Translation files of the languages (Languages) and, if Targets names it, the Contents files; for a deb-src source they are the Sources of every component. The Targets, Languages and Architectures options select among them (see Source.EffectiveTargets). Sources reached over http, https, file: and copy:, and through mirror+ lists, are supported; cdrom: and every other scheme fail with ErrUnsupportedScheme.
An index is fetched by its digest (by-hash) when the Release says Acquire-By-Hash: yes or the source says By-Hash: force, and falls back to the plain path unless forced. An index the previous update left, in any compression, is brought up to date with the repository's Packages.diff patches when it lists any and they are smaller than the whole file, and fetched whole otherwise.
Indexes the Release does not list are skipped silently, as apt does. It returns how many (source, index) pairs are now in place, whether fetched or already current, and an *UpdateError holding everything that failed: a partial failure still reports the successes. Use IsVerificationError to tell trust failures from network ones.
Types ¶
type AutoMark ¶ added in v0.4.0
type AutoMark struct {
// Package is the package name.
Package string
// Architecture is the Architecture of the paragraph; "" means every
// architecture of the package.
Architecture string
}
AutoMark is one package that an extended states file marks as automatically installed.
func ParseExtendedStates ¶ added in v0.4.0
ParseExtendedStates reads the paragraphs of an apt extended states file (/var/lib/apt/extended_states) that carry a positive "Auto-Installed" field, as apt's readStateFile does. The architecture is "" for a paragraph without an Architecture field, which covers every architecture of the name. A paragraph without a Package, or whose Auto-Installed is absent, zero, negative or not a number, marks nothing. It fails with ErrTooManyExtendedStates for a file with more than 1048576 paragraphs.
type ByHashMode ¶ added in v0.4.0
type ByHashMode uint8
ByHashMode is the By-Hash source option.
const ( // ByHashDefault is unset: by-hash is used when the Release file says // Acquire-By-Hash: yes, as with "yes". ByHashDefault ByHashMode = iota // ByHashYes uses by-hash when the Release file offers it. ByHashYes // ByHashNo never uses by-hash. ByHashNo // ByHashForce uses by-hash even if the Release file does not say so, and // does not fall back to the plain index path. ByHashForce )
type Cache ¶
type Cache struct {
// contains filtered or unexported fields
}
Cache is an in-memory index of package metadata, merged from apt package indexes and the dpkg status database. Every version of a package that any index carries is kept, grouped by name and architecture. It is safe for concurrent use.
func Load ¶
func Load(opts LoadOptions) (*Cache, error)
Load reads the apt indexes of opts.ListsDir, then the dpkg status database of opts.StatusFile.
Every version of a package that an index carries is kept. A stanza without Version, or whose relation fields do not parse, is skipped.
An installed package whose Status is "hold ok installed" has PackageInfo.Held set, and one that opts.ExtendedStatesFile marks Auto-Installed has PackageInfo.AutoInstalled set; Cache.Plan honours both.
Like apt itself, Load tolerates what it cannot read: a missing directory, an unreadable or corrupt index. The returned Cache is never nil and holds everything that did load; the error, when not nil, joins one error per file that did not, so a caller can warn about them.
func NewCache ¶
NewCache returns an empty cache. hostArch is the architecture packages are looked up for when a name carries no qualifier; empty selects the one of the running program.
func (*Cache) AddEntry ¶
func (c *Cache) AddEntry(info *PackageInfo)
AddEntry adds a version of a package. An entry with the same name, architecture and version replaces the old one; another version is kept next to the others. Use it to set a cache up by hand, before it is shared.
func (*Cache) Candidate ¶ added in v0.4.0
func (c *Cache) Candidate(name string, pol *Policy) (PackageInfo, bool)
Candidate returns the version of the named package apt would install under the pin policy pol: the highest priority wins, the highest version among equals, and a version below priority 0 or a phased update withheld from the installed system is never chosen. A nil pol applies apt's defaults (no preferences). The bool is false when no version qualifies.
func (*Cache) CapabilityCount ¶
CapabilityCount is the number of virtual package names (Provides) known.
func (*Cache) Download ¶
func (c *Cache) Download(ctx context.Context, destDir string, pkgs []string, opts DownloadOptions) error
Download fetches the named packages into destDir, each as the base name of its index Filename. A name may carry an architecture qualifier and a version constraint ("gcc-11:arm64 (= 11.3.0-1)"); the highest version that meets it is fetched, the highest of all without one. The size and SHA-256 of the index are enforced while the file is written, and a file that fails the check is not left behind.
Every package is resolved and validated before any transfer starts, so an unknown package, a package without a repository URL, or a malformed index entry (missing or invalid SHA256, Size out of range, unsafe Filename) fails the call at once. Transfers then run to completion; the error of the first failing package, in argument order, is returned.
A plain-http transfer that fails with a transient error is retried once over https.
func (*Cache) DownloadClosure ¶
func (c *Cache) DownloadClosure( ctx context.Context, destDir string, seeds []string, opts DownloadOptions, ) (resolved []*PackageInfo, unresolved []string, err error)
DownloadClosure resolves the transitive closure of the seed names with ResolveDeps, downloads every resulting .deb into destDir, and returns the resolved packages in dependency order (dependencies first) and the names that could not be resolved.
Installed packages are skipped, and so are their dependencies: as with apt, an installed package is taken to have its own met. A dependency an installed package would meet only for another architecture (a cross build reading the dependencies of a foreign library) is still resolved, since the installed one does not satisfy it.
func (*Cache) InstalledNames ¶
InstalledNames returns the names, without architecture qualifier, of the packages the dpkg status database reports as installed. A name counts when at least one architecture of it is installed.
Cross-build extractors use it to avoid overlaying a foreign-architecture payload on host binaries whose path is shared between architectures (/usr/bin/sudo is one file, and may be in use).
func (*Cache) Lookup ¶
func (c *Cache) Lookup(name string) (PackageInfo, bool)
Lookup returns the highest installable version of the named package. The name may carry an architecture qualifier ("gcc-11:arm64"). Without one, or when the qualified package is missing, it tries the bare name (architecture all), the host architecture, then any architecture. A package that is only installed, with no index version, is returned too, with HasCandidate false.
func (*Cache) PackageCount ¶
PackageCount is the number of packages in the cache, counting a name on two architectures twice and every version of one once.
func (*Cache) Plan ¶ added in v0.4.0
func (c *Cache) Plan(req PlanRequest, opts PlanOptions) (*Plan, error)
Plan works out the changes the request needs, the way apt does: the candidates are installed together with their dependencies, an installed package that a new package Conflicts with is removed, one it Breaks is upgraded (or removed when it cannot be), installed packages whose dependencies a new version no longer meets are upgraded too, and what cannot be saved is removed. It is a port of the decisions of apt's pkgDepCache::MarkInstall and pkgProblemResolver (the "internal" solver of "apt-get install", "remove", "upgrade" and "dist-upgrade"), so for a system described the same way the plan is the one "apt-get -s" prints.
The system is the one the cache holds: packages of the dpkg status database are installed, those of the indexes can be installed. Candidates come from PlanOptions.Policy, pins included: a version of priority below zero is never a candidate. Cache.ResolveDeps differs in that it never removes anything and may pick any version that fits; use that to extract a toolchain, and Plan to predict what a package manager would do.
Recommends of the packages being installed are installed too when they can be, and skipped silently when not, as apt does with Install-Recommends (PlanOptions.InstallRecommends, on by default); Suggests only with PlanOptions.InstallSuggests. Nothing is removed to satisfy a soft dependency, except that a recommended package that conflicts with an installed one removes it, as in apt. The automatic-installation marks of /var/lib/apt/extended_states (LoadOptions.ExtendedStatesFile) and the dpkg holds of the status file are read by Load; new dependencies are marked automatic in the result (Change.Auto, Plan.Manual), and PlanRequest.AutoRemove, like "remove" with --auto-remove, removes the automatically installed packages nothing manual needs any more (Plan.AutoRemovable lists them). PlanOptions.Held adds holds the status database does not carry; an explicit request for a held package overrides its hold, as it does in apt.
Once the resolver has decided, the plan is ordered the way apt orders it: unpack and configure steps are replayed with a port of apt's ordering of Pre-Depends and Depends (pkgOrderList and pkgPackageManager), so Plan.Changes come in the order "apt-get -s" prints them (removals first) and a system apt cannot configure fails as it does: an *OrderError that wraps ErrOrderLoop, ErrOrderRemoval or ErrOrderSimulation and names the cycle.
What is not modelled: the fallback to apt's second solver when the first one fails (such a request fails here), the versioned-kernel protection of autoremove (APT::VersionedKernelPackages and the protected kernels, which depend on the running system), purge as distinct from remove (the state of configuration files is not known), the Important and Protected package flags beyond Essential, implicit Breaks and reinstalls. Where apt's choice rests on the order of its internal hash tables (a tie between packages of equal score) the plan takes the order of the package names; the order of reverse dependencies follows apt's package table as far as the loaded indexes tell, so it may differ for versions that only a larger archive holds.
An error is a *PlanError when the resolver fails, an *OrderError when the steps cannot be ordered, a *VirtualPackageError for an ambiguous request, a *PlanOptionError for an invalid option, ErrResolveLimit when the work budget runs out, or a parse error of a request (it wraps deb.ErrInvalidControlFormat).
Example ¶
Plan predicts what apt-get would do: here installing mta-a removes the installed mta-b it conflicts with, and upgrades nothing else.
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/M0Rf30/pkgformat/deb/apt"
)
func main() {
dir, err := os.MkdirTemp("", "plan")
if err != nil {
fmt.Println(err)
return
}
defer os.RemoveAll(dir)
index := "Package: mta-a\nVersion: 1\nArchitecture: amd64\nConflicts: mta-b\n\n"
status := "Package: mta-b\nStatus: install ok installed\nVersion: 1\nArchitecture: amd64\n\n"
list := filepath.Join(dir, "example.org_dists_stable_main_binary-amd64_Packages")
statusFile := filepath.Join(dir, "status")
if err := os.WriteFile(list, []byte(index), 0o600); err != nil {
fmt.Println(err)
return
}
if err := os.WriteFile(statusFile, []byte(status), 0o600); err != nil {
fmt.Println(err)
return
}
cache, err := apt.Load(apt.LoadOptions{ListsDir: dir, StatusFile: statusFile, HostArch: "amd64"})
if err != nil {
fmt.Println(err)
return
}
plan, err := cache.Plan(apt.PlanRequest{Install: []string{"mta-a"}}, apt.PlanOptions{})
if err != nil {
fmt.Println(err)
return
}
for _, ch := range plan.Changes {
fmt.Println(ch.Kind, ch.Package.Name, "-", ch.Reason.Kind)
}
}
Output: remove mta-b - conflict install mta-a - requested
func (*Cache) ResolveDeps ¶
func (c *Cache) ResolveDeps(seeds []string) ([]*PackageInfo, []string, error)
ResolveDeps resolves what installing seeds would add. It returns the packages to download, dependencies before dependents (Pre-Depends and Depends alike, in the order they are written), and the names that neither a package nor a Provides of the index covers.
A seed is a dependency in control-file syntax: "foo", "foo:arm64", "foo (>= 1.2)", "a | b"; one seed string may hold several, comma separated. A malformed one fails with an error wrapping deb.ErrInvalidControlFormat. A seed also asks for the newest version, as apt-get install does: an installed package with a newer version in the index is listed again, to be upgraded. A seed qualified with an architecture that has no such package falls back to the host architecture, then to any.
The resolution follows apt, over every version the indexes carry:
- A dependency is met by an installed or already selected package first, in the order of its alternatives; only then is a package chosen, the first alternative that can be installed, and of it the highest version that satisfies the constraint ("<<", "<=", "=", ">=", ">>"). Versions older than the installed one are not offered, and an installed package is upgraded only when a dependency needs it.
- A virtual package is met by a package that Provides it. A versioned dependency is met only by a versioned Provides ("foo (= 1.2)"), never by a bare one (Debian Policy 7.5). Among providers the higher Priority wins, then the one read last from the indexes, as apt does.
- A package that Conflicts with or Breaks an installed or selected one, or the other way round, is refused and the next candidate is tried; when none is left the error is a *ConflictError inside an *UnsatisfiedError. Unlike apt, installed packages are never removed.
- Multi-Arch: a dependency of an architecture A package is met by an A or all package, or by a Multi-Arch: foreign package of any architecture (the host's is preferred); "name:any" only by Multi-Arch: allowed; "name:native" by the host architecture; "name:arch" by that one. Dependencies are read for the architecture of the package that declares them.
Differences from apt-get install --no-install-recommends, on purpose (use Cache.Plan for the behaviour of apt itself):
- apt looks only at the candidate (the highest version), so a constraint it fails ("foo (<< 3)" with 3 available) is unsatisfiable to it; here the highest version that does satisfy it is taken.
- apt resolves a clash with an installed package by removing it, and a Breaks by upgrading or removing the broken one. Here the candidate is refused and the next one tried, and the clash is an error when none is left; nothing is ever removed or upgraded to make room, which is what an extractor that must leave the host's packages alone needs.
- Pin priorities and apt's pkgProblemResolver scoring are not modelled, nor is the ordering of configuration (Pre-Depends loops).
A dependency that no candidate satisfies fails with an *UnsatisfiedError (ErrUnsatisfiable); an installed package a new version would break counts as one too. A name the index does not know at all is not an error: it is listed in the second result. The result is deterministic. A chain deeper than a few thousand packages fails with ErrDependencyDepth, and a hostile index that makes backtracking explode with ErrResolveLimit.
Example ¶
package main
import (
"fmt"
"github.com/M0Rf30/pkgformat/deb"
"github.com/M0Rf30/pkgformat/deb/apt"
)
func main() {
c := apt.NewCache("amd64")
depends, err := deb.ParseRelations("libfoo (>= 2.0), mta | postfix, unknown-tool")
if err != nil {
fmt.Println(err)
return
}
for _, p := range []*apt.PackageInfo{
{Name: "app", Architecture: "amd64", HasCandidate: true, Version: "1.0",
Filename: "pool/main/a/app/app_1.0_amd64.deb", Depends: depends},
{Name: "libfoo", Architecture: "amd64", HasCandidate: true, Version: "1.9",
Filename: "pool/main/libf/libfoo/libfoo_1.9_amd64.deb"},
{Name: "libfoo", Architecture: "amd64", HasCandidate: true, Version: "2.1",
Filename: "pool/main/libf/libfoo/libfoo_2.1_amd64.deb"},
{Name: "exim4", Architecture: "amd64", HasCandidate: true, Version: "4.96",
Filename: "pool/main/e/exim4/exim4_4.96_amd64.deb",
Provides: []deb.Relation{{Name: "mta"}}},
} {
c.AddEntry(p)
}
order, unresolved, err := c.ResolveDeps([]string{"app"})
if err != nil {
fmt.Println(err)
return
}
for _, p := range order {
fmt.Println(p.Name, p.Version)
}
fmt.Println("unresolved:", unresolved)
}
Output: libfoo 2.1 exim4 4.96 app 1.0 unresolved: [unknown-tool]
func (*Cache) ResolveVirtual ¶
ResolveVirtual returns the name of the concrete package ResolveDeps prefers for a virtual package (the highest priority, then the provider read last), or name itself when it is a real package (it has a candidate) or unknown.
func (*Cache) Versions ¶ added in v0.3.1
func (c *Cache) Versions(name string) []PackageInfo
Versions returns every known version of the named package, the highest first, from the first architecture Lookup would find it under.
type Change ¶ added in v0.4.0
type Change struct {
// Kind is what happens to the package.
Kind ChangeKind
// Package is the version installed afterwards; for a removal the
// installed version that goes.
Package *PackageInfo
// From is the installed version an upgrade or downgrade replaces; nil
// otherwise.
From *PackageInfo
// Reason says why.
Reason Reason
// Auto is true for an install or upgrade that leaves the package marked
// as automatically installed: a dependency, not a request. A caller that
// writes apt's extended states file records these.
Auto bool
}
Change is one step of a Plan.
type ChangeKind ¶ added in v0.4.0
type ChangeKind uint8
ChangeKind is what a plan does to one package.
const ( // ChangeInstall installs a package that is not installed. ChangeInstall ChangeKind = iota + 1 // ChangeUpgrade replaces an installed version by a higher one. ChangeUpgrade // ChangeDowngrade replaces an installed version by a lower one (a pin // above 1000 asks for it). ChangeDowngrade // ChangeRemove removes an installed package. ChangeRemove )
func (ChangeKind) String ¶ added in v0.4.0
func (k ChangeKind) String() string
String names the kind.
type ConflictError ¶ added in v0.3.1
type ConflictError struct {
// Package is the package that was refused ("name:arch version").
Package string
// With is the package it clashes with.
With string
// WithInstalled is true when With is installed, false when it was selected
// earlier in the same resolution.
WithInstalled bool
// Kind is "Conflicts" or "Breaks".
Kind string
// Relation is the relation as written in the declaring package.
Relation string
// Reverse is true when With declares the relation and Package is the
// target; false when Package declares it.
Reverse bool
}
ConflictError reports a package that cannot be installed because it conflicts with, or breaks, a package that is installed or already selected, or the other way round. It matches ErrConflict.
func (*ConflictError) Error ¶ added in v0.3.1
func (e *ConflictError) Error() string
Error names both packages and the relation.
func (*ConflictError) Is ¶ added in v0.3.1
func (e *ConflictError) Is(target error) bool
Is matches ErrConflict.
type DownloadOptions ¶
type DownloadOptions struct {
// Client performs the transfers. Nil builds one without an overall timeout,
// which would abort a large package on a slow link.
Client *httpclient.Client
// Concurrency caps the parallel transfers. Zero selects 6.
Concurrency int
// Progress, when set, is called after each chunk of a package with its
// file name, the bytes on disk and the expected size. It must be safe for
// concurrent use.
Progress func(name string, done, total int64)
}
DownloadOptions configures Download and DownloadClosure. The zero value is valid.
type ExtendedStatesError ¶ added in v0.4.0
ExtendedStatesError is the error Load joins for an extended states file it could not read: the file is unreadable, over MaxExtendedStatesBytes (ErrTooLarge), or holds more than 1048576 paragraphs (ErrTooManyExtendedStates). A missing file is not an error: apt treats it as no package being automatic.
func (*ExtendedStatesError) Error ¶ added in v0.4.0
func (e *ExtendedStatesError) Error() string
Error names the file and the cause.
func (*ExtendedStatesError) Unwrap ¶ added in v0.4.0
func (e *ExtendedStatesError) Unwrap() error
Unwrap exposes the cause to errors.Is and errors.As.
type KeyNotFoundError ¶ added in v0.4.0
type KeyNotFoundError struct {
// Fingerprints are the missing fingerprints, upper-case, without the "!".
Fingerprints []string
}
KeyNotFoundError reports the fingerprints of a Signed-By option that no searched keyring holds. It matches deb.ErrNoTrustAnchor.
func (*KeyNotFoundError) Error ¶ added in v0.4.0
func (e *KeyNotFoundError) Error() string
Error lists the missing fingerprints.
func (*KeyNotFoundError) Unwrap ¶ added in v0.4.0
func (e *KeyNotFoundError) Unwrap() error
Unwrap makes the error match deb.ErrNoTrustAnchor.
type LoadOptions ¶
type LoadOptions struct {
// ListsDir is the directory holding the downloaded Packages indexes, named
// the way apt names them ("<host>_<path>_dists_<suite>_<comp>_binary-<arch>_Packages[.ext]").
// Empty loads no index.
ListsDir string
// StatusFile is the dpkg status database to overlay, to set Installed. Empty
// skips it.
StatusFile string
// ExtendedStatesFile is apt's extended states file
// (/var/lib/apt/extended_states), whose "Auto-Installed: 1" paragraphs set
// [PackageInfo.AutoInstalled] on the installed versions. It is read after
// the status database, so it needs StatusFile to mark anything. Empty skips
// it, and a file that does not exist marks nothing.
ExtendedStatesFile string
// Sources resolve the BaseURL of every index: an index file named after a
// source's host and path takes that source's URL.
Sources []Source
// HostArch is the architecture unqualified names resolve to. Empty selects
// the one of the running program.
HostArch string
// Logger receives one debug record per file loaded and one per stanza that
// is skipped. Nil is silent.
Logger *slog.Logger
}
LoadOptions says where a Cache is read from. Every field is optional.
type OrderError ¶ added in v0.4.0
type OrderError struct {
// Kind says what went wrong.
Kind OrderKind
// Package is the package the failure is about, as "name:arch".
Package string
// Cycle lists the packages being configured when the failure came up,
// from the first appearance of Package to Package again: for two
// packages that Pre-Depend on each other, "a b a".
Cycle []string
// Detail is apt's wording of the failure.
Detail string
}
OrderError reports a plan the unpack and configure steps cannot carry out. It matches ErrOrderLoop, ErrOrderRemoval or ErrOrderSimulation according to its Kind.
Example ¶
Two packages that Pre-Depend on each other cannot be configured. The plan fails as apt-get does, with an error that carries the cycle.
package main
import (
"errors"
"fmt"
"os"
"path/filepath"
"github.com/M0Rf30/pkgformat/deb/apt"
)
// exampleCache loads an index, a dpkg status file and an apt extended states
// file written to a scratch directory.
func exampleCache(index, status, states string) (*apt.Cache, error) {
dir, err := os.MkdirTemp("", "plan")
if err != nil {
return nil, err
}
defer os.RemoveAll(dir)
files := map[string]string{
"example.org_dists_stable_main_binary-amd64_Packages": index,
"status": status,
"extended_states": states,
}
for name, content := range files {
if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0o600); err != nil {
return nil, err
}
}
return apt.Load(apt.LoadOptions{
ListsDir: dir,
StatusFile: filepath.Join(dir, "status"),
ExtendedStatesFile: filepath.Join(dir, "extended_states"),
HostArch: "amd64",
})
}
func main() {
cache, err := exampleCache("Package: a\nVersion: 1\nArchitecture: amd64\nPre-Depends: b\n\n"+
"Package: b\nVersion: 1\nArchitecture: amd64\nPre-Depends: a\n\n", "", "")
if err != nil {
fmt.Println(err)
return
}
_, err = cache.Plan(apt.PlanRequest{Install: []string{"a"}}, apt.PlanOptions{})
var oe *apt.OrderError
fmt.Println(errors.Is(err, apt.ErrOrderLoop), errors.As(err, &oe))
fmt.Println(oe.Kind, oe.Cycle)
}
Output: true true loop [a:amd64 b:amd64 a:amd64]
func (*OrderError) Error ¶ added in v0.4.0
func (e *OrderError) Error() string
Error gives apt's message and the cycle.
func (*OrderError) Is ¶ added in v0.4.0
func (e *OrderError) Is(target error) bool
Is matches the sentinel of the Kind.
type OrderKind ¶ added in v0.4.0
type OrderKind uint8
OrderKind says why a plan could not be ordered.
const ( // OrderLoop: a package cannot be configured because its Pre-Depends // form a cycle ("Couldn't configure X, probably a dependency cycle"). OrderLoop OrderKind = iota // OrderUnconfigured: packages were left unconfigured. OrderUnconfigured // OrderEssentialRemoval: an essential (or depended-on-by-essential) // package would have to be removed temporarily. OrderEssentialRemoval // OrderEarlyRemove: a package could not be removed or deconfigured to // make way for another. OrderEarlyRemove // OrderSimulation: replaying the steps broke a dependency. OrderSimulation )
type PackageInfo ¶
type PackageInfo struct {
// Name is the package name ("gcc", "libssl-dev").
Name string
// Architecture is the Architecture field ("amd64", "all", "arm64").
Architecture string
// Essential is true for "Essential: yes".
Essential bool
// MultiArch is the Multi-Arch field ("same", "foreign", "allowed" or "").
MultiArch string
// Priority is the Priority field ("required", "optional", ...). It orders
// the candidates of a virtual package.
Priority string
// Section is the Section field ("admin", "metapackages", "oldlibs"). The
// auto-remover of [Cache.Plan] reads it for the packages of the sections
// apt treats specially.
Section string
// Installed is true when the dpkg status database reports this version as
// installed (see [deb.Status.Installed]).
Installed bool
// HasCandidate is true when this version is in an apt index, that is, it
// can be downloaded. An installed version that no index carries any more
// has none.
HasCandidate bool
// Filename is the path of the .deb relative to the repository base URL
// ("pool/main/g/gcc/gcc_12.2.0-14_amd64.deb").
Filename string
// SHA256 is the expected SHA-256 of the .deb, hex encoded.
SHA256 string
// Size is the expected size of the .deb in bytes.
Size int64
// BaseURL is the repository URL Filename is relative to, such as
// "https://ports.ubuntu.com/ubuntu-ports/". Empty for packages that only
// come from the dpkg status database, which cannot be downloaded.
BaseURL string
// Depends is the Depends field, one [deb.Alternatives] per entry.
Depends []deb.Alternatives
// PreDepends is the same for Pre-Depends. Resolution treats both alike.
PreDepends []deb.Alternatives
// Recommends is the Recommends field. [Cache.Plan] installs these with a
// package when [PlanOptions.InstallRecommends] says so, and keeps them
// from being auto-removed.
Recommends []deb.Alternatives
// Suggests is the same for Suggests, installed when
// [PlanOptions.InstallSuggests] says so.
Suggests []deb.Alternatives
// Held is true when the dpkg status database holds the installed version
// ("Status: hold ok installed"): [Cache.Plan] neither upgrades nor removes
// it, whatever [PlanOptions.Held] says.
Held bool
// AutoInstalled is true when the extended states file of
// [LoadOptions.ExtendedStatesFile] marks the installed version as
// installed to satisfy a dependency ("Auto-Installed: 1"), which makes it
// a candidate for [PlanRequest.AutoRemove].
AutoInstalled bool
// Conflicts is the Conflicts field.
Conflicts []deb.Relation
// Breaks is the Breaks field.
Breaks []deb.Relation
// Provides is the Provides field: the virtual packages, with the version
// of a versioned one ("foo (= 1.2)").
Provides []deb.Relation
// Version is the Version field.
Version string
// SourceName and SourceVersion are the source package the version was
// built from: the Source field, which defaults to Name and, when it carries
// a version in parentheses, that one, else Version. Phased updates are
// seeded with them.
SourceName, SourceVersion string
// PhasedUpdatePercentage is the Phased-Update-Percentage field; nil when
// the version has none.
PhasedUpdatePercentage *int
// Releases lists the Release files of the indexes the version was read
// from, in load order; empty for a version only the status database or a
// hand-built entry knows. Pin matching and the Not-Automatic rules read
// them.
Releases []*ReleaseInfo
}
PackageInfo is the subset of a package's control fields that dependency resolution and downloading need. One value describes one version of one package on one architecture.
Example (Held) ¶
Packages dpkg holds are neither upgraded nor removed, however the request is made; PlanOptions.Held adds holds the status database does not know.
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/M0Rf30/pkgformat/deb/apt"
)
// exampleCache loads an index, a dpkg status file and an apt extended states
// file written to a scratch directory.
func exampleCache(index, status, states string) (*apt.Cache, error) {
dir, err := os.MkdirTemp("", "plan")
if err != nil {
return nil, err
}
defer os.RemoveAll(dir)
files := map[string]string{
"example.org_dists_stable_main_binary-amd64_Packages": index,
"status": status,
"extended_states": states,
}
for name, content := range files {
if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0o600); err != nil {
return nil, err
}
}
return apt.Load(apt.LoadOptions{
ListsDir: dir,
StatusFile: filepath.Join(dir, "status"),
ExtendedStatesFile: filepath.Join(dir, "extended_states"),
HostArch: "amd64",
})
}
func main() {
index := "Package: kept\nVersion: 2\nArchitecture: amd64\n\nPackage: moved\nVersion: 2\nArchitecture: amd64\n\n"
status := "Package: kept\nStatus: hold ok installed\nVersion: 1\nArchitecture: amd64\n\n" +
"Package: moved\nStatus: install ok installed\nVersion: 1\nArchitecture: amd64\n\n"
cache, err := exampleCache(index, status, "")
if err != nil {
fmt.Println(err)
return
}
plan, err := cache.Plan(apt.PlanRequest{Upgrade: apt.UpgradeSafe}, apt.PlanOptions{})
if err != nil {
fmt.Println(err)
return
}
for _, ch := range plan.Changes {
fmt.Println(ch.Kind, ch.Package.Name, ch.From.Version, "->", ch.Package.Version)
}
for _, h := range plan.Held {
fmt.Println("held:", h.Name)
}
}
Output: upgrade moved 1 -> 2 held: kept
func (PackageInfo) ArchitectureAll ¶
func (p PackageInfo) ArchitectureAll() bool
ArchitectureAll reports whether the package is architecture-independent.
func (PackageInfo) MultiArchForeign ¶
func (p PackageInfo) MultiArchForeign() bool
MultiArchForeign reports whether one copy of the package on the host is meant to serve every architecture (Multi-Arch: foreign or allowed): tools and daemons that run on the build host, which must not be qualified with a target architecture during cross-compilation. Multi-Arch: same, the -dev libraries, is deliberately excluded. The resolver itself follows apt more closely: only "foreign" satisfies a dependency from another architecture, and only "allowed" satisfies one written "name:any".
func (PackageInfo) MultiArchSame ¶
func (p PackageInfo) MultiArchSame() bool
MultiArchSame reports whether the package must be installed once per architecture (Multi-Arch: same).
type PhasedModel ¶ added in v0.4.0
type PhasedModel int
PhasedModel selects which generation of apt's phased-update logic a Policy reproduces. The three differ in details that decide whether one machine gets an update, so the one matching the apt being mimicked must be chosen; the zero value is the current one.
const ( // PhasedCurrent is apt 3.3.0 and later: the draw is uniform over 0..99 and // an update is held back when the draw is at least the percentage, so 0% // holds everyone back and 100% nobody. A version in a "-security" suite // between the installed and the candidate version, the candidate included, // lifts the hold. PhasedCurrent PhasedModel = iota // PhasedPre33 is apt 2.7.11 up to 3.2.x, Debian 13's apt among them: the // draw is uniform over 0..100 and an update is held back when the draw is // above the percentage, so a machine is in phase with probability // (percentage+1)/101, and 0% still lets one machine in a hundred and one // through. The security rule is as in [PhasedCurrent]. PhasedPre33 // PhasedPre2711 is apt before 2.7.11, Debian 12's apt among them. The draw // is that of [PhasedPre33]; the security rule only looks at the versions // between the installed one and the candidate, not at the candidate. PhasedPre2711 )
type Pin ¶ added in v0.4.0
type Pin struct {
// Packages are the whitespace separated names of the Package field: plain
// names, globs ("lib*"), regular expressions ("/^lib.*-dev$/"), "src:name"
// for every binary package built from a source package, and any of them
// with an architecture ("name:arch"). Nil for "Package: *", which pins
// package files rather than versions.
Packages []string
// Type is the kind of the Pin field.
Type PinType
// Data is the rest of the Pin field after its type word.
Data string
// Priority is the Pin-Priority; [PriorityNever] for "never".
Priority int
// Explanation is the free-form Explanation field.
Explanation string
}
Pin is one record of an apt preferences file.
type PinType ¶ added in v0.4.0
type PinType int
PinType is what a pin's Pin field selects versions by.
const ( // PinRelease matches the Release file a version comes from: "a=stable,c=main", // a bare archive or codename, a version number, or "*". PinRelease PinType = iota // PinVersion matches the version string, with the glob rules of apt. PinVersion // PinSourceVersion matches the version of the source package. PinSourceVersion // PinOrigin matches the host name of the archive; "" selects local files. PinOrigin )
type Plan ¶ added in v0.4.0
type Plan struct {
// Install is the packages to install.
Install []*PackageInfo
// Upgrade is the new versions of installed packages.
Upgrade []*PackageInfo
// Downgrade is the older versions to install over installed ones.
Downgrade []*PackageInfo
// Remove is the installed versions to remove.
Remove []*PackageInfo
// Held is the installed packages kept at their version though a newer
// candidate exists.
Held []*PackageInfo
// Manual is the installed packages that were automatically installed and
// that the request names without the plan changing them: they become
// manually installed ("set to manually installed" of apt-get), so a later
// auto-removal keeps them. A named package the plan installs or upgrades
// is manually installed too; [Change.Auto] reports it.
Manual []*PackageInfo
// AutoRemovable is the installed packages that were installed
// automatically and that nothing needs any more, though the plan does
// not remove them (apt-get's "no longer required" list). With
// [PlanRequest.AutoRemove] they are in Remove instead.
AutoRemovable []*PackageInfo
// Unresolved is the requested names no package matched.
Unresolved []string
// Changes lists every change with its reason, in the order apt unpacks
// and removes the packages.
Changes []Change
}
Plan is what Cache.Plan decides: the changes that bring the installed system to the state the request asks for, the way "apt-get -s" computes them.
Install lists the packages new to the system, Upgrade and Downgrade the installed packages that change version, Remove the installed packages that go. Changes lists them in the order apt carries the steps out, which each of the other lists keeps: the order of the "Inst" and "Remv" lines of "apt-get -s" (see the Planning section of the package documentation). Held lists the installed packages that have a newer candidate the plan did not take (the "kept back" of apt). Unresolved lists the names of the request that no index knows.
The PackageInfo values point into the cache and must not be modified.
type PlanError ¶ added in v0.4.0
type PlanError struct {
// Broken is why each broken package is broken.
Broken []error
}
PlanError reports that no consistent plan exists: the packages that remain broken after the resolver has done all it can, one error each (an *UnsatisfiedError or a *ConflictError). It matches ErrUnresolvable; the causes are visible to errors.Is and errors.As, so a plan that fails on a conflict matches ErrConflict too.
type PlanOptionError ¶ added in v0.4.0
type PlanOptionError struct {
// Option is the name of the field.
Option string
// Value is the offending value.
Value string
// Err is the cause.
Err error
}
PlanOptionError reports a PlanOptions value that cannot be used, such as a NeverAutoRemove entry that is not a regular expression. It matches ErrPlanOption.
func (*PlanOptionError) Error ¶ added in v0.4.0
func (e *PlanOptionError) Error() string
Error names the option, the value and the cause.
func (*PlanOptionError) Is ¶ added in v0.4.0
func (e *PlanOptionError) Is(target error) bool
Is matches ErrPlanOption.
func (*PlanOptionError) Unwrap ¶ added in v0.4.0
func (e *PlanOptionError) Unwrap() error
Unwrap exposes the cause.
type PlanOptions ¶ added in v0.4.0
type PlanOptions struct {
// Policy selects the candidate version of every package from the pins of
// a preferences file. Nil selects the highest version of the most
// trusted index: priority 500, 100 for a NotAutomatic index that is
// ButAutomaticUpgrades, 1 for one that is NotAutomatic, and never a
// version older than the installed one.
Policy *Policy
// Held lists packages dpkg holds ("hold" in the status database): they
// are neither upgraded nor removed by the resolver. A name without an
// architecture holds every architecture of the package.
//
// Packages that the status database holds ([PackageInfo.Held]) are held
// as well; Held adds to them, for a caller that keeps its holds elsewhere.
Held []string
// InstallRecommends is APT::Install-Recommends: install the Recommends of
// every package the plan installs or upgrades, when they can be met
// without removing anything; one that cannot is skipped. Nil is apt's
// default for "apt-get install", true.
InstallRecommends *bool
// InstallSuggests is APT::Install-Suggests, the same for Suggests. Nil is
// apt's default, false.
InstallSuggests *bool
// AutoRemoveRecommendsImportant is APT::AutoRemove::RecommendsImportant:
// a package an installed package Recommends counts as needed by it, so
// [PlanRequest.AutoRemove] keeps it. Nil is apt's default, true.
AutoRemoveRecommendsImportant *bool
// AutoRemoveSuggestsImportant is APT::AutoRemove::SuggestsImportant, the
// same for Suggests. Nil is apt's default, true.
AutoRemoveSuggestsImportant *bool
// NeverAutoRemove lists regular expressions (APT::NeverAutoRemove) of
// package names that auto-removal keeps. Nil selects
// [DefaultNeverAutoRemove]; an empty non-nil slice keeps nothing.
NeverAutoRemove []string
// MaxSteps bounds the work of a plan, so a hostile index cannot make it
// run for ever. Zero selects DefaultPlanSteps.
MaxSteps int
}
PlanOptions configures Cache.Plan.
Example (InstallRecommends) ¶
With apt's default, Install-Recommends, a new package brings its Recommends along when they can be installed; InstallRecommends turns that off, as --no-install-recommends does.
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/M0Rf30/pkgformat/deb/apt"
)
// exampleCache loads an index, a dpkg status file and an apt extended states
// file written to a scratch directory.
func exampleCache(index, status, states string) (*apt.Cache, error) {
dir, err := os.MkdirTemp("", "plan")
if err != nil {
return nil, err
}
defer os.RemoveAll(dir)
files := map[string]string{
"example.org_dists_stable_main_binary-amd64_Packages": index,
"status": status,
"extended_states": states,
}
for name, content := range files {
if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0o600); err != nil {
return nil, err
}
}
return apt.Load(apt.LoadOptions{
ListsDir: dir,
StatusFile: filepath.Join(dir, "status"),
ExtendedStatesFile: filepath.Join(dir, "extended_states"),
HostArch: "amd64",
})
}
func printPlan(plan *apt.Plan) {
for _, ch := range plan.Changes {
fmt.Println(ch.Kind, ch.Package.Name, "-", ch.Reason.Kind)
}
}
func main() {
cache, err := exampleCache("Package: app\nVersion: 1\nArchitecture: amd64\nRecommends: extra, absent\n\n"+
"Package: extra\nVersion: 1\nArchitecture: amd64\n\n", "", "")
if err != nil {
fmt.Println(err)
return
}
for _, recommends := range []bool{true, false} {
plan, err := cache.Plan(apt.PlanRequest{Install: []string{"app"}}, apt.PlanOptions{InstallRecommends: &recommends})
if err != nil {
fmt.Println(err)
return
}
fmt.Println("recommends:", recommends)
printPlan(plan)
}
}
Output: recommends: true install app - requested install extra - recommends recommends: false install app - requested
type PlanRequest ¶ added in v0.4.0
type PlanRequest struct {
// Install names the packages to install, as a dependency field is
// written: "curl", "curl:arm64", "curl (>= 8)", "libfoo (= 1.2)". A
// relation with a version constraint selects the highest version that
// meets it as the candidate, as "apt-get install curl=VERSION" does.
// Several alternatives ("a | b") pick the first that exists.
Install []string
// Remove names installed packages to remove ("apt-get remove"). What
// depends on them goes too, unless the dependency can be met otherwise.
Remove []string
// Upgrade asks for a system upgrade on top of Install and Remove.
Upgrade UpgradeMode
// FixBroken is "apt-get -f" (and "apt-get install -f" with no packages):
// repair the installed packages whose dependencies are unmet, installing
// what they need and removing what cannot be saved, then do the upgrade
// the request asks for. As in apt it acts only on a request that names no
// package. Without it a broken system makes a request without packages
// fail, and one with packages fail unless the packages themselves repair
// every problem.
FixBroken bool
// AutoRemove is "apt-get autoremove" and "--auto-remove": after the rest
// of the request, remove the installed packages that were installed
// automatically (see [PackageInfo.AutoInstalled]) and that nothing
// installed needs any more. Without it such packages are only listed in
// [Plan.AutoRemovable]. "apt-get purge" and "autopurge" differ from the
// removal only in what dpkg does with configuration files, so they plan
// the same changes.
AutoRemove bool
}
PlanRequest says what a plan is to achieve.
Example (AutoRemove) ¶
A package that was installed automatically and that nothing installed needs any more is what "apt-get autoremove" removes; the marks come from apt's extended states file.
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/M0Rf30/pkgformat/deb/apt"
)
// exampleCache loads an index, a dpkg status file and an apt extended states
// file written to a scratch directory.
func exampleCache(index, status, states string) (*apt.Cache, error) {
dir, err := os.MkdirTemp("", "plan")
if err != nil {
return nil, err
}
defer os.RemoveAll(dir)
files := map[string]string{
"example.org_dists_stable_main_binary-amd64_Packages": index,
"status": status,
"extended_states": states,
}
for name, content := range files {
if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0o600); err != nil {
return nil, err
}
}
return apt.Load(apt.LoadOptions{
ListsDir: dir,
StatusFile: filepath.Join(dir, "status"),
ExtendedStatesFile: filepath.Join(dir, "extended_states"),
HostArch: "amd64",
})
}
func printPlan(plan *apt.Plan) {
for _, ch := range plan.Changes {
fmt.Println(ch.Kind, ch.Package.Name, "-", ch.Reason.Kind)
}
}
func main() {
index := ""
status := "Package: app\nStatus: install ok installed\nVersion: 1\nArchitecture: amd64\nDepends: lib\n\n" +
"Package: lib\nStatus: install ok installed\nVersion: 1\nArchitecture: amd64\n\n" +
"Package: old\nStatus: install ok installed\nVersion: 1\nArchitecture: amd64\n\n"
states := "Package: lib\nArchitecture: amd64\nAuto-Installed: 1\n\n" +
"Package: old\nArchitecture: amd64\nAuto-Installed: 1\n"
cache, err := exampleCache(index, status, states)
if err != nil {
fmt.Println(err)
return
}
plan, err := cache.Plan(apt.PlanRequest{AutoRemove: true}, apt.PlanOptions{})
if err != nil {
fmt.Println(err)
return
}
printPlan(plan)
}
Output: remove old - auto-remove
type Policy ¶ added in v0.4.0
type Policy struct {
// contains filtered or unexported fields
}
Policy decides pin priorities and candidate versions, as apt's pkgPolicy. It is immutable and safe for concurrent use.
func NewPolicy ¶ added in v0.4.0
func NewPolicy(prefs *Preferences, opts PolicyOptions) *Policy
NewPolicy builds a Policy from preferences (nil for none) and options.
Example ¶
package main
import (
"fmt"
"github.com/M0Rf30/pkgformat/deb/apt"
)
func main() {
prefs, _ := apt.ParsePreferences(`Package: hello
Pin: release a=testing
Pin-Priority: 900
`)
stable := &apt.ReleaseInfo{Suite: "stable", Codename: "bookworm"}
testing := &apt.ReleaseInfo{Suite: "testing", Codename: "trixie"}
backports := &apt.ReleaseInfo{Suite: "bookworm-backports", NotAutomatic: true, ButAutomaticUpgrades: true}
versions := []*apt.PackageInfo{
{Name: "hello", Architecture: "amd64", Version: "2.10-4", Releases: []*apt.ReleaseInfo{testing}},
{Name: "hello", Architecture: "amd64", Version: "2.10-3~bpo12+1", Releases: []*apt.ReleaseInfo{backports}},
{Name: "hello", Architecture: "amd64", Version: "2.10-2", Releases: []*apt.ReleaseInfo{stable}},
}
policy := apt.NewPolicy(prefs, apt.PolicyOptions{NativeArch: "amd64", DefaultRelease: "stable"})
for _, v := range versions {
fmt.Println(v.Version, policy.Priority(v))
}
fmt.Println("candidate:", policy.Candidate(versions, nil).Version)
}
Output: 2.10-4 900 2.10-3~bpo12+1 100 2.10-2 990 candidate: 2.10-2
func (*Policy) Candidate ¶ added in v0.4.0
func (p *Policy) Candidate(versions []*PackageInfo, installed *PackageInfo) *PackageInfo
Candidate returns the version apt would install of a package, as apt's pkgPolicy::GetCandidateVer: versions are the available versions of one package, highest version first; installed is the installed one or nil (a version of versions flagged Installed stands in for a nil installed). It is the first version of the highest priority; a version older than the installed one only counts from priority 1000, and priority 0 never counts. It returns nil when no version qualifies.
Example ¶
package main
import (
"fmt"
"github.com/M0Rf30/pkgformat/deb/apt"
)
func main() {
stable := &apt.ReleaseInfo{Suite: "stable"}
newer := &apt.PackageInfo{Name: "tool", Architecture: "amd64", Version: "2.0", Releases: []*apt.ReleaseInfo{stable}}
older := &apt.PackageInfo{Name: "tool", Architecture: "amd64", Version: "1.0", Releases: []*apt.ReleaseInfo{stable}}
installed := &apt.PackageInfo{Name: "tool", Architecture: "amd64", Version: "3.0", Installed: true}
policy := apt.NewPolicy(nil, apt.PolicyOptions{NativeArch: "amd64"})
// Without a pin of 1000 or more, apt never installs a version older than
// the installed one: the installed one stays.
fmt.Println(policy.Candidate([]*apt.PackageInfo{installed, newer, older}, installed).Version)
pinned, _ := apt.ParsePreferences("Package: tool\nPin: version 1.0\nPin-Priority: 1001\n")
fmt.Println(apt.NewPolicy(pinned, apt.PolicyOptions{NativeArch: "amd64"}).Candidate([]*apt.PackageInfo{installed, newer, older}, installed).Version)
}
Output: 3.0 1.0
func (*Policy) Phased ¶ added in v0.4.0
func (p *Policy) Phased(v, installed *PackageInfo) bool
Phased reports whether apt holds back an upgrade from installed to v because v is a phased update this machine is not yet part of (apt-get upgrade, full upgrade and the upgradable lists). It is false without an installed version (a new installation is never phased), when v is the installed version, when v has no Phased-Update-Percentage or it is 100, when PolicyOptions AlwaysIncludePhased is set, when the machine has no identifier or runs in a chroot, and when v comes from a security suite. It is true under NeverIncludePhased.
With only v at hand the security rule looks at v's own suites; use Policy.PhasedIn to let it see the versions between the installed one and v too. With PolicyOptions PhasePolicy, phasing is part of the pin priorities instead and Phased answers for every version, installed or not.
Example ¶
package main
import (
"fmt"
"github.com/M0Rf30/pkgformat/deb/apt"
)
func main() {
percentage := 20
installed := &apt.PackageInfo{Name: "tool", Architecture: "amd64", Version: "1.0", Installed: true}
update := &apt.PackageInfo{Name: "tool", Architecture: "amd64", Version: "1.1", PhasedUpdatePercentage: &percentage}
// The draw only depends on the source package, its version and the machine.
fmt.Println("draw:", apt.PhasedDraw("tool", "1.1", "3e6a1d7dbd3a4b7b9d3c0f3a2b6c9f10", apt.PhasedCurrent))
for _, id := range []string{"3e6a1d7dbd3a4b7b9d3c0f3a2b6c9f10", "0000000000000000000000000000000b", ""} {
policy := apt.NewPolicy(nil, apt.PolicyOptions{MachineID: id, NativeArch: "amd64"})
fmt.Printf("%q held back: %v\n", id, policy.Phased(update, installed))
}
}
Output: draw: 89 "3e6a1d7dbd3a4b7b9d3c0f3a2b6c9f10" held back: true "0000000000000000000000000000000b" held back: false "" held back: false
func (*Policy) PhasedIn ¶ added in v0.4.0
func (p *Policy) PhasedIn(versions []*PackageInfo, v, installed *PackageInfo) bool
PhasedIn is Policy.Phased with the versions of the package, the highest first, for the security rule: a version in a "-security" suite lifts the hold when it is v or lies between the installed version and v.
func (*Policy) Priority ¶ added in v0.4.0
func (p *Policy) Priority(v *PackageInfo) int
Priority is the pin priority of a version, as apt's pkgPolicy::GetPriority: the priority of the first pin for its package that matches, unless every package file of the version is never-pinned; otherwise the highest priority of its package files (its indexes and, when installed, the status file), which a "Package: *" pin, PolicyOptions.DefaultRelease or the flags of the Release file set. 0 means the version is no candidate and negative that it must not be installed; PriorityNever is the "never" pin.
A version that has no Releases and is available (a hand-built entry) counts as one ordinary archive, priority 500 unless a "release *" pin says otherwise.
type PolicyOptions ¶ added in v0.4.0
type PolicyOptions struct {
// DefaultRelease is APT::Default-Release (apt-get -t): versions of that
// release (matched as archive, then codename) get priority 990 unless a
// pin says otherwise. Any release pin expression works ("a=stable",
// "o=Debian,n=bookworm", "12*"). apt refuses a value no source has; a
// Policy cannot, and then simply pins nothing.
DefaultRelease string
// MachineID is the identifier phased updates are seeded with (the content
// of /etc/machine-id); empty disables phasing (every version is in phase).
// Only the first line counts.
MachineID string
// AlwaysIncludePhased and NeverIncludePhased are
// APT::Get::Always-Include-Phased-Updates and Never-Include-Phased-Updates.
AlwaysIncludePhased, NeverIncludePhased bool
// NativeArch is the native architecture: a "Package:" name without
// architecture pins that one. Empty selects the one of the running
// program.
NativeArch string
// PhasedBehavior selects the generation of apt's phasing logic; the zero
// value is the current one.
PhasedBehavior PhasedModel
// PhasePolicy is APT::Get::Phase-Policy: phased versions that are not
// yet in phase get a pin priority of at most 1 instead of being held back
// at upgrade time.
PhasePolicy bool
// IgnoreSourceVersionPins reads the source-version pin type as apt before
// 2.7 (Debian 12 and older) does: it does not know it, warns, and drops
// the stanza.
IgnoreSourceVersionPins bool
// InChroot reports that the program runs in a chroot (ischroot -t), where
// apt does not phase updates.
InChroot bool
}
PolicyOptions configures a Policy.
type Preferences ¶ added in v0.4.0
type Preferences struct {
// Pins in the order apt sees them: /etc/apt/preferences first, then the
// files of preferences.d by name.
Pins []Pin
// Warnings lists what apt only warns about: unknown pin types, a version
// pin for "Package: *", a missing preferences.d.
Warnings []string
}
Preferences is the content of apt_preferences(5) files, as the ordered pins apt applies: the first pin that matches a version wins.
func LoadPreferences ¶ added in v0.4.0
func LoadPreferences(file, dir string) (*Preferences, error)
LoadPreferences reads the preferences file and the "*.pref" files of preferences.d (files without extension too; names must be made of letters, digits, '_', '-', '.' and ':'). An empty path is skipped and a path that does not exist adds nothing, like apt. Files are read in name order and a failing file does not stop the next one.
The result is never nil; the error joins one *PreferencesError per refused record and the I/O errors, and matches ErrTooLarge for a file or directory over its bound.
Example ¶
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/M0Rf30/pkgformat/deb/apt"
)
func main() {
dir, err := os.MkdirTemp("", "apt-")
if err != nil {
fmt.Println(err)
return
}
defer func() { _ = os.RemoveAll(dir) }()
_ = os.WriteFile(filepath.Join(dir, "preferences"), []byte("Package: *\nPin: release a=stable\nPin-Priority: 700\n"), 0o600)
_ = os.MkdirAll(filepath.Join(dir, "preferences.d"), 0o750)
_ = os.WriteFile(filepath.Join(dir, "preferences.d", "backports.pref"), []byte("Package: hello\nPin: release a=bookworm-backports\nPin-Priority: 800\n"), 0o600)
// Files with other extensions are not read, as in apt.
_ = os.WriteFile(filepath.Join(dir, "preferences.d", "notes.txt"), []byte("not a preferences file"), 0o600)
prefs, err := apt.LoadPreferences(filepath.Join(dir, "preferences"), filepath.Join(dir, "preferences.d"))
if err != nil {
fmt.Println(err)
return
}
for _, pin := range prefs.Pins {
fmt.Println(pin.Packages, pin.Data, pin.Priority)
}
}
Output: [] a=stable 700 [hello] a=bookworm-backports 800
func ParsePreferences ¶ added in v0.4.0
func ParsePreferences(content string) (*Preferences, error)
ParsePreferences reads one preferences file as apt does: records separated by blank lines, "#" lines are comments, field names are case-insensitive and a record without a Pin field is ignored.
Like apt it stops at the first record it refuses and returns a *PreferencesError for it; the Preferences is never nil and holds the pins read before. A line without a colon ends the file silently, as in apt.
Example ¶
package main
import (
"fmt"
"github.com/M0Rf30/pkgformat/deb/apt"
)
func main() {
prefs, err := apt.ParsePreferences(`Explanation: prefer the stable release, take a few packages from testing
Package: *
Pin: release a=stable
Pin-Priority: 700
Package: hello libhello*
Pin: release a=testing
Pin-Priority: 900
Package: nonfree-driver
Pin: version 535.*
Pin-Priority: 1001
`)
if err != nil {
fmt.Println(err)
return
}
for _, pin := range prefs.Pins {
fmt.Println(pin.Packages, pin.Type, pin.Data, pin.Priority)
}
}
Output: [] release a=stable 700 [hello libhello*] release a=testing 900 [nonfree-driver] version 535.* 1001
Example (Error) ¶
package main
import (
"errors"
"fmt"
"github.com/M0Rf30/pkgformat/deb/apt"
)
func main() {
_, err := apt.ParsePreferences("Package: hello\nPin: release a=stable\nPin-Priority: never\n")
fmt.Println(err)
fmt.Println(errors.Is(err, apt.ErrNeverPin))
}
Output: apt: preferences record 1 (Package: hello): apt: Pin-Priority never needs Package: *: "never" true
func (*Preferences) Add ¶ added in v0.4.0
func (p *Preferences) Add(other *Preferences)
Add appends the pins and warnings of other.
type PreferencesError ¶ added in v0.4.0
type PreferencesError struct {
// File is the file the record was read from; empty for ParsePreferences.
File string
// Record is the 1-based number of the record in the file, counting only
// records that have a field.
Record int
// Package is the Package field of the record, when it has one.
Package string
// Value is the offending field value, when there is one.
Value string
// Reason is the sentinel that says what is wrong.
Reason error
}
PreferencesError reports a preferences record apt refuses. It matches ErrPreferences and the reason, one of ErrNoPackageHeader, ErrPinPriority or ErrNeverPin.
func (*PreferencesError) Error ¶ added in v0.4.0
func (e *PreferencesError) Error() string
Error implements error.
func (*PreferencesError) Unwrap ¶ added in v0.4.0
func (e *PreferencesError) Unwrap() []error
Unwrap lets errors.Is match both ErrPreferences and the reason.
type Reason ¶ added in v0.4.0
type Reason struct {
// Kind is the cause category; zero when the engine has nothing to say.
Kind ReasonKind
// Cause is the package ("name:arch version") whose installation led to
// the change.
Cause string
// Relation is the dependency or conflict as written, when there is one.
Relation string
}
Reason records why a package is in a plan.
type ReasonKind ¶ added in v0.4.0
type ReasonKind uint8
ReasonKind says why a package is in a Plan.
const ( // ReasonRequested: the request named the package, or an upgrade mode // selected it. ReasonRequested ReasonKind = iota + 1 // ReasonDependency: a new package that a dependency of Cause needs. ReasonDependency // ReasonRecommends: a new package that a Recommends of Cause brings, with // [PlanOptions.InstallRecommends]. ReasonRecommends // ReasonSuggests: a new package that a Suggests of Cause brings, with // [PlanOptions.InstallSuggests]. ReasonSuggests // ReasonAutoRemove: removed because it was installed to satisfy a // dependency and nothing that is installed needs it any more // ([PlanRequest.AutoRemove]). ReasonAutoRemove // ReasonUpgradeDependency: an installed package upgraded because the new // version of Cause needs it, or no longer fits with it. ReasonUpgradeDependency // ReasonSameSource: an installed package upgraded along with the other // binaries of the source package of Cause. ReasonSameSource // ReasonConflict: removed because Cause Conflicts with it. ReasonConflict // ReasonBreaks: removed because Cause Breaks it and it has no version // that Cause allows. ReasonBreaks // ReasonBrokenDependency: removed because a dependency of it can no // longer be met after the other changes (Cause names the dependency or // the package that went). ReasonBrokenDependency )
func (ReasonKind) String ¶ added in v0.4.0
func (k ReasonKind) String() string
String names the kind.
type ReleaseInfo ¶ added in v0.4.0
type ReleaseInfo struct {
// Origin, Label, Suite (the archive, "a=" of a pin), Codename ("n="),
// Version ("v=") and Component ("c=") as the Release file and the index
// name them. Architecture is the architecture of the index ("b=").
Origin, Label, Suite, Codename, Version, Component, Architecture string
// Site is the host name of the source the index came from, matched by
// "origin" pins; empty for a local source.
Site string
// NotAutomatic and ButAutomaticUpgrades are the Release flags of those
// names: NotAutomatic repositories have pin priority 1, or 100 together
// with ButAutomaticUpgrades.
NotAutomatic, ButAutomaticUpgrades bool
}
ReleaseInfo is what apt keeps of the Release file of the index a version was read from: the properties package pins match against, and the repository's automatic-upgrade flags.
type Source ¶
type Source struct {
// Type is TypeDeb or TypeDebSrc. The zero value means TypeDeb.
Type SourceType
// URL is the repository base URL with a trailing slash
// ("https://archive.ubuntu.com/ubuntu/"). Besides http(s) it may carry
// the schemes file:, copy:, cdrom:, mirror+http(s):// and mirror+file://
// (and, accepted by the parser, anything else apt knows, which Update
// refuses with ErrUnsupportedScheme). It is kept as written, apart from
// the trailing slash; ListFileNameFor applies apt's normalisation.
URL string
// Suite is the distribution ("jammy", "bookworm-updates"). A suite that
// ends in a slash ("./", "debian/$(ARCH)/") names an exact path: the
// repository is flat, the Release lies in that directory and Components is
// empty.
Suite string
// Components lists the archive areas ("main", "universe").
Components []string
// Architectures restricts the source to these architectures. Empty means
// the default architecture.
Architectures []string
// ArchitecturesAdd and ArchitecturesRemove are the Architectures-Add and
// Architectures-Remove options (arch+= and arch-=): architectures added
// to, or taken off, the set the source is fetched for.
ArchitecturesAdd, ArchitecturesRemove []string
// Languages are the Languages option for the Translation indexes ("en",
// "de", "none"); empty means the default (the translations apt would
// fetch for the environment, here "none" unless UpdateOptions says
// otherwise).
Languages []string
// LanguagesAdd and LanguagesRemove are the Languages-Add and
// Languages-Remove options (lang+= and lang-=).
LanguagesAdd, LanguagesRemove []string
// Targets are the Targets option: the kinds of index to fetch, such as
// "Packages", "Translations", "Contents", "Sources". Empty selects the
// default of the Type: Packages for deb, Sources for deb-src.
Targets []string
// TargetsAdd and TargetsRemove are the Targets-Add and Targets-Remove
// options (target+= and target-=).
TargetsAdd, TargetsRemove []string
// SignedBy is the Signed-By option verbatim: key fingerprints (separated
// by comma or blank, each optionally ending in "!"), paths of keyring
// files or directories, or an inline armored PGP public key block. "" means
// the default keyrings. LoadKeyring interprets it.
SignedBy string
// Trusted, AllowInsecure, AllowWeak, AllowDowngradeToInsecure,
// CheckValidUntil and CheckDate are the options of those names (trusted,
// allow-insecure, allow-weak, allow-downgrade-to-insecure,
// check-valid-until, check-date).
Trusted, AllowInsecure, AllowWeak, AllowDowngradeToInsecure, CheckValidUntil, CheckDate Switch
// ValidUntilMin and ValidUntilMax are the Valid-Until-Min and
// Valid-Until-Max options, as durations. Zero is unset.
ValidUntilMin, ValidUntilMax time.Duration
// DateMaxFuture is the Date-Max-Future option: how far past the local clock
// the Date of the Release may lie. Zero is unset.
DateMaxFuture time.Duration
// ByHash is the By-Hash option.
ByHash ByHashMode
// PDiffs is the PDiffs option.
PDiffs Switch
// Snapshot is the Snapshot option as written: a snapshot id for archives
// that serve them, "enable" or "disable" (or another yes/no spelling), or
// "" when unset.
Snapshot string
// Options holds the options the parser does not interpret (InRelease-Path,
// target identifiers such as Contents-deb=no, anything unknown), with their
// names as written, so that a writer can reproduce them.
Options map[string]string
}
Source is one apt repository: a base URL, a suite and its components, with the options of a sources.list line or deb822 stanza.
A one-line entry and a deb822 stanza with one Types, URIs and Suites value each give one Source; a stanza with several of them gives one per type, URI and suite, all with the same Components and options.
func LoadSources ¶
LoadSources reads the configured sources. listFile is a sources.list style file and listDir a directory of *.list (one-line) and *.sources (deb822) files, read in name order, as apt reads /etc/apt/sources.list and sources.list.d. Either may be empty, and either may be missing: apt tolerates that, and so does LoadSources.
In the directory only regular files (or links to them) count, named with letters, digits, "_", "-" and "." and not starting with a dot or ending with one, as apt's run-parts style rule has it; other names are ignored.
A file that exists but cannot be read, or is larger than MaxSourcesFileBytes, is skipped and reported in the returned error, next to the sources that did load; so is every entry that did not parse, as a *SourceError carrying the file name and line. The error is an errors.Join of them, empty when all went well.
func ParseSources822 ¶
ParseSources822 parses the deb822 format of *.sources files after sources.list(5). A stanza gives one Source per Types, URIs and Suites value (all with the stanza's Components); the capitalised option names are Architectures, Architectures-Add, Architectures-Remove, Languages, Languages-Add, Languages-Remove, Targets, Targets-Add, Targets-Remove, Trusted, Signed-By (a list of fingerprints, keyring paths, or an inline armored key block whose empty lines are written " ."), Check-Valid-Until, Valid-Until-Min, Valid-Until-Max (seconds), Check-Date, Date-Max-Future (seconds), By-Hash (yes, no or force), PDiffs, Snapshot, Allow-Insecure, Allow-Weak and Allow-Downgrade-To-Insecure, matched case-insensitively. List values are separated by blanks and newlines. Other fields are kept in Source.Options under their name as written.
A stanza with "Enabled: no" (or another false spelling) is skipped. Errors are reported as in ParseSourcesList: a bad stanza is skipped and described by a *SourceError whose Line is its first line.
Input over MaxSourcesFileBytes is refused with ErrTooLarge.
Example ¶
package main
import (
"fmt"
"github.com/M0Rf30/pkgformat/deb/apt"
)
func main() {
sources, err := apt.ParseSources822(`Types: deb deb-src
URIs: https://deb.debian.org/debian
Suites: bookworm bookworm-updates
Components: main contrib
Architectures-Add: i386
Signed-By: /usr/share/keyrings/debian-archive-keyring.gpg
Types: deb
URIs: file:///srv/local
Suites: ./
Enabled: no
`)
if err != nil {
fmt.Println(err)
return
}
for _, s := range sources {
fmt.Println(s.Type, s.URL, s.Suite, s.EffectiveArchitectures("amd64"))
}
}
Output: deb https://deb.debian.org/debian/ bookworm [amd64 i386] deb https://deb.debian.org/debian/ bookworm-updates [amd64 i386] deb-src https://deb.debian.org/debian/ bookworm [amd64 i386] deb-src https://deb.debian.org/debian/ bookworm-updates [amd64 i386]
func ParseSourcesList ¶
ParseSourcesList parses the one-line format of /etc/apt/sources.list and *.list files after sources.list(5):
deb [arch=amd64 signed-by=/usr/share/keyrings/k.gpg] https://archive.ubuntu.com/ubuntu/ jammy main universe deb-src [arch+=i386 lang=de,fr target-=Contents-deb] http://deb.example.org/ stable main
Both types (deb, deb-src) and every URI scheme are returned; filter with Source.IsSource and Source.Scheme. A line gives one Source holding all the components. Options sit between brackets, separated by blanks; values of list options are separated by commas, and "+=" and "-=" add to or remove from the default instead of replacing it (arch, lang and target). Words may be quoted with double quotes and carry %xx escapes, and a "#" starts a comment unless it is inside the brackets.
A suite that ends in a slash is an exact path and takes no component.
The parser is as strict as apt about the shape of a line, and stricter about option values, which apt silently reads as false or 0: an entry that is not well formed (unknown type, no URI, no suite or component, a URI without a scheme, an option that is not key=value) or whose known option has an invalid value is skipped and reported as a *SourceError, all of them joined into the returned error next to the sources that did parse. Options this package does not know are kept in Source.Options.
Input over MaxSourcesFileBytes is refused with ErrTooLarge.
Example ¶
package main
import (
"fmt"
"github.com/M0Rf30/pkgformat/deb/apt"
)
func main() {
sources, err := apt.ParseSourcesList(`
# main archive
deb [arch=amd64] https://deb.debian.org/debian bookworm main contrib
deb-src https://deb.debian.org/debian bookworm main
`)
if err != nil {
fmt.Println(err)
return
}
for _, s := range sources {
fmt.Println(s.Type, s.URL, s.Suite, s.Components, s.Architectures)
}
}
Output: deb https://deb.debian.org/debian/ bookworm [main contrib] [amd64] deb-src https://deb.debian.org/debian/ bookworm [main] []
Example (Errors) ¶
package main
import (
"errors"
"fmt"
"github.com/M0Rf30/pkgformat/deb/apt"
)
func main() {
sources, err := apt.ParseSourcesList(`deb [trusted=perhaps] http://a.example/ stable main
deb http://b.example/ stable main
deb ftp://c.example/debian stable main
`)
// The good lines are returned next to the error that describes the bad one.
var se *apt.SourceError
if errors.As(err, &se) {
fmt.Println("line", se.Line, "option", se.Option, errors.Is(err, apt.ErrInvalidOption))
}
for _, s := range sources {
fmt.Println(s.Scheme(), s.URL)
}
}
Output: line 1 option trusted true http http://b.example/ ftp ftp://c.example/debian/
func (*Source) EffectiveArchitectures ¶ added in v0.4.0
EffectiveArchitectures returns the architectures the source is fetched for: Architectures (defaultArch when that is empty), plus ArchitecturesAdd, minus ArchitecturesRemove, without duplicates, in that order. apt's implicit "all" is not added; it holds for every source whose Release lists it.
func (*Source) EffectiveLanguages ¶ added in v0.4.0
EffectiveLanguages returns the translation languages of the source: Languages (defaults when that is empty), plus LanguagesAdd, minus LanguagesRemove. "none" is kept as a language, as apt does.
func (*Source) EffectiveTargets ¶ added in v0.4.0
EffectiveTargets returns the kinds of index the source fetches. Without a Targets option the default is Packages for a deb source, with Translations after it when EffectiveLanguages(defaultLanguages) holds a language other than "none"; and Sources for a deb-src source. TargetsAdd and TargetsRemove are applied to the result.
Example ¶
package main
import (
"fmt"
"github.com/M0Rf30/pkgformat/deb/apt"
)
func main() {
src := apt.Source{Type: apt.TypeDeb, TargetsAdd: []string{"Contents"}}
fmt.Println(src.EffectiveTargets([]string{"none"}))
fmt.Println(src.EffectiveTargets([]string{"en"}))
}
Output: [Packages Contents] [Packages Translations Contents]
func (*Source) ExpandArch ¶ added in v0.4.0
ExpandArch returns a copy of the source with the $(ARCH) variable of URL and Suite replaced by arch, as apt does with its native architecture.
func (*Source) Flat ¶ added in v0.4.0
Flat reports whether the suite is an exact path (it ends in a slash), so that the repository has no dists/ tree and no components.
type SourceError ¶ added in v0.4.0
type SourceError struct {
// Path is the file the entry is in, "" when parsing a string.
Path string
// Line is the 1-based line of the entry (of the first line of a deb822
// stanza), 0 when unknown.
Line int
// Option is the option or field at fault, as written, or "".
Option string
// Err says what is wrong.
Err error
}
SourceError reports an entry of a sources file that was skipped. Parsers return every such error joined (errors.Join) next to the sources that did parse. It matches ErrMalformedSource, ErrInvalidOption, ErrInvalidSignedBy or whatever else Err wraps, with errors.Is.
func (*SourceError) Error ¶ added in v0.4.0
func (e *SourceError) Error() string
Error renders "apt: path:line: option "x": reason".
func (*SourceError) Unwrap ¶ added in v0.4.0
func (e *SourceError) Unwrap() error
Unwrap exposes Err to errors.Is and errors.As.
type SourceType ¶ added in v0.4.0
type SourceType string
SourceType is the Types value of a source: what kind of archive it is.
const ( // TypeDeb is a binary package archive ("deb"). TypeDeb SourceType = "deb" // TypeDebSrc is a source package archive ("deb-src"). TypeDebSrc SourceType = "deb-src" )
type Switch ¶ added in v0.4.0
type Switch uint8
Switch is a yes/no source option that may be left to the global configuration. The zero value means unset.
type UnsatisfiedError ¶ added in v0.3.1
type UnsatisfiedError struct {
// Package is the package whose dependency it is ("name:arch version"), or
// "" for a name given to ResolveDeps.
Package string
// Dependency is the dependency as written ("foo (>= 2) | bar").
Dependency string
// Reason says why nothing satisfied it when no candidate was tried.
Reason string
// Causes are the errors of the candidates that were tried, in order.
Causes []error
}
UnsatisfiedError reports a dependency that no available package satisfies: no version of the name meets the constraint, or every candidate was refused (see Causes). It matches ErrUnsatisfiable.
func (*UnsatisfiedError) Error ¶ added in v0.3.1
func (e *UnsatisfiedError) Error() string
Error describes the dependency and, when there are any, the reasons.
func (*UnsatisfiedError) Is ¶ added in v0.3.1
func (e *UnsatisfiedError) Is(target error) bool
Is matches ErrUnsatisfiable.
func (*UnsatisfiedError) Unwrap ¶ added in v0.3.1
func (e *UnsatisfiedError) Unwrap() []error
Unwrap exposes the candidate failures to errors.Is and errors.As.
type UpdateError ¶
type UpdateError struct {
Errors []error
}
UpdateError is the error Update returns when sources fail: one error for each (source, architecture) or component that did not update. The indexes that did update are in place regardless.
func (*UpdateError) Error ¶
func (e *UpdateError) Error() string
Error lists the failures, one per line.
func (*UpdateError) Unwrap ¶
func (e *UpdateError) Unwrap() []error
Unwrap exposes the failures to errors.Is and errors.As.
type UpdateOptions ¶
type UpdateOptions struct {
// ListsDir is the directory the indexes and Release files are written to,
// under the names apt gives them. Update creates it. A Cache reads it back
// through LoadOptions.ListsDir.
ListsDir string
// DefaultArch is the architecture of sources that name none. Empty selects
// the one of the running program.
DefaultArch string
// DefaultLanguages are the Translation languages of sources without a
// Languages option (Acquire::Languages). Empty fetches no translations.
DefaultLanguages []string
// DefaultKeyrings are the keyring files and directories that trust sources
// without a Signed-By option (/etc/apt/trusted.gpg.d, /usr/share/keyrings,
// /etc/apt/keyrings, /etc/apt/trusted.gpg on a Debian host). See LoadKeyring.
DefaultKeyrings []string
// AllowUnverified accepts a repository for which no trust anchor exists, a
// Release signed by an unknown key, or one without a signature. A signature
// that is present and does not verify is rejected regardless. The
// allow-insecure source option does the same for one source, and
// trusted=no refuses it for one source.
AllowUnverified bool
// DisableByHash stops Update from fetching indexes by their digest, which
// it otherwise does for a Release that says Acquire-By-Hash: yes (the
// source option By-Hash overrides it per source).
DisableByHash bool
// DisablePDiffs stops Update from patching an index it already has with
// the Packages.diff of the repository instead of fetching it whole
// (Acquire::PDiffs); the source option PDiffs overrides it per source.
DisablePDiffs bool
// Client performs the transfers. Nil builds one with the default policy.
Client *httpclient.Client
// Concurrency caps the sources updated at once. Zero selects
// min(2*GOMAXPROCS, 8).
Concurrency int
// Now is the clock the Date and Valid-Until checks of a Release use. Nil is
// time.Now.
Now func() time.Time
// Logger receives progress and warnings. Nil is silent.
Logger *slog.Logger
}
UpdateOptions configures Update. Only ListsDir is required.
type UpgradeMode ¶ added in v0.4.0
type UpgradeMode uint8
UpgradeMode selects a system upgrade a PlanRequest asks for.
const ( // UpgradeNone upgrades nothing beyond what the request needs. UpgradeNone UpgradeMode = iota // UpgradeSafe is "apt-get upgrade": every installed package that can be // upgraded is, without installing a new package or removing one. A // package that would need either is kept back. UpgradeSafe // UpgradeWithNew is "apt upgrade" (apt-get upgrade --with-new-pkgs): as // UpgradeSafe, but new packages may be installed to meet the new // dependencies of an upgrade. UpgradeWithNew // UpgradeFull is "apt-get dist-upgrade": the best upgrade, removing or // installing packages as needed. UpgradeFull )
func (UpgradeMode) String ¶ added in v0.4.0
func (m UpgradeMode) String() string
String names the mode the way the apt command line does.
type VirtualPackageError ¶ added in v0.4.0
type VirtualPackageError struct {
// Name is the virtual package.
Name string
// Providers are the packages that could be installed for it
// ("name:arch version").
Providers []string
}
VirtualPackageError reports a request for a virtual package that several packages provide: apt does not choose between them for the user. It matches ErrVirtualPackage.
func (*VirtualPackageError) Error ¶ added in v0.4.0
func (e *VirtualPackageError) Error() string
Error names the providers.
func (*VirtualPackageError) Is ¶ added in v0.4.0
func (e *VirtualPackageError) Is(target error) bool
Is matches ErrVirtualPackage.
Source Files
¶
- cache.go
- doc.go
- download.go
- errors.go
- extended_states.go
- keyring.go
- load.go
- phased.go
- pinmatch.go
- policy.go
- preferences.go
- resolve.go
- resolve_auto.go
- resolve_engine.go
- resolve_install.go
- resolve_order.go
- resolve_plan.go
- resolve_policy.go
- resolve_problem.go
- resolve_revdeps.go
- resolve_upgrade.go
- sources.go
- sources_load.go
- sources_parse.go
- sources_uri.go
- transport.go
- update.go
- update_index.go
- update_pdiff.go
- update_release.go