apk

package
v1.4.11 Latest Latest
Warning

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

Go to latest
Published: Oct 10, 2026 License: Apache-2.0 Imports: 63 Imported by: 11

Documentation

Overview

Copyright 2023 Chainguard, Inc.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Index

Constants

View Source
const (
	// IndexCacheEntriesEnv sets how many parsed APKINDEX generations stay in
	// memory.
	IndexCacheEntriesEnv = "APKO_INDEX_CACHE_ENTRIES"
	// ResolverCacheEntriesEnv sets how many distinct index combinations the
	// resolver and disqualify caches each retain.
	ResolverCacheEntriesEnv = "APKO_RESOLVER_CACHE_ENTRIES"
)

Environment variables that override the sizes of the process-wide in-memory caches. Both default to 64 entries. Every entry pins a parsed index generation (index cache) or a full package resolver built from one (resolver and disqualify caches), so raising either trades memory for hit rate. Long-running multi-tenant services that resolve against many distinct repository sets can raise them; the apko CLI does not need to.

View Source
const (
	DefaultKeyRingPath       = "/etc/apk/keys"
	DefaultSystemKeyRingPath = "/usr/share/apk/keys/"
)
View Source
const (
	// DefaultHTTPResponseSize is the default maximum size for HTTP responses (2 GB).
	DefaultHTTPResponseSize = 2 << 30
)
View Source
const DefaultMaxAPKIndexDecompressedSize = 300 << 20

DefaultMaxAPKIndexDecompressedSize is the maximum decompressed size for APKINDEX archives (300 MB). This protects against gzip bombs where a small compressed file expands to a huge size.

Variables

View Source
var (
	// ErrEmptyName is returned when an archive entry name is empty. Such a name
	// has no valid representation on disk, and it previously reached an
	// unguarded index into its first byte.
	ErrEmptyName = errors.New("name is empty")

	// ErrControlCharacter is returned when an archive entry name contains a
	// byte below 0x20 or the DEL byte 0x7f.
	ErrControlCharacter = errors.New("name contains a control character")

	// ErrEmbeddedNewline is returned when a value would be written into a
	// line-oriented database as more than one line.
	//
	// This is an alias for types.ErrEmbeddedNewline rather than a second
	// sentinel with the same meaning. The .PKGINFO parser rejects the same
	// class of value one layer earlier, and a caller matching only one of two
	// look-alike sentinels would silently miss half the cases -- which is the
	// coupling these sentinels exist to remove, not to reintroduce across a
	// package boundary.
	ErrEmbeddedNewline = types.ErrEmbeddedNewline

	// ErrInstallAborted is returned by any install or record write attempted
	// after an earlier package install failed. It always wraps the original
	// failure, so a caller can match this to mean "this instance is finished"
	// while still recovering the cause with errors.As.
	ErrInstallAborted = errors.New("refusing to continue after an earlier package install failed")
)

Reasons a package's data is refused. These are matchable with errors.Is, so a caller can distinguish the cases without parsing message text.

Functions

func ArchToAPK

func ArchToAPK(in string) string

func ArchiveFromIndex

func ArchiveFromIndex(apkindex *APKIndex) (archive io.Reader, err error)

func CompareVersions

func CompareVersions(actual, required Version) int

CompareVersions compares versions based on https://dev.gentoo.org/~ulm/pms/head/pms.html#x1-250003.2

func FetchKeyBytes added in v1.2.24

func FetchKeyBytes(ctx context.Context, client *http.Client, a auth.Authenticator, keyURL string) ([]byte, error)

FetchKeyBytes downloads a keyring from the given URL and returns its raw bytes. It applies the provided authenticator (which may be nil for anonymous fetches).

func IndexURL

func IndexURL(repo, arch string) string

IndexURL returns the full URL to the index file for the given repo and arch.

`repo` is the URL of the repository including the protocol, e.g. "https://packages.wolfi.dev/os".

`arch` is the architecture of the index, e.g. "x86_64" or "aarch64".

func NewRangeRetryTransport added in v1.0.2

func NewRangeRetryTransport(base http.RoundTripper) http.RoundTripper

NewRangeRetryTransport returns a transport that retries failed reads using HTTP Range requests.

func PackageToInstalled

func PackageToInstalled(pkg *Package) (out []string)

PackageToInstalled takes a Package and returns it as the string representation of lines in a /usr/lib/apk/db/installed file.

func ParseAlpineVersion added in v0.30.32

func ParseAlpineVersion(repo string) (version string, ok bool)

ParseAlpineVersion parses the Alpine version from a repository URL. Returns the version string (e.g., "v3.21") and true if successful.

func ScanRepositoryIndex added in v1.4.9

func ScanRepositoryIndex(ctx context.Context, repoURL string, keys map[string][]byte, arch string, fn func(record []byte) error, options ...IndexOption) (etag string, err error)

ScanRepositoryIndex fetches the index of the repository at repoURL for arch, verifies its signature against keys exactly as GetRepositoryIndexes does, and then calls fn with each package record of the index, in index order. No fn call happens unless the signature verifies.

Unlike GetRepositoryIndexes, it neither builds Packages nor caches anything, so its memory use is bounded by the size of the compressed index plus one record; a record larger than maxIndexRecordSize fails the scan. A record is the raw text of one package stanza, each line terminated by "\n" and the whole followed by the blank separator line, so ParsePackageIndex parses it into a single Package, or into none when the stanza names no package (a stanza a whole-index parse drops too). The record is only valid until fn returns. As with ParsePackageIndex, a trailing stanza that is not terminated by a blank line is ignored; records are not otherwise validated. An archive with more than one APKINDEX member is rejected.

repoURL is a plain repository URL or local path; "@tag" repository lines are not accepted. A non-nil error from fn stops the scan and is returned wrapped. The scan can also fail after fn has seen some records, as when the index exceeds the decompressed size limit or is malformed past them, so on any error the caller must discard every record it was given. The returned etag is an opaque token of the index's ETag, or "" when the server sent none or the repository is local.

The options honored are those that affect fetching and verification: WithHTTPClient, WithIndexAuthenticator, WithIgnoreSignatures, WithIgnoreSignatureForIndexes and WithIndexDecompressedMaxSize.

Types

type APK

type APK struct {

	// This is a map of arch to apk.APK for every arch in a mult-arch situation.
	// It's stuffed here to avoid plumbing it across every method, but it's optional.
	ByArch map[string]*APK
	// contains filtered or unexported fields
}

func New

func New(ctx context.Context, options ...Option) (*APK, error)

func (*APK) AddInstalledPackage

func (a *APK) AddInstalledPackage(pkg *Package, files []tar.Header) ([]byte, error)

AddInstalledPackage add a package to the list of installed packages and returns the _incremental_ diff installing the package had on the idb file.

func (*APK) CalculateWorld

func (a *APK) CalculateWorld(ctx context.Context, allpkgs []*RepositoryPackage) ([]*APKResolved, error)

func (*APK) DiscoverKeys added in v0.18.0

func (a *APK) DiscoverKeys(ctx context.Context, repository string) ([]Key, error)

func (*APK) FetchPackage

func (a *APK) FetchPackage(ctx context.Context, pkg FetchablePackage) (io.ReadCloser, error)

FetchPackage fetches the given package and returns a ReadCloser for its contents. This is only kept for backwards compatibility, prefer using packageGetter.GetPackage instead.

func (*APK) FixateWorld

func (a *APK) FixateWorld(ctx context.Context, sourceDateEpoch *time.Time) ([]InstalledDiff, error)

FixateWorld force apk's resolver to re-resolve the requested dependencies in /etc/apk/world.

func (*APK) GetInstalled

func (a *APK) GetInstalled() ([]*InstalledPackage, error)

getInstalledPackages get list of installed packages

func (*APK) GetRepositories

func (a *APK) GetRepositories() (repos []string, err error)

func (*APK) GetRepositoryIndexes

func (a *APK) GetRepositoryIndexes(ctx context.Context, ignoreSignatures bool) ([]NamedIndex, error)

GetRepositoryIndexes returns the indexes for the repositories in the specified root. The signatures for each index are verified unless ignoreSignatures is set to true.

func (*APK) GetWorld

func (a *APK) GetWorld() ([]string, error)

GetWorld - get list of packages that should be installed, according to /etc/apk/world

func (*APK) InitDB

func (a *APK) InitDB(ctx context.Context, buildRepos ...string) error

Initialize the APK database for a given build context. Assumes base directories are in place and checks them. Returns the list of files and directories and files installed and permissions, unless those files will be included in the installed database, in which case they can be retrieved via GetInstalled().

func (*APK) InitKeyring

func (a *APK) InitKeyring(ctx context.Context, keyFiles, extraKeyFiles []string) error

Installs the specified keys into the APK keyring inside the build context.

func (*APK) InstallPackageContents added in v1.2.43

func (a *APK) InstallPackageContents(ctx context.Context, sourceDateEpoch *time.Time, all []PackageContents) ([]InstalledDiff, error)

InstallPackageContents installs exactly the given packages, in the given order, from their supplied contents: no index is consulted, no dependency resolution happens, and nothing is fetched — the caller has already settled the set and supplies each member's contents.

func (*APK) InstallPackages

func (a *APK) InstallPackages(ctx context.Context, sourceDateEpoch *time.Time, allpkgs []InstallablePackage) ([]InstalledDiff, error)

func (*APK) ListInitFiles

func (a *APK) ListInitFiles() []tar.Header

ListInitFiles list the files that are installed during the InitDB phase.

func (*APK) ResolveAndCalculateWorld

func (a *APK) ResolveAndCalculateWorld(ctx context.Context) ([]*APKResolved, error)

func (*APK) ResolveWorld

func (a *APK) ResolveWorld(ctx context.Context) (toInstall []*RepositoryPackage, conflicts []string, err error)

ResolveWorld determine the target state for the requested dependencies in /etc/apk/world. Does not install anything.

func (*APK) SetRepositories

func (a *APK) SetRepositories(ctx context.Context, repos []string) error

SetRepositories sets the contents of /etc/apk/repositories file. The base directory of /etc/apk must already exist, i.e. this only works on an initialized APK database.

func (*APK) SetWorld

func (a *APK) SetWorld(ctx context.Context, packages []string) error

SetWorld sets the list of world packages intended to be installed. The base directory of /etc/apk must already exist, i.e. this only works on an initialized APK database.

type APKIndex

type APKIndex struct {
	Signature   []byte
	Description string
	Packages    []*Package
}

func IndexFromArchive

func IndexFromArchive(archive io.ReadCloser, opts ...IndexFromArchiveOption) (*APKIndex, error)

IndexFromArchive parses an APKINDEX archive. Options can be used to configure size limits to protect against gzip bombs.

type APKResolved

type APKResolved struct {
	Package *RepositoryPackage

	SignatureSize int
	SignatureHash []byte

	ControlSize int
	ControlHash []byte

	DataSize int
	DataHash []byte
}

func NewAPKResolved added in v0.26.0

func NewAPKResolved(pkg *RepositoryPackage, expanded *expandapk.APKExpanded) *APKResolved

func ResolveApk

func ResolveApk(ctx context.Context, source io.Reader) (*APKResolved, error)

type AlpineKeyFetchError added in v1.2.34

type AlpineKeyFetchError struct {
	Repository string
	Version    string
	Err        error
}

AlpineKeyFetchError reports a failure to retrieve signing keys for an Alpine package repository.

func (*AlpineKeyFetchError) Error added in v1.2.34

func (e *AlpineKeyFetchError) Error() string

func (*AlpineKeyFetchError) Unwrap added in v1.2.34

func (e *AlpineKeyFetchError) Unwrap() error

type Cache added in v0.19.3

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

func NewCache added in v0.19.3

func NewCache(etag bool) *Cache

NewCache returns a new Cache, which allows us to persist the results of HEAD requests for a given URL across multiple builds. This is generally desirable when building many images all at once, since we can eliminate round trips to HEAD the same e.g. APKINDEX repeatedly. However, this is not desirable for long-lived processes where we expected the APKINDEX to change over time and want to observe those changes and re-fetch the new APKINDEX. Since apko is used in both contexts, this knob is exposed, but very few people actually should be using apko as a library, so I'm mostly just talking to myself here. This used to be a process-wide global cache, which was great for the short-lived terraform module, but a terrible default behavior for a library.

Even if you don't want to cache HEAD requests, this is still useful for coalescing concurrent requests for the same resource when passing etag=false.

type ConstraintError

type ConstraintError struct {
	Constraint string
	Wrapped    error
}

func (*ConstraintError) Error

func (e *ConstraintError) Error() string

func (*ConstraintError) Unwrap

func (e *ConstraintError) Unwrap() error

type DateTime

type DateTime struct {
	time.Time
}

DateTime wrapper for time.Time because the date format is "YYYY-MM-DD"

func (DateTime) MarshalJSON

func (c DateTime) MarshalJSON() ([]byte, error)

func (*DateTime) UnmarshalJSON

func (c *DateTime) UnmarshalJSON(b []byte) error

type DepError

type DepError struct {
	Package *RepositoryPackage
	Wrapped error
}

func (*DepError) Error

func (e *DepError) Error() string

func (*DepError) Unwrap

func (e *DepError) Unwrap() error

type DisqualifiedError

type DisqualifiedError struct {
	Package *RepositoryPackage
	Wrapped error
}

func (*DisqualifiedError) Error

func (e *DisqualifiedError) Error() string

func (*DisqualifiedError) Unwrap

func (e *DisqualifiedError) Unwrap() error

type Executor

type Executor interface {
	Execute(name string, arg ...string) error
}

Executor provider of interface to execute commands, if used. Will be used primarily to execute scripts.

type FetchablePackage added in v0.25.7

type FetchablePackage interface {
	URL() string
	PackageName() string
}

FetchablePackage represents a minimal set of information needed to fetch a package.

func NewFetchablePackage added in v0.25.7

func NewFetchablePackage(pkgName, url string) FetchablePackage

NewFetchablePackage creates and returns a minimal implementation of FetchablePackage.

type FileConflictError added in v0.25.5

type FileConflictError struct {
	// The full path of the file that has conflicting origins.
	Path string

	// The origins of the file, as a map from the package name to the origin
	Origins map[string]string
}

FileConflictError is returned when a file has conflicting origins.

Generally, this is a user Config error. However, since this can happen both during Config resolution, and building - it is hard for users using chainguard.dev/apko as a library to flag this to the user as a user error.

To help with that, we create this structure error.

func (FileConflictError) Error added in v0.25.5

func (f FileConflictError) Error() string

func (FileConflictError) Is added in v0.25.5

func (f FileConflictError) Is(target error) bool

type FileExistsError

type FileExistsError struct {
	Path string
	Sha1 []byte
}

func (FileExistsError) Error

func (f FileExistsError) Error() string

func (FileExistsError) Is

func (f FileExistsError) Is(target error) bool

type IndexFromArchiveOption added in v1.1.0

type IndexFromArchiveOption func(*indexFromArchiveOpts)

IndexFromArchiveOption configures IndexFromArchive behavior.

func WithDecompressedMaxSize added in v1.1.0

func WithDecompressedMaxSize(size int64) IndexFromArchiveOption

WithDecompressedMaxSize sets the maximum decompressed size for the APKINDEX archive. Use 0 for default, or < 0 for unlimited.

type IndexOption

type IndexOption func(*indexOpts)

func WithHTTPClient

func WithHTTPClient(c *http.Client) IndexOption

func WithIgnoreSignatureForIndexes

func WithIgnoreSignatureForIndexes(noSignatureIndexes ...string) IndexOption

func WithIgnoreSignatures

func WithIgnoreSignatures(ignoreSignatures bool) IndexOption

func WithIndexAuthenticator added in v0.16.0

func WithIndexAuthenticator(a auth.Authenticator) IndexOption

func WithIndexDecompressedMaxSize added in v1.1.0

func WithIndexDecompressedMaxSize(size int64) IndexOption

type InstallablePackage

type InstallablePackage interface {
	URL() string
	PackageName() string
	ChecksumString() string
}

InstallablePackage represents a minimal set of information needed to install a package within an Image.

type InstalledDiff added in v0.29.4

type InstalledDiff struct {
	Package *Package
	Diff    []byte
}

InstalledDiff tracks a package and the incremental change it wrote to the installed database file. This is used by our layering mechanism to generate partial idb files per layer to satisfy scanners. Mostly, this just makes the return type of InstallPackages cleaner so it's easier to track which package produced which diff to the idb file.

type InstalledPackage

type InstalledPackage struct {
	Package
	Files []tar.Header
}

func ParseInstalled

func ParseInstalled(installed io.Reader) ([]*InstalledPackage, error)

parseInstalled parses an installed file. It returns the installed packages.

type InvalidEntryNameError added in v1.4.2

type InvalidEntryNameError struct {
	// Package is the name of the package the entry came from.
	Package string

	// Path is the offending entry name.
	Path string

	// Err is why the name was rejected: ErrEmptyName or ErrControlCharacter from
	// the install paths, or ErrEmbeddedNewline from the installed-database sink.
	Err error
}

InvalidEntryNameError is returned when an archive entry name cannot be used.

The apk installed database is a newline-delimited "<token>:<value>" format written from these names verbatim, so a control character -- a newline in particular -- would let a package forge additional records. Like FileConflictError, this is surfaced as its own type so that library consumers such as melange can report a malformed or malicious package as a package problem rather than an opaque build failure.

Use errors.As to recover the package and path, and errors.Is against ErrEmptyName, ErrControlCharacter or ErrEmbeddedNewline to distinguish the reason.

func (InvalidEntryNameError) Error added in v1.4.2

func (e InvalidEntryNameError) Error() string

func (InvalidEntryNameError) Unwrap added in v1.4.2

func (e InvalidEntryNameError) Unwrap() error

type InvalidFieldError added in v1.4.2

type InvalidFieldError = types.InvalidFieldError

InvalidFieldError is re-exported so that a caller which matched ErrEmbeddedNewline through this package can also recover the offending .PKGINFO field and value through it, rather than having to import pkg/apk/types for the error type after importing nothing else from it. This package already aliases PackageInfo and Package for the same reason.

type Key added in v0.18.0

type Key struct {
	ID    string
	Bytes []byte
}

func DiscoverKeys added in v0.18.1

func DiscoverKeys(ctx context.Context, client *http.Client, auth auth.Authenticator, repository string) ([]Key, error)

DiscoverKeys fetches the public keys for the repositories in the APK database using chainguard-style discovery.

type LocatablePackage added in v0.25.7

type LocatablePackage interface {
	URL() string
}

LocatablePackage represents a minimal set of information needed to locate a package for retrieval over a network.

type MalformedPackageError added in v1.4.2

type MalformedPackageError struct {
	// Package is the name of the offending package. Empty when the package name
	// is itself what was rejected.
	Package string

	// Field identifies what was wrong: "name" for the package name, or the
	// installed-database token of the offending record line, e.g. "T:".
	Field string

	// Value is the offending value.
	Value string

	// Err is why it was rejected: ErrEmptyName or ErrEmbeddedNewline.
	Err error
}

MalformedPackageError is returned when a package's own data, rather than one of its file names, would produce an installed-database record that is unsafe or unreadable.

Use errors.As to recover the field and value, and errors.Is against ErrEmptyName or ErrEmbeddedNewline for the reason.

func (MalformedPackageError) Error added in v1.4.2

func (e MalformedPackageError) Error() string

func (MalformedPackageError) Unwrap added in v1.4.2

func (e MalformedPackageError) Unwrap() error

type NamedIndex

type NamedIndex interface {
	Name() string
	Packages() []*RepositoryPackage
	Source() string
	Count() int
}

NamedIndex an index that contains all of its packages, as well as having an optional name and source. The name and source need not be unique.

func GetRepositoryIndexes

func GetRepositoryIndexes(ctx context.Context, repos []string, keys map[string][]byte, arch string, options ...IndexOption) ([]NamedIndex, error)

GetRepositoryIndexes returns the indexes for the named repositories, keys and archs. The signatures for each index are verified unless ignoreSignatures is set to true. The key-value pairs in the map for `keys` are the name of the key and the contents of the key. The name is just indicative. If it finds a match, it will use it. Else, it will try all keys.

func NewNamedRepositoryWithIndex

func NewNamedRepositoryWithIndex(name string, repo *RepositoryWithIndex) NamedIndex

type NoKeysFoundError

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

func (*NoKeysFoundError) Error

func (e *NoKeysFoundError) Error() string

type OfflineNetworkError added in v1.2.34

type OfflineNetworkError struct {
	Method string
	URL    string
}

OfflineNetworkError reports a network request blocked by offline mode.

func (*OfflineNetworkError) Error added in v1.2.34

func (e *OfflineNetworkError) Error() string

type Option

type Option func(*opts) error

func WithArch

func WithArch(arch string) Option

WithArch sets the architecture to use. If not provided, will use the default runtime.GOARCH.

func WithAuthenticator added in v0.16.0

func WithAuthenticator(a auth.Authenticator) Option

func WithCache

func WithCache(cacheDir string, offline bool, shared *Cache) Option

WithCache sets to use a cache directory for downloaded apk files and APKINDEX files. If not provided, will not cache.

If offline is true, only read from the cache and do not make any network requests to populate it.

func WithExecutor

func WithExecutor(executor Executor) Option

WithExecutor executor to use. Not currently used.

func WithFS

func WithFS(fs apkfs.FullFS) Option

WithFS sets the filesystem to use. If not provided, will use the OS filesystem based at root /.

func WithIgnoreIndexSignatures added in v0.16.0

func WithIgnoreIndexSignatures(ignore bool) Option

WithIgnoreIndexSignatures sets whether to ignore repository signature verification. Default is false.

func WithIgnoreMknodErrors

func WithIgnoreMknodErrors(ignore bool) Option

WithIgnoreMknodErrors sets whether to ignore errors when creating device nodes. Default is false.

func WithNoSignatureIndexes

func WithNoSignatureIndexes(noSignatureIndex ...string) Option

func WithOffline added in v1.2.34

func WithOffline(offline bool) Option

WithOffline controls whether network requests are permitted. Cached and local resources remain available in offline mode.

func WithPackageGetter added in v1.0.4

func WithPackageGetter(pg PackageGetter) Option

WithPackageGetter sets a custom PackageGetter for fetching, expanding, and caching packages. If not provided, a DefaultPackageGetter will be created automatically.

func WithSizeLimits added in v1.1.0

func WithSizeLimits(limits *SizeLimits) Option

WithSizeLimits sets size limits for APK operations.

func WithTransport added in v0.24.0

func WithTransport(t http.RoundTripper) Option

WithTransport allows explicitly setting the inner HTTP transport.

func WithVersion

func WithVersion(version string) Option

WithVersion sets the version to use for downloading keys and other purposes. If not provided, finds the latest stable.

type Package

type Package = types.Package

Package represents a single package with the information present in an APKINDEX.

func ParsePackage

func ParsePackage(ctx context.Context, apkPackage io.Reader, size uint64) (*Package, error)

ParsePackage parses a .apk file and returns a Package struct

func ParsePackageIndex

func ParsePackageIndex(apkIndexUnpacked io.Reader) ([]*Package, error)

ParsePackageIndex parses a plain (uncompressed) APKINDEX file. It returns an ApkIndex struct

type PackageContents added in v1.2.43

type PackageContents interface {
	// PkgInfo returns the package's parsed .PKGINFO.
	PkgInfo() (*types.PackageInfo, error)
	// ControlSection returns the package's control section exactly as
	// distributed — the compressed tar segment. This is the section's
	// identity-bearing form: its SHA1 is the checksum apk records for the
	// package.
	ControlSection() ([]byte, error)
	// ControlData returns the same section as the uncompressed tar stream,
	// which script and trigger extraction read. Carriers hold one form or
	// the other natively, and consumers need one or the other, so the
	// contract carries both rather than making every side convert.
	ControlData() ([]byte, error)
	// Size returns the package's total size in bytes, as recorded in the
	// installed database.
	Size() int64
	// Entries returns the package's install records in install order.
	Entries() ([]tar.Header, error)
	// FS opens an entry's content by its record name.
	FS() fs.FS
}

PackageContents is the per-package input to installation: the package's control-section metadata, its install records (tar headers, in install order), and a filesystem that opens each record's content by name. It abstracts the expanded APK so installation can be fed the same information from another carrier of it (e.g. a pre-indexed image of the package) without consulting the APK itself.

func ExpandedContents added in v1.2.43

func ExpandedContents(exp *expandapk.APKExpanded) PackageContents

ExpandedContents adapts an expanded APK to PackageContents.

type PackageDataStreamer added in v1.4.3

type PackageDataStreamer interface {
	PackageData() (io.ReadCloser, error)
}

PackageDataStreamer is the optional half of the PackageContents contract, for carriers that can hand over the whole data section as a single tar stream. The non-WriteHeaderer install path consumes that; a carrier holding only a pre-built index cannot produce it, which is why this is separate.

The stream is an io.ReadCloser rather than an *os.File on purpose. An *os.File is a name plus a file offset shared with every descriptor dup'd from it, and the only copy of a data section worth trusting has neither: it is unlinked, and it is read concurrently by the index that was built over it. Requiring a file would force a carrier to publish one.

type PackageFilter added in v1.4.9

type PackageFilter func(*RepositoryPackage) bool

PackageFilter reports whether a package may be considered during resolution. See PkgResolver.Filtered.

type PackageGetter added in v1.0.4

type PackageGetter interface {
	// GetPackage fetches and returns an expanded package.
	GetPackage(ctx context.Context, pkg InstallablePackage) (*expandapk.APKExpanded, error)
}

PackageGetter abstracts how packages are fetched and expanded.

type PackageInfo

type PackageInfo = types.PackageInfo

PackageInfo represents the information present in .PKGINFO.

func ParsePackageInfo

func ParsePackageInfo(apkPackage io.Reader) (*PackageInfo, hash.Hash, error)

ParsePackageInfo returns a parsed .PKGINFO from an APK reader and the control section hash.

type PackageRank added in v1.4.9

type PackageRank func(*RepositoryPackage) uint64

PackageRank places a package among the others a resolver considers for the same name. See PkgResolver.Ranked.

type ParsedConstraint added in v0.26.0

type ParsedConstraint struct {
	Name    string
	Version string
	// contains filtered or unexported fields
}

func ResolvePackageNameVersionPin added in v0.26.0

func ResolvePackageNameVersionPin(pkgName string) ParsedConstraint

func (ParsedConstraint) SatisfiedBy added in v0.26.0

func (p ParsedConstraint) SatisfiedBy(v Version) (bool, error)

type PkgResolver

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

PkgResolver resolves packages from a list of indexes. It is created with NewPkgResolver and passed a list of indexes. It then can be used to resolve the correct version of a package given version constraints, if any, as well as all the package and all of the required upstream dependencies. If provided multiple indexes, it will look for dependencies in all of the indexes. If you need to look only in a certain set, you should create a new PkgResolver with only those indexes, or narrow an existing one with Filtered. If the indexes change, you should generate a new pkgResolver.

func BuildPkgResolver added in v1.4.9

func BuildPkgResolver(ctx context.Context, indexes []NamedIndex) *PkgResolver

BuildPkgResolver creates a new PkgResolver from a list of indexes, like NewPkgResolver, but without the process-wide resolver cache: the resolver and the indexes it references are retained only for as long as the caller holds them. That holds only for resolutions that leave allArchs nil or use GetPackagesWithDependenciesByArch, as the multi-arch check of GetPackagesWithDependencies caches its indexes process-wide.

func NewPkgResolver

func NewPkgResolver(ctx context.Context, indexes []NamedIndex) *PkgResolver

NewPkgResolver creates a new pkgResolver from a list of indexes. The indexes are anything that implements NamedIndex.

Resolvers are cached process-wide, keyed by the indexes. Use BuildPkgResolver to own a resolver's lifetime instead.

func (*PkgResolver) Clone added in v0.19.3

func (p *PkgResolver) Clone() *PkgResolver

Clone returns a copy of PkgResolver.

func (*PkgResolver) Extend added in v1.4.9

func (p *PkgResolver) Extend(ctx context.Context, indexes ...NamedIndex) *PkgResolver

Extend returns a new PkgResolver that resolves over p's packages plus the packages of indexes, as if built from both sets of indexes; any filter and rank on p carry over, so a rank must place the added packages too. p itself is not modified, so resolutions already using p, or other resolvers extended from it, are unaffected.

Extending copies p's top-level maps, so it costs time proportional to the number of names p knows about; batch additions where possible. Packages already in p are not deduplicated.

func (*PkgResolver) Filtered added in v1.4.9

func (p *PkgResolver) Filtered(keep PackageFilter) *PkgResolver

Filtered returns a copy of p that only considers the packages keep accepts. It resolves as a PkgResolver built from just those packages would: version selection, provides, install-if, conflicts and "nothing provides" errors all ignore the rejected packages. The copy shares p's package maps, so it is cheap to create one per resolution over a large resolver.

Where resolution breaks a tie by position, the kept packages keep p's order, which need not be the order of the index they came from; Ranked restores it.

keep must give the same answer for a package for the lifetime of the returned resolver. Filtering an already filtered resolver keeps only the packages both filters accept; a nil keep adds no filter.

For a multi-arch build, resolve with GetPackagesWithDependenciesByArch: GetPackagesWithDependencies checks the other arches against their whole indexes. The returned resolver memoizes lookups, even in ResolvePackage, so it must not be used from more than one goroutine; give each goroutine its own Filtered or Clone.

func (*PkgResolver) GetPackageWithDependencies

func (p *PkgResolver) GetPackageWithDependencies(ctx context.Context, pkgName string, existing map[string]*RepositoryPackage, dq map[*RepositoryPackage]string) (*RepositoryPackage, []*RepositoryPackage, []string, error)

GetPackageWithDependencies get all of the dependencies for a single package as well as looking up the package itself and resolving its version, based on the indexes. Requires the existing set because the logic for resolving dependencies between competing options may depend on whether or not one already is installed. Must not modify the existing map directly.

func (*PkgResolver) GetPackagesWithDependencies

func (p *PkgResolver) GetPackagesWithDependencies(ctx context.Context, packages []string, allArchs map[string][]NamedIndex) (toInstall []*RepositoryPackage, conflicts []string, err error)

GetPackagesWithDependencies get all of the dependencies for the given packages based on the indexes. Does not filter for installed already or not.

allArchs holds the indexes of every arch being built, and a package not available on all of them is disqualified. That check reads the indexes whole, ignoring any filter on p, and caches resolvers for them process-wide; use GetPackagesWithDependenciesByArch with Filtered or BuildPkgResolver resolvers.

func (*PkgResolver) GetPackagesWithDependenciesByArch added in v1.4.9

func (p *PkgResolver) GetPackagesWithDependenciesByArch(ctx context.Context, packages []string, byArch map[string]*PkgResolver) (toInstall []*RepositoryPackage, conflicts []string, err error)

GetPackagesWithDependenciesByArch is GetPackagesWithDependencies with the cross-arch check made over resolvers instead of indexes: byArch holds a resolver for every arch being built, p's included, and a package is disqualified unless each of them considers a package of the same name and version. Their filters apply, and nothing is cached.

Unlike GetPackagesWithDependencies, which builds its cross-arch set once per set of indexes and caches it, every call walks each resolver in byArch whole and calls its filter on every package, so a call costs time and memory proportional to the resolvers, not to the packages resolved. A single-arch resolution can pass a nil byArch to skip the walk.

The resolvers in byArch are only read, so one byArch may serve concurrent resolutions of each of its arches provided their filters are safe for concurrent use.

func (*PkgResolver) Ranked added in v1.4.9

func (p *PkgResolver) Ranked(rank PackageRank) *PkgResolver

Ranked returns a copy of p that considers the candidates for a name, and the install-if packages for a trigger, in ascending rank, packages of equal rank keeping p's order. A nil rank keeps p's order; a rank replaces any earlier one.

Resolution breaks some ties by position: between packages of the same name and version, and among install-if packages of one name, the first wins. A resolver built from indexes considers packages in index order, so a filtered resolver over packages gathered from many indexes resolves as one built from a single index only when ranked by that index's order. Only the order among packages of one name matters.

rank must give the same answer for a package for the lifetime of the returned resolver. Like Filtered, the returned resolver memoizes lookups and must not be used from more than one goroutine.

func (*PkgResolver) ResolvePackage

func (p *PkgResolver) ResolvePackage(pkgName string, dq map[*RepositoryPackage]string) ([]*RepositoryPackage, error)

ResolvePackage given a single package name and optional version constraints, resolve to a list of packages that satisfy the constraint. The list will be sorted by version number, with the highest version first and decreasing from there. In general, the first one in the list is the best match. This function returns multiple in case you need to see all potential matches.

type ReleaseBranch

type ReleaseBranch struct {
	Arches        []string              `json:"arches"`
	GitBranch     string                `json:"git_branch"`
	Keys          map[string][]RepoKeys `json:"keys"`
	ReleaseBranch string                `json:"rel_branch"`
	Repos         []Repo                `json:"repos"`
}

func (ReleaseBranch) KeysFor

func (r ReleaseBranch) KeysFor(arch string, date time.Time) []string

KeysFor returns the keys for the given architecture and date. The date is used to check for deprecation.

type Releases

type Releases struct {
	Architectures   []string        `json:"architectures"`
	LatestStable    string          `json:"latest_stable"`
	ReleaseBranches []ReleaseBranch `json:"release_branches"`
}

func FetchAlpineReleases added in v0.30.32

func FetchAlpineReleases(ctx context.Context, client *http.Client) (*Releases, error)

FetchAlpineReleases fetches and returns the Alpine releases metadata from alpinelinux.org.

func (Releases) GetReleaseBranch

func (r Releases) GetReleaseBranch(version string) *ReleaseBranch

GetReleaseBranch returns the release branch for the given version. If not found, nil is returned.

type Repo

type Repo struct {
	Name string   `json:"name"`
	EOL  DateTime `json:"eol_date"`
}

type RepoKeys

type RepoKeys struct {
	URL        string   `json:"url"`
	Deprecated DateTime `json:"deprecated_since"`
}

type Repository

type Repository struct {
	URI string
}

func NewRepositoryFromComponents

func NewRepositoryFromComponents(baseURI, release, repo, arch string) Repository

NewRepositoryFromComponents creates a new Repository with the uri constructed from the individual components

func (*Repository) IndexURI

func (r *Repository) IndexURI() string

IndexURI returns the uri of the APKINDEX for this repository

func (*Repository) IsRemote

func (r *Repository) IsRemote() bool

IsRemote returns whether the repository is considered remote and needs to be fetched over http(s)

func (*Repository) WithIndex

func (r *Repository) WithIndex(index *APKIndex) *RepositoryWithIndex

WithIndex returns a RepositoryWithIndex object with the

type RepositoryPackage

type RepositoryPackage struct {
	*Package
	// contains filtered or unexported fields
}

func NewRepositoryPackage

func NewRepositoryPackage(pkg *Package, repo *RepositoryWithIndex) *RepositoryPackage

func (*RepositoryPackage) Repository

func (rp *RepositoryPackage) Repository() *RepositoryWithIndex

func (*RepositoryPackage) URL

func (rp *RepositoryPackage) URL() string

type RepositoryWithIndex

type RepositoryWithIndex struct {
	*Repository
	// contains filtered or unexported fields
}

RepositoryWithIndex represents a repository with the index read and parsed

func (*RepositoryWithIndex) Count

func (r *RepositoryWithIndex) Count() int

Count returns the amount of packages that are available in this repository

func (*RepositoryWithIndex) Packages

func (r *RepositoryWithIndex) Packages() []*RepositoryPackage

Packages returns a list of RepositoryPackage in this repository

func (*RepositoryWithIndex) RepoAbbr

func (r *RepositoryWithIndex) RepoAbbr() string

RepoAbbr returns a short name of this repository consisting of the repo name and the architecture.

type Signature added in v0.23.0

type Signature struct {
	KeyID           string
	Signature       []byte
	DigestAlgorithm crypto.Hash
}

type SizeLimits added in v1.1.0

type SizeLimits struct {
	APKIndexDecompressedMaxSize int64
	APKControlMaxSize           int64
	APKDataMaxSize              int64
	HTTPResponseMaxSize         int64
}

SizeLimits configures maximum sizes for various APK operations.

type Version

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

func ParseVersion

func ParseVersion(version string) (Version, error)

ParseVersion parses a version string into a Version struct.

type WriteHeaderer

type WriteHeaderer interface {
	WriteHeader(hdr tar.Header, tfs fs.FS, pkg *Package) (bool, error)
}

Jump to

Keyboard shortcuts

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