repodata

package
v0.4.2 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: Apache-2.0 Imports: 36 Imported by: 2 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package repodata writes and reads the metadata of an RPM repository: the repomd.xml index and the primary.xml, filelists.xml, other.xml, comps.xml and modules.yaml documents that dnf and yum fetch.

Writing

The writers take the rpm.Package values that rpm.ReadPackage returns, set the checksum and size of the file, and stream a document to an io.Writer with memory use independent of the size of the repository: WritePrimaryXML, WriteFilelistsXML, WriteOtherXML, WriteCompsXML. A DocWriter writes a document package by package. CompressMetadataStream compresses a document (gzip, zstd or xz) and returns the checksums and sizes repomd.xml records; GenerateRepomdXML writes the index, and SignRepomdXML signs it for clients that check repo_gpgcheck.

The output of the primary, filelists, filelists-ext and other writers, and of Repomd.Marshal, equals byte for byte what createrepo_c writes for the same packages; testdata/createrepo holds a corpus of real packages and the reference output.

Other metadata

Besides the three core documents the package reads and writes comps.xml (Comps, with environments, langpacks and localized names), updateinfo.xml (Advisory, MergeUpdateinfo), modules.yaml as typed modulemd v2, defaults, obsoletes and translations documents (ParseModulemd, WriteModules; libmodulemd reads what is written), prestodelta.xml (DeltaInfo), filelists-ext.xml, the SQLite databases of schema version 10 (WriteSQLite, OpenSQLite) and zchunk files (NewZchunkWriter, ReadZchunkHeader, NewZchunkReader; the Zchunk compression). NewRecord, AddRecord and RemoveRecord do what modifyrepo_c does, including for the AppStream records.

Reading

ParseRepomd reads repomd.xml, OpenMetadata decompresses a document by the extension of its name with a bound on the decompressed size, and ReadPrimary decodes primary.xml package by package with limits on the dependency lists, file lists and text fields. ScanPackages walks the <package> elements of any of the three documents and can hand them back verbatim, which is how MergeModules and a repository merge are built. ModuleIndex interprets modules.yaml the way dnf does when no module stream is enabled.

Untrusted input

Every reader bounds what it keeps or decompresses and fails with ErrTooLarge when a limit is exceeded; none of them panics on malformed input.

Example

Write the metadata of a one-package repository, then read it back the way a client does: repomd.xml names the primary document, which is decompressed and decoded.

package main

import (
	"bytes"
	"fmt"
	"io"
	"log"

	"github.com/M0Rf30/pkgformat/rpm"
	"github.com/M0Rf30/pkgformat/rpm/repodata"
)

func main() {
	pkgs := []rpm.Package{{
		Name: "hello", Version: "1.0", Release: "1", Arch: "noarch",
		Summary: "A greeting", SHA256: "0123", PackageSize: 4096,
		Requires: []rpm.Dependency{{Name: "bash"}},
	}}

	primary, err := repodata.CompressMetadataStream(repodata.Zstd, func(w io.Writer) error {
		return repodata.WritePrimaryXML(w, pkgs)
	})
	if err != nil {
		log.Fatal(err)
	}

	name := "repodata/" + primary.SHA256 + "-primary.xml" + repodata.Zstd.Extension()

	repomd, err := repodata.GenerateRepomdXML("1", []repodata.RepomdData{{
		Type: "primary", Location: name, Checksum: primary.SHA256, ChecksumType: "sha256",
		OpenChecksum: primary.OpenSHA256, OpenChecksumType: "sha256",
		Timestamp: 1, Size: primary.Size, OpenSize: primary.OpenSize,
	}})
	if err != nil {
		log.Fatal(err)
	}

	// Client side.
	index, err := repodata.ParseRepomd(bytes.NewReader(repomd))
	if err != nil {
		log.Fatal(err)
	}

	entry, _ := index.Find("primary")

	doc, err := repodata.OpenMetadata(io.NopCloser(bytes.NewReader(primary.Data)), entry.Location, 0)
	if err != nil {
		log.Fatal(err)
	}
	defer doc.Close()

	err = repodata.ReadPrimary(doc, repodata.PrimaryLimits{}, func(p *repodata.PrimaryPackage) error {
		fmt.Println(p.Name, p.Version, p.Requires[0].Name, p.Location)

		return nil
	})
	if err != nil {
		log.Fatal(err)
	}
}
Output:
hello 1.0 bash Packages/hello-1.0-1.noarch.rpm

Index

Examples

Constants

View Source
const (
	CompsMandatory   = "mandatory"
	CompsDefault     = "default"
	CompsOptional    = "optional"
	CompsConditional = "conditional"
)

Package types of a comps group, as dnf reads them.

View Source
const (
	// DefaultMaxCompsBytes bounds the size of the document read.
	DefaultMaxCompsBytes = 256 << 20
	// DefaultMaxCompsEntries bounds the groups, categories, environments,
	// language packs, blacklisted packages and ignored dependencies together.
	DefaultMaxCompsEntries = 1 << 20
	// DefaultMaxCompsListItems bounds each list of an element: the packages
	// of a group, the groups of a category or environment, the translations
	// of a text.
	DefaultMaxCompsListItems = 100_000
	// DefaultMaxCompsFieldBytes bounds one text value.
	DefaultMaxCompsFieldBytes = 1 << 20
)

Default limits of ReadComps.

View Source
const (
	// DefaultMaxDeltaPackages bounds the <newpackage> elements of a document.
	DefaultMaxDeltaPackages = 1 << 20
	// DefaultMaxDeltas bounds the <delta> elements of one <newpackage>.
	DefaultMaxDeltas = 10_000
	// DefaultMaxDeltaFieldBytes bounds one text value or attribute of a
	// document, such as a file name.
	DefaultMaxDeltaFieldBytes = 64 << 10
)

Default limits of ReadDeltaInfo.

View Source
const (
	FileTypeRegular = ""
	FileTypeDir     = "dir"
	FileTypeGhost   = "ghost"
)

The types of a <file> element of filelists.xml and filelists-ext.xml. A regular file, a symbolic link or any other entry has no type.

View Source
const (
	// DefaultMaxModulemdDocument bounds one document of a modules.yaml; the
	// largest real ones are a few hundred kilobytes.
	DefaultMaxModulemdDocument = 16 << 20
	// DefaultMaxModulemdEntries bounds each list and mapping of a document.
	DefaultMaxModulemdEntries = 1 << 20
	// DefaultMaxModulemdDepth bounds the nesting of the xmd block.
	DefaultMaxModulemdDepth = 64
)

Defaults of ModulemdLimits.

View Source
const (
	// DefaultMaxDependencies bounds each dependency list of a package.
	DefaultMaxDependencies = 100_000
	// DefaultMaxFiles bounds the <file> entries of a package.
	DefaultMaxFiles = 100_000
	// DefaultMaxFieldBytes bounds one text field of a package, such as the
	// description.
	DefaultMaxFieldBytes = 1 << 20
	// DefaultMaxFileBytes bounds the total size of the <file> paths of a
	// package.
	DefaultMaxFileBytes = 16 << 20
)

Default limits of ReadPrimary.

View Source
const (
	// RecordAppStream is the AppStream catalog, appstream.xml.
	RecordAppStream = "appstream"
	// RecordAppStreamIcons is the tarball of the icons the catalog names,
	// appstream-icons.tar.
	RecordAppStreamIcons = "appstream-icons"
	// RecordPrestoDelta is prestodelta.xml, see [DeltaInfo].
	RecordPrestoDelta = "prestodelta"
)

The data types of the records that carry a file this package does not interpret, or interprets in another file.

View Source
const (
	// DefaultMaxDatabaseBytes bounds the size of a database; it is
	// [DefaultMaxDocument].
	DefaultMaxDatabaseBytes = DefaultMaxDocument
	// DefaultMaxChangelogs bounds the changelog entries of a package.
	DefaultMaxChangelogs = 10_000
)

Default limits of OpenSQLite.

View Source
const (
	// DefaultMaxUpdates bounds the advisories of a document. The updateinfo
	// of the largest distributions holds a few tens of thousands.
	DefaultMaxUpdates = 1_000_000
	// DefaultMaxReferences bounds the references of one advisory.
	DefaultMaxReferences = 10_000
	// DefaultMaxCollections bounds the collections of one advisory.
	DefaultMaxCollections = 10_000
	// DefaultMaxAdvisoryPackages bounds the packages of one advisory,
	// summed over its collections. A Fedora advisory for a large rebuild
	// lists a few thousand.
	DefaultMaxAdvisoryPackages = 100_000
	// DefaultMaxAdvisoryFieldBytes bounds one text field of an advisory,
	// such as its description.
	DefaultMaxAdvisoryFieldBytes = 1 << 20
)

Default limits of ReadUpdateinfo.

View Source
const (

	// DefaultZchunkMaxHeader is the header size [ReadZchunkHeader] and
	// [NewZchunkReader] allow by default. The index takes about 20 bytes per
	// chunk, and a file has a chunk per package or per 32 KiB of data.
	DefaultZchunkMaxHeader int64 = 64 << 20
	// DefaultZchunkMaxChunk is the uncompressed size of one chunk the readers
	// allow by default; the writers' own limit is 10 MiB.
	DefaultZchunkMaxChunk int64 = 64 << 20
)
View Source
const (
	// DefaultZchunkLevel is the zstd level zck compresses with.
	DefaultZchunkLevel = 9
	// DefaultZchunkMaxWriteChunk is the largest chunk a writer makes by
	// default.
	DefaultZchunkMaxWriteChunk = 10 << 20
)
View Source
const DatabaseVersion = 10

DatabaseVersion is the schema version of the SQLite databases createrepo_c and this package write.

View Source
const DefaultChangelogLimit = 10

DefaultChangelogLimit is the number of changelog entries per package an other.xml document keeps, as createrepo_c does by default.

View Source
const DefaultMaxDocument int64 = 16 << 30

DefaultMaxDocument is the decompressed size OpenMetadata allows a document by default. The filelists of the largest repositories are a few gigabytes.

View Source
const DefaultMaxModulesDocument int64 = 1 << 30

DefaultMaxModulesDocument is the size ModuleIndex.Add allows a modules.yaml.

Variables

View Source
var (
	// ErrSignerNil means no signer was given.
	ErrSignerNil = errors.New("repodata: signer is nil")
	// ErrEmptyRepomd means there is no repomd.xml to sign.
	ErrEmptyRepomd = errors.New("repodata: empty repomd.xml")
)

Errors of the repository signer.

View Source
var (
	// ErrDatabaseKind means a SQLite database was asked for a document that
	// has none: only primary, filelists and other have one.
	ErrDatabaseKind = errors.New("repodata: no sqlite database for this document kind")
	// ErrInvalidDatabase means a file is not a primary, filelists or other
	// database in the createrepo_c layout.
	ErrInvalidDatabase = errors.New("repodata: not a repodata sqlite database")
	// ErrDatabaseVersion means a database has a schema version other than
	// [DatabaseVersion].
	ErrDatabaseVersion = errors.New("repodata: unsupported sqlite database version")
)
View Source
var (
	// ErrZchunkFormat means the data is not a well-formed zchunk file.
	ErrZchunkFormat = errors.New("repodata: invalid zchunk file")
	// ErrZchunkChecksum means a checksum of a zchunk file (header, data or
	// one chunk) does not match its content.
	ErrZchunkChecksum = errors.New("repodata: zchunk checksum mismatch")
	// ErrZchunkUnsupported means the file uses a feature of the format that
	// is not implemented: data streams, an unknown compression, or an
	// unknown checksum type.
	ErrZchunkUnsupported = errors.New("repodata: unsupported zchunk feature")
	// ErrZchunkClosed is returned by a [ZchunkWriter] used after Close.
	ErrZchunkClosed = errors.New("repodata: zchunk writer is closed")
)

Zchunk file format errors. They are wrapped with the position of the problem; test for them with errors.Is.

View Source
var ErrDocKind = errors.New("repodata: package does not fit the document kind")

ErrDocKind means a DocWriter was given a package that its document kind cannot hold.

View Source
var ErrEmptyDocument = errors.New("repodata: empty xml document")

ErrEmptyDocument is returned when a metadata generator wrote nothing.

View Source
var ErrInvalidComps = errors.New("repodata: invalid comps")

ErrInvalidComps means a comps.xml document or model breaks a rule of the format: a missing id, a package type that is not one of the Comps* constants, a malformed number or boolean.

View Source
var ErrInvalidModulemd = errors.New("repodata: invalid modulemd document")

ErrInvalidModulemd means a modulemd document is malformed: not YAML, a field of the wrong type, a missing mandatory field or a value libmodulemd would refuse. The error wraps it with the document and the field.

View Source
var ErrInvalidRecord = errors.New("repodata: invalid repomd.xml record")

ErrInvalidRecord means the name or type of a record is not usable: the name is not a plain file name or the type cannot be derived from it.

View Source
var ErrInvalidUpdateinfo = errors.New("repodata: invalid updateinfo advisory")

ErrInvalidUpdateinfo means an updateinfo.xml advisory cannot be read or written: a date or module version that is not a number or a date, an advisory without an id, or a checksum without its type.

View Source
var ErrMalformedDeltaInfo = errors.New("repodata: malformed prestodelta.xml")

ErrMalformedDeltaInfo means a prestodelta.xml document, or the value given to its writer, does not follow the format: the root element is not <prestodelta>, a required attribute or element is missing, or a number does not parse.

View Source
var ErrTooLarge = errors.New("repodata: document exceeds a limit")

ErrTooLarge means a document or one of its lists exceeds a limit.

View Source
var ErrUnsupportedModulemd = errors.New("repodata: unsupported modulemd document")

ErrUnsupportedModulemd means a document is well-formed but of a kind or a format version this package does not model: the kinds are modulemd, modulemd-defaults, modulemd-obsoletes and modulemd-translations; modulemd is read at version 2 and the other three at version 1.

Functions

func AddRecord added in v0.4.0

func AddRecord(m *Repomd, rec RepomdData)

AddRecord registers rec in m the way modifyrepo_c does: every record of the same type is replaced, and the records are then sorted by Repomd.SortData. The file of a record it replaced is not touched; the caller removes it (the old record is what Repomd.Find returned before the call).

func DatabaseFileName added in v0.4.0

func DatabaseFileName(kind DocKind, c Compression) string

DatabaseFileName returns the name createrepo_c gives the compressed database of a document kind: "primary.sqlite.gz", "filelists.sqlite.zst", and so on; empty for a kind that has none.

func DatabaseType added in v0.4.0

func DatabaseType(kind DocKind) string

DatabaseType returns the repomd.xml data type of the SQLite database of a document kind: "primary_db", "filelists_db" or "other_db"; empty for a kind that has none.

func GenerateRepomdXML

func GenerateRepomdXML(revision string, entries []RepomdData) ([]byte, error)

GenerateRepomdXML renders repomd.xml for entries. An empty revision becomes the current Unix time. It is Repomd.Marshal for a repository without tags.

func IsModularPackage

func IsModularPackage(release string) bool

IsModularPackage reports whether the release marks a module-stream build: modular packages carry ".module+" in it.

func MergeModules

func MergeModules(w io.Writer, sources []io.Reader) (int, error)

MergeModules concatenates the modulemd documents of several modules.yaml files into one, in order. A document an earlier file already provided (the same module stream version and context, the same defaults or obsoletes record) is dropped, so the first source wins like it does for packages. It returns the number of documents written; a source over DefaultMaxModulesDocument fails with ErrTooLarge; a file whose documents cannot be parsed contributes none of them.

func MergeUpdateinfo added in v0.4.0

func MergeUpdateinfo(w io.Writer, sources []io.Reader, lim UpdateinfoLimits) (int, error)

MergeUpdateinfo reads the updateinfo.xml documents of sources, merges their advisories like MergeAdvisories, and writes the result to w as one updateinfo.xml. It returns the number of advisories written. The limits apply to each source; MaxUpdates also bounds the distinct advisories of the result, which are held in memory. A source that cannot be read fails the merge before anything is written.

Example

Merge the advisories of two repositories: the newest version of each id wins and the ids keep the order they first appear in.

package main

import (
	"bytes"
	"fmt"
	"io"
	"log"
	"time"

	"github.com/M0Rf30/pkgformat/rpm/repodata"
)

func main() {
	render := func(advisories ...repodata.Advisory) io.Reader {
		var buf bytes.Buffer
		if err := repodata.WriteUpdateinfoXML(&buf, advisories); err != nil {
			log.Fatal(err)
		}

		return &buf
	}

	day := func(d int) time.Time { return time.Date(2026, 1, d, 0, 0, 0, 0, time.UTC) }

	var merged bytes.Buffer

	n, err := repodata.MergeUpdateinfo(&merged, []io.Reader{
		render(repodata.Advisory{ID: "A-1", Title: "first draft", Updated: day(1)}, repodata.Advisory{ID: "A-2", Title: "only here"}),
		render(repodata.Advisory{ID: "A-1", Title: "corrected", Updated: day(9)}),
	}, repodata.UpdateinfoLimits{})
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(n, "advisories")

	err = repodata.ReadUpdateinfo(&merged, repodata.UpdateinfoLimits{}, func(a *repodata.Advisory) error {
		fmt.Println(a.ID, a.Title)

		return nil
	})
	if err != nil {
		log.Fatal(err)
	}
}
Output:
2 advisories
A-1 corrected
A-2 only here

func OpenMetadata

func OpenMetadata(r io.ReadCloser, name string, maxSize int64) (io.ReadCloser, error)

OpenMetadata wraps r according to the extension of the file name it was fetched as (.gz, .xz, .zst, .zck, .bz2 or none), and decompresses at most maxSize bytes: a document over the limit fails the read with ErrTooLarge instead of ending as a silently shortened one; a zchunk file states its size in its header, so it fails here already. A maxSize of 0 selects DefaultMaxDocument. Closing the result closes r.

func PackageLocation

func PackageLocation(p *rpm.Package) string

PackageLocation is the href a package is listed under in primary.xml (and served from): Packages/<name>-<version>-<release>.<arch>.rpm.

func PackageNEVRA

func PackageNEVRA(name, epoch, version, release, arch string) string

PackageNEVRA builds the key modules.yaml artifacts use, "name-epoch:version-release.arch", with an absent epoch as "0".

func PublicKey

func PublicKey(signer gpg.Signer) ([]byte, error)

PublicKey returns the armored public key clients import to verify the signature of repomd.xml.

func ReadComps added in v0.4.0

func ReadComps(r io.Reader, lim CompsLimits, v CompsVisitor) error

ReadComps decodes the comps.xml in r entry by entry and hands each to v, so memory use is that of one entry. The document must be UTF-8 with a <comps> root; elements and attributes this package does not model (such as the <groupreq> of old Fedora releases) are skipped, and the surrounding whitespace around an id, a package name, a number or a flag is dropped, the names and descriptions are kept as they are.

A document that is not well-formed, or whose entry breaks a rule of the format (an empty id, an unknown package type, a boolean that is not true/false/1/0, a non-numeric display_order) fails with ErrInvalidComps or the XML error. A limit exceeded fails with ErrTooLarge. The input is read to its end so trailing garbage is reported, but entries before the error have been delivered already. Bound the decompressed size with OpenMetadata.

Example

Read the groups of a comps.xml one at a time, without holding the document in memory: the visitor sees each group as soon as it is parsed.

package main

import (
	"fmt"
	"log"
	"strings"

	"github.com/M0Rf30/pkgformat/rpm/repodata"
)

func main() {
	const doc = `<comps>
  <group><id>core</id><name>Core</name><packagelist>
    <packagereq type="mandatory">bash</packagereq>
    <packagereq type="optional">vim</packagereq>
  </packagelist></group>
  <group><id>editors</id><name>Editors</name></group>
</comps>`

	err := repodata.ReadComps(strings.NewReader(doc), repodata.CompsLimits{}, repodata.CompsVisitor{
		Group: func(g *repodata.CompsGroup) error {
			fmt.Println(g.ID, g.Name, len(g.Packages), "packages")

			return nil
		},
	})
	if err != nil {
		log.Fatal(err)
	}

}
Output:
core Core 2 packages
editors Editors 0 packages

func ReadDeltaInfo added in v0.4.0

func ReadDeltaInfo(r io.Reader, lim DeltaInfoLimits, fn func(*DeltaPackage) error) error

ReadDeltaInfo decodes prestodelta.xml from r and calls fn for every <newpackage>, in document order. The package is only valid during the call.

A document whose root is not <prestodelta>, a package without a name, version, release or architecture, a delta without an old version, file name, sequence or checksum, and a number that does not parse fail the read with ErrMalformedDeltaInfo; a limit exceeded fails it with ErrTooLarge; an error of fn stops the read and is returned as is. Elements and attributes that the format does not define are ignored. A missing epoch is 0.

func ReadFilelistsExt added in v0.4.0

func ReadFilelistsExt(r io.Reader, lim FilelistsLimits, fn func(*FilelistsExtPackage) error) error

ReadFilelistsExt decodes filelists-ext.xml, or filelists.xml, from r and calls fn for every package, in document order. The package is only valid during the call. A package without a name or an architecture, or with a malformed epoch, is skipped; malformed XML, a limit exceeded (ErrTooLarge) or an error of fn stops the read and is returned. Bound the decompressed size of r with OpenMetadata.

Example

Read a filelists-ext document: the paths of each package with their types, as `createrepo_c --filelists-ext` writes them.

package main

import (
	"fmt"
	"log"
	"strings"

	"github.com/M0Rf30/pkgformat/rpm/repodata"
)

func main() {
	doc := `<?xml version="1.0" encoding="UTF-8"?>
<filelists-ext xmlns="http://linux.duke.edu/metadata/filelists-ext" packages="1">
<package pkgid="abc" name="hello" arch="x86_64">
  <version epoch="0" ver="1.0" rel="1"/>
  <file>/usr/bin/hello</file>
  <file type="dir">/usr/share/hello</file>
  <file type="ghost">/var/log/hello.log</file>
</package>
</filelists-ext>`

	err := repodata.ReadFilelistsExt(strings.NewReader(doc), repodata.FilelistsLimits{}, func(p *repodata.FilelistsExtPackage) error {
		fmt.Println(p.Name, p.Version, p.PkgID)

		for _, f := range p.Files {
			fmt.Printf("%q %s\n", f.Type, f.Path)
		}

		return nil
	})
	if err != nil {
		log.Fatal(err)
	}
}
Output:
hello 1.0 abc
"" /usr/bin/hello
"dir" /usr/share/hello
"ghost" /var/log/hello.log

func ReadModulemd added in v0.4.0

func ReadModulemd(r io.Reader, lim ModulemdLimits, fn func(ModuleDocument) error) error

ReadModulemd decodes a modules.yaml (already decompressed, see OpenMetadata) one document at a time and calls fn with each: a *ModuleStream, *ModuleDefaults, *ModuleObsoletes or *ModuleTranslations. Only the document being decoded is held in memory.

Keys this package does not model are ignored, as libmodulemd does when it is not strict. A malformed document fails the read with ErrInvalidModulemd, a document of another kind or version with ErrUnsupportedModulemd, a limit exceeded with ErrTooLarge; an error of fn stops the read and is returned.

func ReadPrimary

func ReadPrimary(r io.Reader, lim PrimaryLimits, fn func(*PrimaryPackage) error) error

ReadPrimary decodes primary.xml from r and calls fn for every package. A package without a name or an architecture, or with a malformed number, is skipped; malformed XML, a limit exceeded (ErrTooLarge) or an error of fn stops the read and is returned. Bound the decompressed size of r with OpenMetadata.

func ReadUpdateinfo added in v0.4.0

func ReadUpdateinfo(r io.Reader, lim UpdateinfoLimits, fn func(*Advisory) error) error

ReadUpdateinfo decodes updateinfo.xml from r and calls fn for every advisory. An element it does not know is ignored and an advisory without an id is skipped. Malformed XML, a date or module version that is invalid (ErrInvalidUpdateinfo), a limit exceeded (ErrTooLarge) or an error of fn stops the read and is returned. Bound the decompressed size of r with OpenMetadata.

func SafeLocation

func SafeLocation(href string) (string, bool)

SafeLocation cleans a package href and decodes its percent-escapes into the repository-relative path it is served from. ok is false for a location that is absolute or leaves the repository.

func ScanPackages

func ScanPackages(r io.Reader, withElement bool, fn func(info PackageInfo, element []byte) error) error

ScanPackages reads the <package> elements of a primary, filelists, filelists-ext or other document in order. When withElement is set fn also receives the element serialized (without the xml:base attribute of a location, which would send a client to another host); the slice is only valid during the call.

func SignRepomdXML

func SignRepomdXML(signer gpg.Signer, repomdXML []byte) ([]byte, error)

SignRepomdXML returns the armored detached signature of repomd.xml, the content of repomd.xml.asc that clients check with repo_gpgcheck.

func ValidateCompsXML

func ValidateCompsXML(data []byte) error

ValidateCompsXML reports whether data is well-formed XML.

func WriteCompsXML

func WriteCompsXML(w io.Writer, c *Comps) error

WriteCompsXML writes c as comps.xml to w, the file the "group" data entry of repomd.xml points at. A model that breaks a rule of the format fails with ErrInvalidComps before anything is written.

Example

Describe the groups of a distribution in a model and write them as comps.xml; dnf and yum read it from the "group" record of repomd.xml.

package main

import (
	"log"
	"os"

	"github.com/M0Rf30/pkgformat/rpm/repodata"
)

func main() {
	comps := &repodata.Comps{
		Groups: []repodata.CompsGroup{{
			ID: "editors", Name: "Editors", Description: "Text editors",
			NameLocalized: map[string]string{"de": "Editoren"},
			UserVisible:   true,
			Packages: []repodata.CompsPackage{
				{Name: "vim", Type: repodata.CompsMandatory},
				{Name: "nano", Type: repodata.CompsDefault},
				{Name: "vim-spell", Type: repodata.CompsConditional, Requires: "vim"},
			},
		}},
		Categories: []repodata.CompsCategory{{
			ID: "applications", Name: "Applications",
			Groups: []repodata.CompsGroupRef{{ID: "editors"}},
		}},
	}

	if err := repodata.WriteCompsXML(os.Stdout, comps); err != nil {
		log.Fatal(err)
	}

}
Output:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE comps PUBLIC "-//Red Hat, Inc.//DTD Comps info//EN" "comps.dtd">
<comps>
  <group>
    <id>editors</id>
    <name>Editors</name>
    <name xml:lang="de">Editoren</name>
    <description>Text editors</description>
    <default>false</default>
    <uservisible>true</uservisible>
    <packagelist>
      <packagereq type="mandatory">vim</packagereq>
      <packagereq type="default">nano</packagereq>
      <packagereq requires="vim" type="conditional">vim-spell</packagereq>
    </packagelist>
  </group>
  <category>
    <id>applications</id>
    <name>Applications</name>
    <grouplist>
      <groupid>editors</groupid>
    </grouplist>
  </category>
</comps>

func WriteDeltaInfoXML added in v0.4.0

func WriteDeltaInfoXML(w io.Writer, info *DeltaInfo) error

WriteDeltaInfoXML streams info as prestodelta.xml to w, byte for byte what createrepo_c --deltas writes for the same packages in the same order (it lists them in hash-table order, which no reader relies on).

Example

Write and read the delta rpm index of a repository.

package main

import (
	"bytes"
	"fmt"
	"log"

	"github.com/M0Rf30/pkgformat/rpm/repodata"
)

func main() {
	info := &repodata.DeltaInfo{NewPackages: []repodata.DeltaPackage{{
		Name: "hello", Epoch: 0, Version: "1.1", Release: "1", Arch: "x86_64",
		Deltas: []repodata.Delta{{
			Version: "1.0", Release: "1",
			Filename: "drpms/hello-1.0-1_1.1-1.x86_64.drpm",
			Sequence: "hello-1.0-1-0123456789abcdef",
			Size:     2048,
			Checksum: repodata.DeltaChecksum{Type: "sha256", Value: "ab12"},
		}},
	}}}

	var buf bytes.Buffer
	if err := repodata.WriteDeltaInfoXML(&buf, info); err != nil {
		log.Fatal(err)
	}

	fmt.Println(buf.String())

	err := repodata.ReadDeltaInfo(&buf, repodata.DeltaInfoLimits{}, func(p *repodata.DeltaPackage) error {
		fmt.Println(p.Name, p.Version, "from", p.Deltas[0].Version, p.Deltas[0].Size)

		return nil
	})
	if err != nil {
		log.Fatal(err)
	}
}
Output:
<?xml version="1.0" encoding="UTF-8"?>
<prestodelta>
  <newpackage name="hello" epoch="0" version="1.1" release="1" arch="x86_64">
    <delta oldepoch="0" oldversion="1.0" oldrelease="1">
      <filename>drpms/hello-1.0-1_1.1-1.x86_64.drpm</filename>
      <sequence>hello-1.0-1-0123456789abcdef</sequence>
      <size>2048</size>
      <checksum type="sha256">ab12</checksum>
    </delta>
  </newpackage>
</prestodelta>
hello 1.1 from 1.0 2048

func WriteFilelistsExt added in v0.4.0

func WriteFilelistsExt(w io.Writer, packages []FilelistsExtPackage) error

WriteFilelistsExt streams packages as filelists-ext.xml to w, in the layout and with the escaping createrepo_c --filelists-ext uses: reading a document it wrote with ReadFilelistsExt and writing the packages back gives the same bytes.

func WriteFilelistsExtXML added in v0.4.0

func WriteFilelistsExtXML(w io.Writer, packages []rpm.Package) error

WriteFilelistsExtXML streams filelists-ext.xml, the filelists with the digest of each regular file, for packages to w.

func WriteFilelistsXML

func WriteFilelistsXML(w io.Writer, packages []rpm.Package) error

WriteFilelistsXML streams filelists.xml for packages to w.

func WriteModuleDocument added in v0.4.0

func WriteModuleDocument(w io.Writer, doc ModuleDocument) error

WriteModuleDocument writes one document, from "---" to "...", in the layout WriteModules uses.

func WriteModules added in v0.4.0

func WriteModules(w io.Writer, set *ModuleSet) error

WriteModules writes a modules.yaml the way libmodulemd does: documents grouped by module in name order, and in each group the defaults, the obsoletes, the translations and then the streams by ModuleStream.NSVCA, every document opened by "---" and closed by "...", keys in libmodulemd's order and sets sorted. libmodulemd reads the output, and writes it back unchanged.

A document that libmodulemd would refuse to write (an empty name, a missing summary, ...) fails with ErrInvalidModulemd, before anything is written for it. An empty set writes nothing; compress the result with CompressMetadataStream to register it in repomd.xml as "modules".

Example

Write a modules.yaml: documents come out in libmodulemd's order and layout.

package main

import (
	"log"
	"os"

	"github.com/M0Rf30/pkgformat/rpm/repodata"
)

func main() {
	set := &repodata.ModuleSet{
		Defaults: []*repodata.ModuleDefaults{{Module: "tools", Stream: "2.0", Profiles: map[string][]string{"2.0": {"default"}}}},
		Streams: []*repodata.ModuleStream{{
			Name: "tools", Stream: "2.0", Version: 1, Context: "abc", Arch: "noarch",
			Summary: "Tools", Description: "A set of tools.",
			License:  repodata.ModuleLicense{Module: []string{"MIT"}},
			Profiles: map[string]repodata.ModuleProfile{"default": {RPMs: []string{"tool-b", "tool-a"}}},
		}},
	}

	if err := repodata.WriteModules(os.Stdout, set); err != nil {
		log.Fatal(err)
	}

}
Output:
---
document: modulemd-defaults
version: 1
data:
  module: tools
  stream: "2.0"
  profiles:
    "2.0": [default]
...
---
document: modulemd
version: 2
data:
  name: tools
  stream: "2.0"
  version: 1
  context: abc
  arch: noarch
  summary: Tools
  description: >-
    A set of tools.
  license:
    module:
    - MIT
  profiles:
    default:
      rpms:
      - tool-a
      - tool-b
...

func WriteOtherXML

func WriteOtherXML(w io.Writer, packages []rpm.Package) error

WriteOtherXML streams other.xml for packages to w.

func WritePrimaryXML

func WritePrimaryXML(w io.Writer, packages []rpm.Package) error

WritePrimaryXML streams primary.xml for packages to w.

func WriteSQLite added in v0.4.0

func WriteSQLite(w io.Writer, kind DocKind, packages []rpm.Package, opts SQLiteOptions) error

WriteSQLite writes the SQLite database of the given kind (DocPrimary, DocFilelists or DocOther) for packages to w, in the schema version 10 that createrepo_c --database writes and dnf reads: the same tables, columns, indexes and trigger, and the same rows, a package's pkgKey being its position in packages counted from 1. A primary database applies the filtering of WritePrimaryXML to the requirements, lists only the files primary.xml lists, and records the location and checksum of each package like it does. The rows of the filelist table follow the first appearance of a directory in the package rather than createrepo_c's hash order.

The database is assembled in a temporary file, so memory use does not grow with the repository; w receives it once it is complete.

func WriteUpdateinfoXML added in v0.4.0

func WriteUpdateinfoXML(w io.Writer, advisories []Advisory) error

WriteUpdateinfoXML writes advisories as updateinfo.xml to w, the file the "updateinfo" data entry of repomd.xml points at. The output equals what createrepo_c's library writes for the same advisories.

Example

Write an advisory, register the document in repomd.xml, and read it back the way a client does.

package main

import (
	"bytes"
	"fmt"
	"io"
	"log"
	"time"

	"github.com/M0Rf30/pkgformat/rpm/repodata"
)

func main() {
	advisory := repodata.Advisory{
		ID: "FEDORA-2026-c3b1d2e4f5", Title: "bash-5.3.99-1.fc45", Type: "security", Severity: "Important",
		Status: "stable", From: "updates@fedoraproject.org",
		Issued:      time.Date(2026, 10, 2, 11, 43, 19, 0, time.UTC),
		Release:     "Fedora 45",
		Summary:     "bash-5.3.99-1.fc45 security update",
		Description: "Fixes an out-of-bounds read in the history expansion code.",
		References: []repodata.AdvisoryReference{{
			Href: "https://bugzilla.redhat.com/show_bug.cgi?id=2410101", ID: "2410101", Type: "bugzilla",
			Title: "CVE-2026-0101 bash: out-of-bounds read in history expansion",
		}},
		Collections: []repodata.AdvisoryCollection{{
			Short: "F45", Name: "Fedora 45",
			Packages: []repodata.AdvisoryPackage{{
				Name: "bash", Version: "5.3.99", Release: "1.fc45", Epoch: "0", Arch: "x86_64",
				Filename: "bash-5.3.99-1.fc45.x86_64.rpm",
				Sum:      repodata.AdvisorySum{Type: "sha256", Value: "0f1e2d3c"},
			}},
		}},
	}

	doc, err := repodata.CompressMetadataStream(repodata.Zstd, func(w io.Writer) error {
		return repodata.WriteUpdateinfoXML(w, []repodata.Advisory{advisory})
	})
	if err != nil {
		log.Fatal(err)
	}

	repomd := &repodata.Repomd{Revision: "1"}
	repomd.Data = append(repomd.Data, doc.Entry("updateinfo", "updateinfo.xml"+repodata.Zstd.Extension(), 1))

	index, err := repomd.Marshal()
	if err != nil {
		log.Fatal(err)
	}

	// Client side.
	parsed, err := repodata.ParseRepomd(bytes.NewReader(index))
	if err != nil {
		log.Fatal(err)
	}

	entry, _ := parsed.Find("updateinfo")

	rc, err := repodata.OpenMetadata(io.NopCloser(bytes.NewReader(doc.Data)), entry.Location, 0)
	if err != nil {
		log.Fatal(err)
	}
	defer rc.Close()

	err = repodata.ReadUpdateinfo(rc, repodata.UpdateinfoLimits{}, func(a *repodata.Advisory) error {
		fmt.Println(a.ID, a.Type, a.Severity, a.Issued.Format(time.DateOnly), a.Collections[0].Packages[0].Filename)

		return nil
	})
	if err != nil {
		log.Fatal(err)
	}
}
Output:
FEDORA-2026-c3b1d2e4f5 security Important 2026-10-02 bash-5.3.99-1.fc45.x86_64.rpm

Types

type Advisory added in v0.4.0

type Advisory struct {
	// ID is the identifier of the advisory, such as "FEDORA-2024-1a2b3c4d5e"
	// or "RLSA-2024:1234"; it is required.
	ID string
	// Title is the one line name of the advisory.
	Title string
	// Type is "security", "bugfix", "enhancement" or "newpackage".
	Type string
	// Severity is "Critical", "Important", "Moderate", "Low" or "None".
	Severity string
	// Status is the state of the advisory, "stable" or "final".
	Status string
	// Version is the revision of the advisory text, usually a small number.
	Version string
	// From is the contact of the issuer, such as "updates@fedoraproject.org".
	From string
	// Issued and Updated are when the advisory was first published and last
	// changed, in UTC; the zero time leaves the date out.
	Issued  time.Time
	Updated time.Time
	// Release names the distribution release the advisory is for.
	Release string
	// Rights is the copyright notice.
	Rights string
	// Summary, Description and Solution are the texts of the advisory.
	Summary     string
	Description string
	Solution    string
	// PushCount is how many times the advisory was pushed.
	PushCount string
	// RebootSuggested says that installing any package of the advisory calls
	// for a reboot.
	RebootSuggested bool
	// References are the bug reports, CVEs and pages that concern it.
	References []AdvisoryReference
	// Collections are the package sets the advisory fixes.
	Collections []AdvisoryCollection
}

Advisory is an <update> of updateinfo.xml: a security, bug fix or enhancement announcement and the packages that carry it.

func MergeAdvisories added in v0.4.0

func MergeAdvisories(sources ...[]Advisory) []Advisory

MergeAdvisories combines advisories of several sources into one list with every id once. Of the advisories that share an id the one updated last (issued last when none was updated) wins; on a tie the earlier source wins. The result lists the ids in the order they first appear.

type AdvisoryCollection added in v0.4.0

type AdvisoryCollection struct {
	// Short is the short name of the collection, such as "F40".
	Short string
	// Name is its descriptive name, such as "Fedora 40".
	Name string
	// Module is set when the collection belongs to a module stream.
	Module   *AdvisoryModule
	Packages []AdvisoryPackage
}

AdvisoryCollection is a <collection> of an advisory: the packages of one repository or module stream.

type AdvisoryModule added in v0.4.0

type AdvisoryModule struct {
	Name    string
	Stream  string
	Version uint64
	Context string
	Arch    string
}

AdvisoryModule is the module stream a collection is for.

type AdvisoryPackage added in v0.4.0

type AdvisoryPackage struct {
	Name    string
	Version string
	Release string
	// Epoch is written as it is, "0" included.
	Epoch string
	Arch  string
	// Src is the source package, as a file name or an address.
	Src string
	// Filename is the name of the .rpm file.
	Filename string
	// Sum is the checksum of the .rpm file; empty when the advisory has none.
	Sum AdvisorySum
	// RebootSuggested, RestartSuggested and ReloginSuggested say what
	// installing this package calls for.
	RebootSuggested  bool
	RestartSuggested bool
	ReloginSuggested bool
}

AdvisoryPackage is a <package> of a collection: the package an advisory fixes.

type AdvisoryReference added in v0.4.0

type AdvisoryReference struct {
	// Href is the address of the page.
	Href string
	// ID is the identifier in the referenced system, such as a CVE number.
	ID string
	// Title names the referenced item.
	Title string
	// Type is "self", "cve", "bugzilla", "vendor", and so on.
	Type string
}

AdvisoryReference is a <reference> of an advisory.

type AdvisorySum added in v0.4.0

type AdvisorySum struct {
	// Type is the algorithm: "md5", "sha1", "sha256" or "sha512".
	Type string
	// Value is the hex digest.
	Value string
}

AdvisorySum is the checksum of a package of an advisory.

type AppStream added in v0.4.0

type AppStream struct {
	// Components is the content of appstream.xml; empty to leave the catalog
	// out.
	Components []byte
	// Icons is the content of the icon tarball, appstream-icons.tar
	// (uncompressed); empty to leave the icons out.
	Icons []byte
}

AppStream is the AppStream data of a repository: the catalog of the components its packages ship and the icons the catalog refers to.

type CompressedMetadata

type CompressedMetadata struct {
	// Data is the compressed document.
	Data []byte
	// SHA256 is the hex checksum of Data (the checksum of the repomd.xml
	// data entry).
	SHA256 string
	// Size is len(Data).
	Size int64
	// OpenSHA256 is the hex checksum of the uncompressed document (the
	// open-checksum of the data entry).
	OpenSHA256 string
	// OpenSize is the size of the uncompressed document.
	OpenSize int64
	// HeaderSHA256 and HeaderSize are the checksum and length of the header
	// of a zchunk file (the header-checksum and header-size of the data
	// entry); empty and zero for any other compression.
	HeaderSHA256 string
	HeaderSize   int64
}

CompressedMetadata is one repodata document compressed for repomd.xml.

func CompressMetadataStream

func CompressMetadataStream(c Compression, write func(io.Writer) error) (*CompressedMetadata, error)

CompressMetadataStream runs write against a sink that feeds the encoder of c, so the uncompressed document never has to exist in memory.

func CompressSQLite added in v0.4.0

func CompressSQLite(c Compression, kind DocKind, packages []rpm.Package, opts SQLiteOptions) (*CompressedMetadata, error)

CompressSQLite builds the database of kind (DocPrimary, DocFilelists or DocOther) for packages and compresses it with c, like CompressMetadataStream does for an XML document.

Example

Write the XML documents and the SQLite databases of a one-package repository, list them in repomd.xml, then read the primary database back the way a client does.

package main

import (
	"bytes"
	"fmt"
	"io"
	"log"

	"github.com/M0Rf30/pkgformat/rpm"
	"github.com/M0Rf30/pkgformat/rpm/repodata"
)

func main() {
	pkgs := []rpm.Package{{
		Name: "hello", Version: "1.0", Release: "1", Arch: "noarch",
		Summary: "A greeting", SHA256: "0123", PackageSize: 4096,
		Requires: []rpm.Dependency{{Name: "bash"}},
	}}

	var entries []repodata.RepomdData

	var primaryDB *repodata.CompressedMetadata

	for _, kind := range []repodata.DocKind{repodata.DocPrimary, repodata.DocFilelists, repodata.DocOther} {
		xml, err := repodata.CompressMetadataStream(repodata.Gzip, func(w io.Writer) error {
			d := repodata.NewDocWriter(w, kind, len(pkgs))
			for i := range pkgs {
				d.Package(&pkgs[i])
			}

			return d.Close()
		})
		if err != nil {
			log.Fatal(err)
		}

		// The database records the checksum of the XML it accompanies.
		db, err := repodata.CompressSQLite(repodata.Gzip, kind, pkgs, repodata.SQLiteOptions{XMLChecksum: xml.SHA256})
		if err != nil {
			log.Fatal(err)
		}

		name := repodata.DatabaseFileName(kind, repodata.Gzip)
		entries = append(entries, repodata.DatabaseEntry(db, kind, name, 1))

		if kind == repodata.DocPrimary {
			primaryDB = db
		}
	}

	repomd, err := repodata.GenerateRepomdXML("1", entries)
	if err != nil {
		log.Fatal(err)
	}

	index, err := repodata.ParseRepomd(bytes.NewReader(repomd))
	if err != nil {
		log.Fatal(err)
	}

	entry, _ := index.Find("primary_db")
	fmt.Println(entry.Location, entry.DatabaseVersion)

	// Client side.
	doc, err := repodata.OpenMetadata(io.NopCloser(bytes.NewReader(primaryDB.Data)), entry.Location, 0)
	if err != nil {
		log.Fatal(err)
	}
	defer doc.Close()

	db, err := repodata.OpenSQLite(doc, repodata.SQLiteLimits{})
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	err = db.Primary(func(p *repodata.PrimaryPackage) error {
		fmt.Println(p.Name, p.Version, p.Requires[0].Name, p.Location)

		return nil
	})
	if err != nil {
		log.Fatal(err)
	}

}
Output:
repodata/primary.sqlite.gz 10
hello 1.0 bash Packages/hello-1.0-1.noarch.rpm

func (*CompressedMetadata) Entry added in v0.4.0

func (c *CompressedMetadata) Entry(typ, name string, timestamp int64) RepomdData

Entry returns the repomd.xml data entry of the document of the given type (see RepomdData.Type) stored as repodata/<name>; timestamp is the Unix time to record.

type Compression

type Compression int

Compression selects how a repodata document is compressed.

const (
	// Gzip is the compression every dnf and createrepo_c understands. The
	// zero value.
	Gzip Compression = iota
	// Zstd is smaller and faster to decompress; dnf 4 and later read it.
	Zstd
	// XZ is the smallest; it is slow to compress.
	XZ
	// Zchunk is a zchunk file (see [ZchunkWriter]): zstd-compressed chunks,
	// one per package of a primary, filelists or other document, so a client
	// that has the previous version downloads only the packages that
	// changed. dnf and createrepo_c know it as the *_zck data types.
	Zchunk
)

func (Compression) Extension

func (c Compression) Extension() string

Extension returns the file name suffix of the compression: ".gz", ".zst", ".xz" or ".zck".

func (Compression) String

func (c Compression) String() string

String returns the name of the compression.

type Comps

type Comps struct {
	Groups       []CompsGroup
	Categories   []CompsCategory
	Environments []CompsEnvironment
	// Langpacks maps a package to the name pattern of its language packs.
	Langpacks []CompsLangpack
	// Blacklist lists packages that dependency resolution must not pull in.
	Blacklist []CompsBlacklisted
	// Whiteout lists dependencies that are ignored.
	Whiteout []CompsIgnoredDep
}

Comps is the content of a comps.xml: the package groups, categories and environments of a repository, and the language support and package filtering rules dnf reads next to them.

Names, descriptions and localized texts that are empty are not written. Localized texts are keyed by their xml:lang value and written in the order of the keys, so the output is the same for the same model.

func ParseComps added in v0.4.0

func ParseComps(r io.Reader, lim CompsLimits) (*Comps, error)

ParseComps decodes a whole comps.xml into a model. See ReadComps for what is accepted and how the limits apply.

func (*Comps) Validate added in v0.4.0

func (c *Comps) Validate() error

Validate reports the first rule of the format the model breaks, wrapping ErrInvalidComps: an empty id, name or language, an id or a package name that starts or ends with white space (a reader trims it), a package type that is not one of the Comps* constants, an architecture that holds a comma or a space.

type CompsBlacklisted added in v0.4.0

type CompsBlacklisted struct {
	Name string
	Arch string
}

CompsBlacklisted is a <package> of <blacklist>.

type CompsCategory

type CompsCategory struct {
	ID                   string
	Arch                 []string
	Name                 string
	NameLocalized        map[string]string
	Description          string
	DescriptionLocalized map[string]string
	DisplayOrder         int
	Groups               []CompsGroupRef
}

CompsCategory is a <category> of comps.xml: a list of groups.

type CompsEnvironment added in v0.4.0

type CompsEnvironment struct {
	ID                   string
	Arch                 []string
	Name                 string
	NameLocalized        map[string]string
	Description          string
	DescriptionLocalized map[string]string
	DisplayOrder         int
	// Groups are the groups of the environment and Options the optional
	// ones the user can add.
	Groups  []CompsGroupRef
	Options []CompsGroupRef
}

CompsEnvironment is an <environment> of comps.xml: the groups an install profile consists of.

type CompsGroup

type CompsGroup struct {
	ID string
	// Arch restricts the group to these architectures; empty means all.
	Arch []string
	// Name and Description are the texts without xml:lang, the localized
	// ones are in NameLocalized and DescriptionLocalized.
	Name                 string
	NameLocalized        map[string]string
	Description          string
	DescriptionLocalized map[string]string
	// Default marks a group that is installed by default. A comps.xml
	// without <default> reads as false; the writer always emits it.
	Default bool
	// UserVisible is false for a group that only other groups and
	// environments pull in. A comps.xml without <uservisible> reads as true;
	// the writer always emits it.
	UserVisible bool
	// BiarchOnly marks a group that only applies to a multilib system; it is
	// written only when true.
	BiarchOnly bool
	// DisplayOrder sorts the groups in a listing; 0 is not written.
	DisplayOrder int
	// LangOnly is the language code of a group that is only installed along
	// with that language.
	LangOnly string
	Packages []CompsPackage
}

CompsGroup is a <group> of comps.xml: a set of packages installed together.

type CompsGroupRef added in v0.4.0

type CompsGroupRef struct {
	ID string
	// Default is the default attribute: the group is selected by default
	// in the option list of an environment.
	Default bool
	// Arch restricts the entry to these architectures; empty means all.
	Arch []string
}

CompsGroupRef is a <groupid> entry of a category, environment or option list.

type CompsIgnoredDep added in v0.4.0

type CompsIgnoredDep struct {
	Requires string
	Package  string
}

CompsIgnoredDep is an <ignoredep> of <whiteout>: the dependency Requires of Package is ignored, of every package when Package is empty.

type CompsLangpack added in v0.4.0

type CompsLangpack struct {
	Name    string
	Install string
}

CompsLangpack is a <match> of <langpacks>: Install is the name of the language pack of the package Name, with %s for the language code.

type CompsLimits added in v0.4.0

type CompsLimits struct {
	// MaxBytes bounds the document; reading more fails with [ErrTooLarge].
	MaxBytes int64
	// MaxEntries bounds the top-level entries of the document.
	MaxEntries int
	// MaxListItems bounds each list of one element.
	MaxListItems int
	// MaxFieldBytes bounds one text value.
	MaxFieldBytes int
}

CompsLimits bounds ReadComps and ParseComps. A zero field selects its default.

type CompsPackage

type CompsPackage struct {
	Name string
	// Type is one of the Comps* constants; empty means [CompsDefault].
	Type string
	// Requires is the package a conditional package needs to be installed.
	Requires string
	// BaseArchOnly installs the package for the base architecture only,
	// not for the secondary one of a multilib system.
	BaseArchOnly bool
	// Arch restricts the package to these architectures; empty means all.
	Arch []string
}

CompsPackage is a <packagereq> of a group.

type CompsVisitor added in v0.4.0

type CompsVisitor struct {
	Group       func(*CompsGroup) error
	Category    func(*CompsCategory) error
	Environment func(*CompsEnvironment) error
	// Langpack, Blacklisted and IgnoredDep receive the entries of
	// <langpacks>, <blacklist> and <whiteout> one by one.
	Langpack    func(CompsLangpack) error
	Blacklisted func(CompsBlacklisted) error
	IgnoredDep  func(CompsIgnoredDep) error
}

CompsVisitor receives the entries of a comps.xml as ReadComps decodes them; a nil field skips that kind of entry. The callee owns the value it is given. An error returned by a callback stops the read and is returned as is.

type CompsWriter added in v0.4.0

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

CompsWriter writes a comps.xml element by element, for a caller that merges the groups of several documents without holding them all in memory. Write the elements in the order groups, categories, environments, langpacks, blacklist, whiteout, then call CompsWriter.Close.

Example

Merge the groups of several documents into one comps.xml as they are read.

package main

import (
	"bytes"
	"fmt"
	"log"
	"strings"

	"github.com/M0Rf30/pkgformat/rpm/repodata"
)

func main() {
	docs := []string{
		`<comps><group><id>a</id></group></comps>`,
		`<comps><group><id>b</id></group><langpacks><match name="x" install="x-%s"/></langpacks></comps>`,
	}

	var out bytes.Buffer

	cw := repodata.NewCompsWriter(&out)

	var langpacks []repodata.CompsLangpack

	for _, doc := range docs {
		err := repodata.ReadComps(strings.NewReader(doc), repodata.CompsLimits{}, repodata.CompsVisitor{
			Group: cw.Group,
			Langpack: func(l repodata.CompsLangpack) error {
				langpacks = append(langpacks, l)

				return nil
			},
		})
		if err != nil {
			log.Fatal(err)
		}
	}

	if err := cw.Langpacks(langpacks); err != nil {
		log.Fatal(err)
	}

	if err := cw.Close(); err != nil {
		log.Fatal(err)
	}

	merged, err := repodata.ParseComps(&out, repodata.CompsLimits{})
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(len(merged.Groups), "groups,", len(merged.Langpacks), "langpack")

}
Output:
2 groups, 1 langpack

func NewCompsWriter added in v0.4.0

func NewCompsWriter(w io.Writer) *CompsWriter

NewCompsWriter writes the document header to w.

func (*CompsWriter) Blacklist added in v0.4.0

func (cw *CompsWriter) Blacklist(list []CompsBlacklisted) error

Blacklist writes one <blacklist> element with the entries; nothing for an empty list.

func (*CompsWriter) Category added in v0.4.0

func (cw *CompsWriter) Category(c *CompsCategory) error

Category writes c. An invalid category fails with ErrInvalidComps and writes nothing.

func (*CompsWriter) Close added in v0.4.0

func (cw *CompsWriter) Close() error

Close writes the closing tag and reports the first write error.

func (*CompsWriter) Environment added in v0.4.0

func (cw *CompsWriter) Environment(e *CompsEnvironment) error

Environment writes e. An invalid environment fails with ErrInvalidComps and writes nothing.

func (*CompsWriter) Group added in v0.4.0

func (cw *CompsWriter) Group(g *CompsGroup) error

Group writes g. An invalid group fails with ErrInvalidComps and writes nothing.

func (*CompsWriter) Langpacks added in v0.4.0

func (cw *CompsWriter) Langpacks(list []CompsLangpack) error

Langpacks writes one <langpacks> element with the entries; nothing for an empty list.

func (*CompsWriter) Whiteout added in v0.4.0

func (cw *CompsWriter) Whiteout(list []CompsIgnoredDep) error

Whiteout writes one <whiteout> element with the entries; nothing for an empty list.

type Delta added in v0.4.0

type Delta struct {
	// Epoch, Version and Release identify the older version the delta is
	// applied to (the oldepoch, oldversion and oldrelease attributes).
	Epoch   uint32
	Version string
	Release string
	// Filename is the path of the .drpm file relative to the repository.
	Filename string
	// Sequence is the sequence text of the delta rpm as deltarpm records it:
	// the name-epoch:version-release of the old package, a dash and the hex
	// digest that applydeltarpm matches against the installed package, for
	// example "bash-0:5.2-1-1f8d0c...".
	Sequence string
	// Size is the size of the .drpm file and Checksum its digest.
	Size     int64
	Checksum DeltaChecksum
}

Delta is one <delta> element: a delta rpm that turns an older version of the package of its DeltaPackage into the new one.

type DeltaChecksum added in v0.4.0

type DeltaChecksum struct {
	Type  string
	Value string
}

DeltaChecksum is the digest of a delta rpm file and the name of its algorithm ("sha256" for the files createrepo_c writes by default).

type DeltaInfo added in v0.4.0

type DeltaInfo struct {
	NewPackages []DeltaPackage
}

DeltaInfo is a prestodelta.xml (deltainfo.xml) document: the delta rpms of a repository, grouped by the package they produce. Only the metadata is modelled; DeltaInfo neither reads nor creates the .drpm files. The Sequence of a delta, which deltarpm stores in the .drpm, is carried as the opaque text of the document, so a delta rpm made by makedeltarpm needs no further conversion to be listed.

func ParseDeltaInfo added in v0.4.0

func ParseDeltaInfo(r io.Reader, lim DeltaInfoLimits) (*DeltaInfo, error)

ParseDeltaInfo reads a whole prestodelta.xml. It is ReadDeltaInfo collecting the packages; bound the decompressed size of r with OpenMetadata.

type DeltaInfoLimits added in v0.4.0

type DeltaInfoLimits struct {
	// MaxPackages bounds the <newpackage> elements of the document.
	MaxPackages int
	// MaxDeltas bounds the <delta> elements of one package.
	MaxDeltas int
	// MaxFieldBytes bounds one text value or attribute; a longer one fails
	// the read with [ErrTooLarge].
	MaxFieldBytes int
}

DeltaInfoLimits bounds ReadDeltaInfo and ParseDeltaInfo. A zero field selects its default.

type DeltaInfoWriter added in v0.4.0

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

DeltaInfoWriter streams a prestodelta.xml document package by package, with memory use independent of the number of packages. The layout is the one createrepo_c --deltas writes: a <newpackage> element at two spaces, its <delta> elements at four, their children at six, and no newline after the root's end tag.

func NewDeltaInfoWriter added in v0.4.0

func NewDeltaInfoWriter(w io.Writer) *DeltaInfoWriter

NewDeltaInfoWriter writes the document header to w.

func (*DeltaInfoWriter) Close added in v0.4.0

func (w *DeltaInfoWriter) Close() error

Close writes the end of the document and reports the first write error.

func (*DeltaInfoWriter) Package added in v0.4.0

func (w *DeltaInfoWriter) Package(p *DeltaPackage) error

Package writes p. A package without deltas is left out, as createrepo_c does; a package or delta missing a required field fails with ErrMalformedDeltaInfo and writes nothing.

type DeltaPackage added in v0.4.0

type DeltaPackage struct {
	Name    string
	Epoch   uint32
	Version string
	Release string
	Arch    string
	Deltas  []Delta
}

DeltaPackage is a <newpackage> element: the package the deltas build, with the older versions they start from.

type DistroTag added in v0.4.0

type DistroTag struct {
	// CPEID is the cpeid attribute; optional.
	CPEID string
	Name  string
}

DistroTag is a <distro> tag of repomd.xml: the name of a distribution and the CPE identifiers that designate it.

type DocKind

type DocKind int

DocKind selects which repodata document a DocWriter renders.

const (
	// DocPrimary is primary.xml.
	DocPrimary DocKind = iota
	// DocFilelists is filelists.xml.
	DocFilelists
	// DocOther is other.xml.
	DocOther
	// DocFilelistsExt is filelists-ext.xml (createrepo_c --filelists-ext):
	// filelists.xml with the digest of every regular file.
	DocFilelistsExt
)

type DocWriter

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

DocWriter streams one repodata document (primary, filelists, filelists-ext or other) package by package, for a caller that merges packages from several sources: rendered ones from the database (Package) and verbatim elements read from an another document (Raw). count is the number of packages the caller will write; it is the document's packages attribute.

func NewDocWriter

func NewDocWriter(w io.Writer, kind DocKind, count int) *DocWriter

NewDocWriter writes the document header of kind to w.

func (*DocWriter) Close

func (d *DocWriter) Close() error

Close writes the closing tag and reports the first write error.

func (*DocWriter) FilelistsExt added in v0.4.0

func (d *DocWriter) FilelistsExt(p *FilelistsExtPackage) error

FilelistsExt renders p into a filelists-ext document, with the digest of the files that have one. It fails with ErrDocKind when d writes another kind of document. A package without a ChecksumType is written with "sha256".

func (*DocWriter) Package

func (d *DocWriter) Package(p *rpm.Package)

Package renders p into the document. A primary document lists it under PackageLocation.

func (*DocWriter) PackageAt added in v0.4.0

func (d *DocWriter) PackageAt(p *rpm.Package, loc Location)

PackageAt renders p into the document; loc is the location a primary document lists the package under and the other documents ignore.

func (*DocWriter) Raw

func (d *DocWriter) Raw(element []byte)

Raw appends an already serialized <package> element.

func (*DocWriter) SetChangelogLimit added in v0.4.0

func (d *DocWriter) SetChangelogLimit(n int)

SetChangelogLimit sets how many of the newest changelog entries of each package an other document keeps; zero or less keeps all of them.

type FilelistsExtPackage added in v0.4.0

type FilelistsExtPackage struct {
	// PkgID is the checksum of the package, the pkgid of its primary.xml
	// entry.
	PkgID   string
	Name    string
	Arch    string
	Epoch   uint32
	Version string
	Release string
	// ChecksumType is the algorithm of the file digests, the type of the
	// <checksum> element: "sha256" for the packages rpm builds by default.
	ChecksumType string
	Files        []FilelistsFile
}

FilelistsExtPackage is a <package> element of filelists-ext.xml, the document createrepo_c --filelists-ext writes: the file list of the package with the digest of every regular file. A filelists.xml package reads into the same type with empty digests.

type FilelistsFile added in v0.4.0

type FilelistsFile struct {
	// Path is the absolute path of the file.
	Path string
	// Type is [FileTypeDir], [FileTypeGhost] or empty for any other entry.
	Type string
	// Hash is the hex digest of the content of a regular file, computed with
	// the algorithm of [FilelistsExtPackage.ChecksumType]; empty for
	// directories, ghost files, symbolic links and files the package carries
	// no digest for.
	Hash string
}

FilelistsFile is a <file> element of filelists-ext.xml.

type FilelistsLimits added in v0.4.0

type FilelistsLimits struct {
	// MaxFiles bounds the <file> entries of a package; a package with more
	// fails the read with [ErrTooLarge].
	MaxFiles int
	// MaxFileBytes bounds the total size of the paths of a package.
	MaxFileBytes int
	// MaxFieldBytes bounds one path, digest or attribute.
	MaxFieldBytes int
}

FilelistsLimits bounds ReadFilelistsExt. A zero field selects its default.

type FilelistsPackage added in v0.4.0

type FilelistsPackage struct {
	// PkgID is the checksum that identifies the package, the pkgid of
	// filelists.xml.
	PkgID string
	// Files holds the path of every file, and marks the directories (Mode)
	// and the ghost files (Flags).
	Files []rpm.FileEntry
}

FilelistsPackage is the file list of one package of a filelists database.

type Location added in v0.4.0

type Location struct {
	Href string
	Base string
}

Location is where a package is served from: Href relative to the repository, or to Base when set (createrepo_c --baseurl).

type MetadataFile added in v0.4.0

type MetadataFile struct {
	Record RepomdData
	Data   []byte
}

MetadataFile is a metadata file ready for the repodata directory: the repomd.xml record that describes it and the bytes to store under the record's Location.

func AppStreamRecords added in v0.4.0

func AppStreamRecords(a AppStream, opts RecordOptions) ([]MetadataFile, error)

AppStreamRecords returns the files and records that publish a: the "appstream" record for appstream.xml and the "appstream-icons" record for appstream-icons.tar, each stored as NewRecord does with opts. Register the records with AddRecord and write the files under the repository root.

Example

Register an AppStream catalog in a repository, the way modifyrepo_c does: the helper returns the record and the bytes of the file to store next to repomd.xml, and AddRecord puts the record in its place.

package main

import (
	"fmt"
	"log"
	"strings"

	"github.com/M0Rf30/pkgformat/rpm/repodata"
)

func main() {
	repomd := &repodata.Repomd{Revision: "1", Data: []repodata.RepomdData{
		{Type: "primary", Location: "repodata/primary.xml.gz"},
	}}

	catalog := []byte("<components version=\"0.16\"><component type=\"desktop-application\"><id>org.example.Demo</id></component></components>")

	files, err := repodata.AppStreamRecords(repodata.AppStream{Components: catalog}, repodata.RecordOptions{
		Compression: repodata.Gzip, Timestamp: 1700000000,
	})
	if err != nil {
		log.Fatal(err)
	}

	for _, f := range files {
		repodata.AddRecord(repomd, f.Record)
		fmt.Println(strings.Replace(f.Record.Location, f.Record.Checksum, "<checksum>", 1), f.Record.OpenSize)
	}

	for _, d := range repomd.Data {
		fmt.Println(d.Type)
	}
}
Output:
repodata/<checksum>-appstream.xml.gz 115
primary
appstream

type ModuleArtifacts added in v0.4.0

type ModuleArtifacts struct {
	// RPMs holds the NEVRA of every binary and source package, as
	// [PackageNEVRA] builds them.
	RPMs []string
	// RPMMap links the checksum of a package in repomd to its NEVRA parts:
	// digest type, then checksum.
	RPMMap map[string]map[string]ModuleRPMMapEntry
}

ModuleArtifacts lists what the build produced.

type ModuleBuildOpts added in v0.4.0

type ModuleBuildOpts struct {
	// Macros is text appended to the rpm macros of the buildroot.
	Macros string
	// Whitelist lists the package names the build may produce.
	Whitelist []string
	// Arches limits the architectures the module is built for.
	Arches []string
}

ModuleBuildOpts holds the build options that apply to the whole module.

type ModuleComponents added in v0.4.0

type ModuleComponents struct {
	RPMs    map[string]ModuleRPMComponent
	Modules map[string]ModuleModuleComponent
}

ModuleComponents are the rpms and modules a stream is built from, by key.

type ModuleDefaults added in v0.4.0

type ModuleDefaults struct {
	Module string
	// Modified is the revision of the document as YYYYMMDDHHMM; zero is
	// absent.
	Modified uint64
	// Stream is the default stream; empty means the module has none.
	Stream string
	// Profiles maps a stream to the profiles installed by default.
	Profiles map[string][]string
	// Intents overrides the defaults for a kind of system ("server",
	// "desktop"), by the name the system declares.
	Intents map[string]ModuleDefaultsIntent
}

ModuleDefaults is a modulemd-defaults v1 document: the default stream of a module and the default profiles of its streams.

type ModuleDefaultsIntent added in v0.4.0

type ModuleDefaultsIntent struct {
	Stream   string
	Profiles map[string][]string
}

ModuleDefaultsIntent is the override of the defaults for one intent.

type ModuleDependency added in v0.4.0

type ModuleDependency struct {
	BuildRequires map[string][]string
	Requires      map[string][]string
}

ModuleDependency is one combination of dependencies of a stream: the module streams it builds against and the ones it needs at run time. The values are the stream lists that satisfy the dependency; an empty list accepts any stream and a name with a leading "-" excludes a stream.

type ModuleDocument added in v0.4.0

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

ModuleDocument is one document of a modules.yaml: a ModuleStream, a ModuleDefaults, a ModuleObsoletes or a ModuleTranslations, always handled through a pointer.

type ModuleIndex

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

ModuleIndex records which module streams a repository offers, to filter modular packages the way dnf does when no module is enabled: the packages of a non-default stream of a module that has a default stream are blocked. The zero value is empty and ready to use; an empty index blocks nothing.

func (*ModuleIndex) Add

func (m *ModuleIndex) Add(r io.Reader, maxSize int64) error

Add reads a modules.yaml (already decompressed, see OpenMetadata) into the index; maxSize bounds it (0 selects DefaultMaxModulesDocument) and a larger document fails with ErrTooLarge. Malformed documents are skipped; the first default stream of a module wins. Streams and defaults may come from different files: the blocked set covers everything added so far.

func (*ModuleIndex) Blocked

func (m *ModuleIndex) Blocked(release, nevra string) bool

Blocked reports whether the package belongs to a non-default stream, so a repository client must not offer it. nevra is the string PackageNEVRA builds. Non-modular packages are never blocked.

func (*ModuleIndex) DefaultStream

func (m *ModuleIndex) DefaultStream(module string) (string, bool)

DefaultStream returns the default stream of a module.

func (*ModuleIndex) Defaults

func (m *ModuleIndex) Defaults() int

Defaults returns the number of modules that have a default stream.

type ModuleLicense added in v0.4.0

type ModuleLicense struct {
	Module  []string
	Content []string
}

ModuleLicense lists the SPDX-style licenses of the module metadata and of the packages inside it.

type ModuleModuleComponent added in v0.4.0

type ModuleModuleComponent struct {
	Rationale  string
	Repository string
	Ref        string
	BuildOrder int64
	BuildAfter []string
	BuildOnly  bool
}

ModuleModuleComponent is a module built inside another one.

type ModuleObsoletedBy added in v0.4.0

type ModuleObsoletedBy struct {
	Module string
	Stream string
}

ModuleObsoletedBy names the module stream that replaces an obsolete one.

type ModuleObsoletes added in v0.4.0

type ModuleObsoletes struct {
	Module  string
	Stream  string
	Context string
	// Modified is when the record was written, in UTC to the minute.
	Modified time.Time
	// EOLDate is when the stream ends; the zero time is absent.
	EOLDate time.Time
	Message string
	// Reset cancels the earlier obsoletes records of the stream.
	Reset bool
	// ObsoletedBy names the stream that replaces this one.
	ObsoletedBy *ModuleObsoletedBy
}

ModuleObsoletes is a modulemd-obsoletes v1 document: a stream, or one context of it, that is no longer maintained.

type ModuleProfile added in v0.4.0

type ModuleProfile struct {
	Description string
	RPMs        []string
	// Default marks the profile dnf installs when none is named.
	Default bool
}

ModuleProfile is a set of packages a user installs together.

type ModuleRPMComponent added in v0.4.0

type ModuleRPMComponent struct {
	// Name is the package name when it differs from the key.
	Name       string
	Rationale  string
	Repository string
	Cache      string
	Ref        string
	// Buildroot and SRPMBuildroot install the buildroot profiles for the
	// later build batches.
	Buildroot     bool
	SRPMBuildroot bool
	// BuildOrder groups components into build batches; zero means none.
	// BuildAfter is the alternative that names the components to build
	// after; a component sets at most one of the two.
	BuildOrder int64
	BuildAfter []string
	BuildOnly  bool
	Arches     []string
	Multilib   []string
}

ModuleRPMComponent is a source package built into the module.

type ModuleRPMMapEntry added in v0.4.0

type ModuleRPMMapEntry struct {
	Name    string
	Epoch   uint64
	Version string
	Release string
	Arch    string
}

ModuleRPMMapEntry describes an artifact of RPMMap. The NEVRA is derived from the fields.

func (ModuleRPMMapEntry) NEVRA added in v0.4.0

func (e ModuleRPMMapEntry) NEVRA() string

NEVRA returns "name-epoch:version-release.arch".

type ModuleReferences added in v0.4.0

type ModuleReferences struct {
	Community     string
	Documentation string
	Tracker       string
}

ModuleReferences points at the community, documentation and issue tracker of the module.

type ModuleServiceLevel added in v0.4.0

type ModuleServiceLevel struct {
	// EOL is the end-of-life date as "YYYY-MM-DD"; empty when none.
	EOL string
}

ModuleServiceLevel is the support commitment of a stream.

type ModuleSet added in v0.4.0

type ModuleSet struct {
	Streams      []*ModuleStream
	Defaults     []*ModuleDefaults
	Obsoletes    []*ModuleObsoletes
	Translations []*ModuleTranslations
}

ModuleSet is the content of a modules.yaml: its documents by kind.

func ParseModulemd added in v0.4.0

func ParseModulemd(r io.Reader, lim ModulemdLimits) (*ModuleSet, error)

ParseModulemd reads every document of a modules.yaml (already decompressed, see OpenMetadata) into a ModuleSet, in the order they appear. It fails on the first document ReadModulemd rejects.

Example

Read the modules.yaml of a repository and list what it offers, then write a stream of your own the way libmodulemd would.

package main

import (
	"fmt"
	"log"
	"strings"

	"github.com/M0Rf30/pkgformat/rpm/repodata"
)

func main() {
	const modulesYAML = `---
document: modulemd-defaults
version: 1
data:
  module: nginx
  stream: "1.24"
  profiles:
    "1.24": [common]
...
---
document: modulemd
version: 2
data:
  name: nginx
  stream: "1.24"
  version: 9040020240101000000
  context: 9
  arch: x86_64
  summary: nginx webserver
  description: >-
    nginx 1.24 webserver module
  license:
    module:
    - MIT
  dependencies:
  - buildrequires:
      platform: [el9.4.0]
    requires:
      platform: [el9]
  profiles:
    common:
      rpms:
      - nginx
  artifacts:
    rpms:
    - nginx-1:1.24.0-1.module+el9.4.0+1+deadbeef.x86_64
...
`

	set, err := repodata.ParseModulemd(strings.NewReader(modulesYAML), repodata.ModulemdLimits{})
	if err != nil {
		log.Fatal(err)
	}

	for _, d := range set.Defaults {
		fmt.Printf("default of %s: %s %v\n", d.Module, d.Stream, d.Profiles[d.Stream])
	}

	for _, s := range set.Streams {
		fmt.Println(s.NSVCA(), "requires", s.Dependencies[0].Requires["platform"], "installs", s.Profiles["common"].RPMs)
	}

}
Output:
default of nginx: 1.24 [common]
nginx:1.24:9040020240101000000:9:x86_64 requires [el9] installs [nginx]

type ModuleStream added in v0.4.0

type ModuleStream struct {
	Name   string
	Stream string
	// Version is the build version, a timestamp by convention; zero is
	// absent.
	Version uint64
	Context string
	// StaticContext marks Context as chosen by the packager instead of a
	// hash of the build.
	StaticContext bool
	Arch          string
	Summary       string
	Description   string
	// ServiceLevels maps a service level name ("rawhide", "bug_fixes", ...)
	// to its end of life.
	ServiceLevels map[string]ModuleServiceLevel
	License       ModuleLicense
	// XMD is the opaque extensible metadata block. Values are strings,
	// booleans, []any and map[string]any: like libmodulemd, a number read from
	// the document is kept as a string.
	XMD          map[string]any
	Dependencies []ModuleDependency
	References   ModuleReferences
	// Profiles maps a profile name to its package lists.
	Profiles map[string]ModuleProfile
	// API lists the binary rpm names that are the stable interface of the
	// module and Filter those left out of it.
	API    []string
	Filter []string
	// Demodularized lists binary rpm names that stopped being part of the
	// module.
	Demodularized []string
	BuildOpts     *ModuleBuildOpts
	Components    ModuleComponents
	Artifacts     ModuleArtifacts
}

ModuleStream is a modulemd v2 document: one build of one stream of a module. Collections left nil are absent from the document; a non-nil empty XMD is written as "xmd: {}".

func (*ModuleStream) NSVCA added in v0.4.0

func (s *ModuleStream) NSVCA() string

NSVCA returns "name:stream:version:context:arch" with the empty trailing parts dropped, the key libmodulemd orders and identifies stream builds by.

type ModuleTranslation added in v0.4.0

type ModuleTranslation struct {
	Summary     string
	Description string
	// Profiles maps a profile name to its translated description.
	Profiles map[string]string
}

ModuleTranslation holds the translated summary, description and profile descriptions of a stream in one locale.

type ModuleTranslations added in v0.4.0

type ModuleTranslations struct {
	Module   string
	Stream   string
	Modified uint64
	// Locales maps a locale ("es_ES", "ja") to its texts.
	Locales map[string]ModuleTranslation
}

ModuleTranslations is a modulemd-translations v1 document: the texts of one stream in other languages.

type ModulemdLimits added in v0.4.0

type ModulemdLimits struct {
	// MaxBytes bounds the whole modules.yaml; a larger one fails the read
	// with [ErrTooLarge]. The default is [DefaultMaxModulesDocument].
	MaxBytes int64
	// MaxDocumentBytes bounds one document, the unit kept in memory. The
	// default is [DefaultMaxModulemdDocument].
	MaxDocumentBytes int
	// MaxEntries bounds every list and mapping of a document. The default
	// is [DefaultMaxModulemdEntries].
	MaxEntries int
	// MaxDepth bounds the nesting of the xmd block. The default is
	// [DefaultMaxModulemdDepth].
	MaxDepth int
}

ModulemdLimits bounds ReadModulemd and ParseModulemd. A zero field selects its default.

type OtherPackage added in v0.4.0

type OtherPackage struct {
	// PkgID is the checksum that identifies the package.
	PkgID string
	// Changelogs lists the entries newest first, the order of a header and of
	// [rpm.Package.Changelogs].
	Changelogs []rpm.ChangelogEntry
}

OtherPackage is the changelog of one package of an other database.

type PackageInfo

type PackageInfo struct {
	Name  string
	Arch  string
	Epoch string
	Ver   string
	Rel   string
	// PkgID is the package checksum (primary: the checksum element, filelists
	// and other: the pkgid attribute).
	PkgID string
	// Href is the package location of a primary element.
	Href string
}

PackageInfo identifies a <package> element of a primary, filelists, filelists-ext or other document. Filelists, filelists-ext and other documents identify the package by the pkgid attribute (a filelists-ext <checksum> element only names the algorithm of the file digests); primary carries the checksum and the location.

func (PackageInfo) NEVRA

func (i PackageInfo) NEVRA() string

NEVRA is the identity two sources' packages collide on.

type PrimaryLimits

type PrimaryLimits struct {
	// MaxDependencies bounds each dependency list; a longer one fails the
	// read with [ErrTooLarge].
	MaxDependencies int
	// MaxFiles bounds the <file> entries of a package; a package with more
	// fails the read with [ErrTooLarge].
	MaxFiles int
	// MaxFileBytes bounds the total size of the <file> paths of a package.
	MaxFileBytes int
	// MaxFieldBytes bounds one text field of a package.
	MaxFieldBytes int
}

PrimaryLimits bounds ReadPrimary. A zero field selects its default.

type PrimaryPackage

type PrimaryPackage struct {
	// Package holds the identity, sizes, dependencies and the <file> paths
	// that primary.xml lists. SHA256 is set when the checksum type is sha256.
	rpm.Package
	// Location is the href of the .rpm file relative to the repository (or
	// to Base) and Base the optional xml:base of the location.
	Location string
	Base     string
	// Checksum is the digest of the .rpm file and ChecksumType its
	// algorithm.
	Checksum     string
	ChecksumType string
}

PrimaryPackage is a <package> element of primary.xml.

type RecordOptions added in v0.4.0

type RecordOptions struct {
	// Compression is the compression of the stored file; it is ignored when
	// Store is set.
	Compression Compression
	// Store keeps the file as it is, with no compression: the record has no
	// open-checksum or open-size (modifyrepo_c --no-compress).
	Store bool
	// SimpleNames names the file repodata/<name> instead of
	// repodata/<checksum>-<name> (modifyrepo_c --simple-md-filenames).
	SimpleNames bool
	// Timestamp is the Unix time recorded in repomd.xml. Zero is the current
	// time; pin it for reproducible metadata.
	Timestamp int64
	// MaxSize bounds the decompressed size of an input that arrives
	// compressed; zero selects [DefaultMaxDocument].
	MaxSize int64
}

RecordOptions selects how NewRecord stores a file in the repository. The zero value is what modifyrepo_c does by default: gzip compression, a file name with the checksum in front of it, and the current time as timestamp.

type Repomd

type Repomd struct {
	// Revision identifies the state of the repository; the current Unix time
	// when empty at [Repomd.Marshal].
	Revision string
	// Content, Repo and Distro are the <tags> of the repository: what it
	// contains, what it is, and the distributions it is for.
	Content []string
	Repo    []string
	Distro  []DistroTag
	Data    []RepomdData
}

Repomd is a repomd.xml: the index of the metadata files of a repository.

func ParseRepomd

func ParseRepomd(r io.Reader) (*Repomd, error)

ParseRepomd parses a repomd.xml. The document is bounded to a few megabytes and a thousand data entries; a larger one fails with ErrTooLarge.

func (*Repomd) Find

func (m *Repomd) Find(dataType string) (RepomdData, bool)

Find returns the first data entry of the given type.

func (*Repomd) Marshal added in v0.4.0

func (m *Repomd) Marshal() ([]byte, error)

Marshal renders m as repomd.xml exactly as createrepo_c does: revision, tags, then the data entries, each with its checksum, open-checksum, header-checksum, location, timestamp, size, open-size, header-size and database_version; an element without a value is left out.

func (*Repomd) SortData added in v0.4.0

func (m *Repomd) SortData()

SortData orders the data entries of m as createrepo_c does: primary, filelists, other, their sqlite databases and then their zchunk files, followed by every other record by type and location.

type RepomdData

type RepomdData struct {
	// Type is the kind of the file: "primary", "filelists", "other",
	// "group", "modules", and so on.
	Type string
	// Location is the path of the file relative to the repository root.
	Location string
	// Checksum is the hex digest of the file and ChecksumType its algorithm,
	// "sha256" for the files this package writes.
	Checksum     string
	ChecksumType string
	// OpenChecksum is the digest of the uncompressed content; optional.
	OpenChecksum     string
	OpenChecksumType string
	// HeaderChecksum is the digest of the header of a zchunk file and
	// HeaderSize the length of that header; both are empty for any other
	// kind of file.
	HeaderChecksum     string
	HeaderChecksumType string
	HeaderSize         int64
	// Timestamp is the Unix time the file was generated.
	Timestamp int64
	// Size is the size of the file and OpenSize that of the uncompressed
	// content; OpenSize is optional.
	Size     int64
	OpenSize int64
	// DatabaseVersion is the schema version of a SQLite database
	// ([DatabaseVersion] for the ones this package writes); zero for any
	// other kind of file.
	DatabaseVersion int
}

RepomdData is one data entry of repomd.xml: a metadata file of the repository and how to check it.

func DatabaseEntry added in v0.4.0

func DatabaseEntry(c *CompressedMetadata, kind DocKind, name string, timestamp int64) RepomdData

DatabaseEntry returns the repomd.xml data entry of a compressed database stored as repodata/<name>: CompressedMetadata.Entry typed by DatabaseType and carrying the DatabaseVersion.

func NewOpaqueRecord added in v0.4.0

func NewOpaqueRecord(typ, name string, data []byte, comp Compression, ts int64) (RepomdData, []byte, error)

NewOpaqueRecord compresses data with comp and returns the repomd.xml record of type typ for it together with the file to store, as modifyrepo_c does: the file is repodata/<checksum>-<name>.<extension>, the record carries the checksum and size of the file and the open-checksum and open-size of data, and ts is its timestamp (zero is the current time).

name is the name of the document the record is for, "appstream.xml" for example. When it ends in .gz, .xz, .zst or .bz2, data is read as that compressed file and decompressed first, and the suffix is not part of the name. An empty typ is derived from name, the part before its first dot.

Example

An arbitrary document becomes a record of any type; RemoveRecord undoes it.

package main

import (
	"fmt"
	"log"
	"strings"

	"github.com/M0Rf30/pkgformat/rpm/repodata"
)

func main() {
	repomd := &repodata.Repomd{}

	rec, file, err := repodata.NewOpaqueRecord("custom", "custom.xml", []byte("<custom/>"), repodata.Zstd, 1700000000)
	if err != nil {
		log.Fatal(err)
	}

	repodata.AddRecord(repomd, rec)
	fmt.Println(rec.Type, rec.OpenSize, strings.HasSuffix(rec.Location, "-custom.xml.zst"), len(file) > 0)

	removed := repodata.RemoveRecord(repomd, "custom")
	fmt.Println(len(removed), len(repomd.Data))
}
Output:
custom 9 true true
1 0

func NewRecord added in v0.4.0

func NewRecord(typ, name string, data []byte, opts RecordOptions) (RepomdData, []byte, error)

NewRecord is NewOpaqueRecord with the options of modifyrepo_c: storing the file uncompressed and naming it without the checksum.

func PrestoDeltaRecord added in v0.4.0

func PrestoDeltaRecord(info *DeltaInfo, opts RecordOptions) (RepomdData, []byte, error)

PrestoDeltaRecord renders info as prestodelta.xml and returns the "prestodelta" record and file for it, stored as NewRecord does with opts.

func RemoveRecord added in v0.4.0

func RemoveRecord(m *Repomd, typ string) []RepomdData

RemoveRecord removes the records of type typ from m as modifyrepo_c --remove does, sorts the rest with Repomd.SortData and returns what it removed, so that the caller can delete the files that are no longer referenced. It returns nil when m has no such record.

type SQLiteDB added in v0.4.0

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

SQLiteDB is an open primary, filelists or other database.

func OpenSQLite added in v0.4.0

func OpenSQLite(r io.Reader, lim SQLiteLimits) (*SQLiteDB, error)

OpenSQLite spools a decompressed database from r (see OpenMetadata) to a temporary file, at most SQLiteLimits.MaxBytes of it, and opens it. Close the result to remove the file.

func OpenSQLiteFile added in v0.4.0

func OpenSQLiteFile(path string, lim SQLiteLimits) (*SQLiteDB, error)

OpenSQLiteFile opens a decompressed database file that is not modified while it is open.

func (*SQLiteDB) Close added in v0.4.0

func (d *SQLiteDB) Close() error

Close closes the database and removes the file OpenSQLite spooled.

func (*SQLiteDB) Filelists added in v0.4.0

func (d *SQLiteDB) Filelists(fn func(*FilelistsPackage) error) error

Filelists calls fn for every package of a filelists database in pkgKey order. A limit exceeded (ErrTooLarge) or an error of fn stops the read and is returned.

func (*SQLiteDB) Info added in v0.4.0

func (d *SQLiteDB) Info() SQLiteInfo

Info returns the db_info of the database.

func (*SQLiteDB) Kind added in v0.4.0

func (d *SQLiteDB) Kind() DocKind

Kind returns which document the database is of: DocPrimary, DocFilelists or DocOther.

func (*SQLiteDB) Other added in v0.4.0

func (d *SQLiteDB) Other(fn func(*OtherPackage) error) error

Other calls fn for every package of an other database in pkgKey order. A limit exceeded (ErrTooLarge) or an error of fn stops the read and is returned.

func (*SQLiteDB) Primary added in v0.4.0

func (d *SQLiteDB) Primary(fn func(*PrimaryPackage) error) error

Primary calls fn for every package of a primary database in pkgKey order. Like ReadPrimary, it skips a package without a name or an architecture and one with a malformed or negative number; a limit exceeded (ErrTooLarge) or an error of fn stops the read and is returned. The dependencies come with the filtering primary.xml applied.

type SQLiteInfo added in v0.4.0

type SQLiteInfo struct {
	// Version is the schema version, [DatabaseVersion] for every database
	// this package reads.
	Version int
	// Checksum is the checksum of the compressed XML document the database
	// was written with; empty when the database records none.
	Checksum string
}

SQLiteInfo is the db_info table of a database.

type SQLiteLimits added in v0.4.0

type SQLiteLimits struct {
	// MaxBytes bounds the size of the database; a larger one fails with
	// [ErrTooLarge]. Default [DefaultMaxDatabaseBytes].
	MaxBytes int64
	// TempDir is where [OpenSQLite] spools the database; the default is
	// os.TempDir.
	TempDir string
	// MaxDependencies, MaxFiles, MaxFileBytes and MaxFieldBytes bound each
	// package like the fields of [PrimaryLimits] do; exceeding one fails the
	// read with [ErrTooLarge]. MaxFiles and MaxFileBytes apply to the files of
	// both primary and filelists databases.
	MaxDependencies int
	MaxFiles        int
	MaxFileBytes    int
	MaxFieldBytes   int
	// MaxChangelogs bounds the changelog entries of a package. Default
	// [DefaultMaxChangelogs].
	MaxChangelogs int
}

SQLiteLimits bounds OpenSQLite and what the readers of the database return. A zero field selects its default.

type SQLiteOptions added in v0.4.0

type SQLiteOptions struct {
	// XMLChecksum is the hex checksum of the compressed XML document the
	// database accompanies (the checksum of its repomd.xml data entry). It is
	// recorded in db_info, which clients compare with repomd.xml to tell
	// whether a database they hold is current. Empty records NULL.
	XMLChecksum string
	// Location gives the location a primary database lists a package under;
	// nil lists every package under [PackageLocation]. The other databases
	// ignore it.
	Location func(*rpm.Package) Location
	// ChangelogLimit is how many of the newest changelog entries of each
	// package an other database keeps: zero selects [DefaultChangelogLimit]
	// and a negative value keeps all of them.
	ChangelogLimit int
	// TempDir is where the database is assembled before it is copied out; the
	// default is os.TempDir.
	TempDir string
}

SQLiteOptions tunes WriteSQLite and CompressSQLite.

type UpdateinfoLimits added in v0.4.0

type UpdateinfoLimits struct {
	// MaxUpdates bounds the advisories of the document.
	MaxUpdates int
	// MaxReferences bounds the references of one advisory.
	MaxReferences int
	// MaxCollections bounds the collections of one advisory.
	MaxCollections int
	// MaxPackages bounds the packages of one advisory, summed over its
	// collections.
	MaxPackages int
	// MaxFieldBytes bounds one text field of an advisory.
	MaxFieldBytes int
}

UpdateinfoLimits bounds ReadUpdateinfo. A zero field selects its default.

type UpdateinfoWriter added in v0.4.0

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

UpdateinfoWriter streams updateinfo.xml advisory by advisory.

func NewUpdateinfoWriter added in v0.4.0

func NewUpdateinfoWriter(w io.Writer) *UpdateinfoWriter

NewUpdateinfoWriter writes the document header of an updateinfo.xml to w. Call UpdateinfoWriter.Add for each advisory, then UpdateinfoWriter.Close.

func (*UpdateinfoWriter) Add added in v0.4.0

func (u *UpdateinfoWriter) Add(a *Advisory) error

Add renders a into the document in the layout of createrepo_c: an element or attribute without a value is left out, except for <references> and <pkglist>. An advisory without an id, or a package with a checksum but no checksum type, fails with ErrInvalidUpdateinfo and writes nothing; a write error of an earlier advisory is returned too.

func (*UpdateinfoWriter) Close added in v0.4.0

func (u *UpdateinfoWriter) Close() error

Close writes the closing tag and reports the first write error.

type ZchunkChecksum added in v0.4.0

type ZchunkChecksum int

ZchunkChecksum is a checksum algorithm of a zchunk file.

const (
	// ZchunkSHA512_128 is the first 128 bits of SHA-512: the checksum zck
	// uses for chunks, and the zero value of the options.
	ZchunkSHA512_128 ZchunkChecksum = iota
	// ZchunkSHA256 is SHA-256: the checksum of the header and of the data of
	// every file this package writes.
	ZchunkSHA256
	// ZchunkSHA512 is SHA-512.
	ZchunkSHA512
	// ZchunkSHA1 is SHA-1. It is read and verified but never written.
	ZchunkSHA1
)

func (ZchunkChecksum) Size added in v0.4.0

func (c ZchunkChecksum) Size() int

Size is the length in bytes of a digest of the algorithm.

func (ZchunkChecksum) String added in v0.4.0

func (c ZchunkChecksum) String() string

String returns the name of the algorithm: "sha1", "sha256", "sha512" or "sha512-128".

type ZchunkChunk added in v0.4.0

type ZchunkChunk struct {
	// Index is the position of the chunk in the index; the dictionary is 0
	// and the first data chunk 1.
	Index int
	// Offset is where the compressed chunk starts in the file and
	// CompressedSize its length; a range request for
	// [Offset, Offset+CompressedSize) fetches the chunk.
	Offset         int64
	CompressedSize int64
	// Size is the length of the chunk once decompressed.
	Size int64
	// Checksum is the digest of the compressed chunk, by the chunk checksum
	// type of the header. Two chunks with the same checksum hold the same
	// bytes.
	Checksum []byte
	// UncompressedChecksum is the digest of the decompressed chunk; only a
	// file made to be applied against an uncompressed source has it.
	UncompressedChecksum []byte
}

ZchunkChunk is one entry of the index of a zchunk file: a chunk of the compressed data, or the compression dictionary.

func (ZchunkChunk) End added in v0.4.0

func (c ZchunkChunk) End() int64

End is the offset after the last byte of the compressed chunk.

type ZchunkChunking added in v0.4.0

type ZchunkChunking int

ZchunkChunking selects where a ZchunkWriter ends a chunk.

const (
	// ZchunkContentDefined ends a chunk where a rolling hash of the content
	// says so, as zck does by default, so equal content gives equal chunks
	// wherever it sits in the file. The chunks are about 32 KiB.
	ZchunkContentDefined ZchunkChunking = iota
	// ZchunkManual ends a chunk only at [ZchunkWriter.EndChunk], or when it
	// reaches the maximum chunk size.
	ZchunkManual
	// ZchunkXMLPackages ends a chunk before every <package> element that
	// starts a line, and when it reaches the maximum chunk size: one chunk
	// for the document header and one per package, which is how createrepo_c
	// chunks primary, filelists and other. A document without such elements
	// is a single chunk.
	ZchunkXMLPackages
)

type ZchunkCompression added in v0.4.0

type ZchunkCompression int

ZchunkCompression is the compression of the chunks of a zchunk file.

const (
	// ZchunkZstd compresses every chunk as a zstd frame. The zero value.
	ZchunkZstd ZchunkCompression = iota
	// ZchunkNone stores the chunks as they are.
	ZchunkNone
)

func (ZchunkCompression) String added in v0.4.0

func (c ZchunkCompression) String() string

type ZchunkDecoder added in v0.4.0

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

ZchunkDecoder checks and decompresses the chunks of one zchunk file, for a client that fetches them itself: the ones it is missing by range requests and the others from an older copy.

func NewZchunkDecoder added in v0.4.0

func NewZchunkDecoder(h *ZchunkHeader, dict []byte, opts ZchunkReadOptions) (*ZchunkDecoder, error)

NewZchunkDecoder prepares to decode the chunks of the file h describes. dict is the compressed dictionary chunk, as stored in the file at h.Dict.Offset; it is required when h.HasDict() and ignored otherwise.

func (*ZchunkDecoder) Close added in v0.4.0

func (d *ZchunkDecoder) Close()

Close releases the decoder.

func (*ZchunkDecoder) Decode added in v0.4.0

func (d *ZchunkDecoder) Decode(c ZchunkChunk, data []byte) ([]byte, error)

Decode verifies the compressed chunk c against the checksum of its index entry and returns its decompressed content. For an uncompressed file the result is data itself.

type ZchunkHeader added in v0.4.0

type ZchunkHeader struct {
	// Detached is set for a header stored apart from its file ("\0ZHR1").
	Detached bool
	// ChecksumType is the algorithm of Checksum and DataChecksum.
	ChecksumType ZchunkChecksum
	// Size is the length of the header, lead included: the offset of the
	// compressed data in the file (the header-size of repomd.xml).
	Size int64
	// Checksum is the digest of the header (the header-checksum of
	// repomd.xml).
	Checksum []byte
	// DataChecksum is the digest of everything after the header; all zeros
	// when UncompressedSource is set.
	DataChecksum []byte
	// Compression is how the chunks are compressed.
	Compression ZchunkCompression
	// UncompressedSource is set when the file can be applied against an
	// uncompressed source: its index has the digest of each decompressed
	// chunk.
	UncompressedSource bool
	// ChunkChecksumType is the algorithm of the chunk checksums.
	ChunkChecksumType ZchunkChecksum
	// Dict is the zstd dictionary the chunks are compressed with; its Size
	// is 0 when there is none.
	Dict ZchunkChunk
	// Chunks are the data chunks, in file order.
	Chunks []ZchunkChunk
	// Signatures are the signatures of the header, if any.
	Signatures []ZchunkSignature
}

ZchunkHeader is the parsed header of a zchunk file: everything needed to know which chunks a download must fetch.

func ReadZchunkHeader added in v0.4.0

func ReadZchunkHeader(r io.Reader, opts ZchunkReadOptions) (*ZchunkHeader, error)

ReadZchunkHeader reads and verifies the header of a zchunk file (or a detached header) from the start of r, and reads nothing after it. This is what a client downloads, by a range request for the header-size bytes repomd.xml gives, to decide which chunks it is missing.

func (*ZchunkHeader) DataSize added in v0.4.0

func (h *ZchunkHeader) DataSize() int64

DataSize is the length of the compressed data: the dictionary and the chunks.

func (*ZchunkHeader) FileSize added in v0.4.0

func (h *ZchunkHeader) FileSize() int64

FileSize is the length of the whole file.

func (*ZchunkHeader) HasDict added in v0.4.0

func (h *ZchunkHeader) HasDict() bool

HasDict reports whether the chunks are compressed with a dictionary.

func (*ZchunkHeader) HexChecksum added in v0.4.0

func (h *ZchunkHeader) HexChecksum() string

HexChecksum is Checksum in hexadecimal, as repomd.xml records it.

func (*ZchunkHeader) MissingChunks added in v0.4.0

func (h *ZchunkHeader) MissingChunks(old *ZchunkHeader) []ZchunkChunk

MissingChunks returns the chunks of the file h describes that a client holding the file old does not have, in file order, each distinct chunk once: the ones to fetch with range requests. Chunks are matched by checksum, which is only meaningful when both files use the same chunk checksum type, compression and dictionary; when they do not, or old is nil, every chunk is missing.

Example

A client that has an older copy of a zchunk file fetches the header of the new one (the header-size bytes of repomd.xml), compares the chunk lists, and requests only the ranges of the chunks it lacks.

package main

import (
	"bytes"
	"fmt"
	"io"
	"log"
	"strings"

	"github.com/M0Rf30/pkgformat/rpm/repodata"
)

const zchunkExampleDoc = `<?xml version="1.0"?>
<metadata packages="3">
<package><name>a</name></package>
<package><name>b</name></package>
<package><name>c</name></package>
</metadata>`

func main() {
	build := func(doc string) *repodata.ZchunkHeader {
		var file bytes.Buffer

		zw, err := repodata.NewZchunkWriter(&file, repodata.ZchunkOptions{Chunking: repodata.ZchunkXMLPackages})
		if err != nil {
			log.Fatal(err)
		}

		_, _ = io.WriteString(zw, doc)

		if err := zw.Close(); err != nil {
			log.Fatal(err)
		}

		h, err := repodata.ReadZchunkHeader(&file, repodata.ZchunkReadOptions{})
		if err != nil {
			log.Fatal(err)
		}

		return h
	}

	oldH := build(zchunkExampleDoc)
	newH := build(strings.NewReplacer(`packages="3"`, `packages="4"`, "</metadata>", "<package><name>d</name></package>\n</metadata>").Replace(zchunkExampleDoc))

	missing := newH.MissingChunks(oldH)
	fmt.Println(len(missing), "of", len(newH.Chunks), "chunks to fetch in", len(repodata.ByteRanges(missing)), "ranges")
}
Output:
3 of 5 chunks to fetch in 2 ranges

func (*ZchunkHeader) UncompressedSize added in v0.4.0

func (h *ZchunkHeader) UncompressedSize() int64

UncompressedSize is the length of the decompressed content.

type ZchunkOptions added in v0.4.0

type ZchunkOptions struct {
	// Chunking selects where chunks end.
	Chunking ZchunkChunking
	// MinChunkSize and MaxChunkSize bound the chunks, by their decompressed
	// size; 1 and 10 MiB when 0. With content-defined chunking the chunk
	// size is also kept between 8 KiB and 128 KiB where these allow.
	MinChunkSize int
	MaxChunkSize int
	// Compression is how the chunks are compressed.
	Compression ZchunkCompression
	// Level is the zstd compression level, 1 to 22; 9 when 0.
	Level int
	// Dictionary is a zstd dictionary in the format zstd --train and
	// zck_gen_zdict write; every chunk is compressed with it and the
	// dictionary is stored in the file. Empty for none.
	Dictionary []byte
	// ChunkChecksum is the checksum of the chunks: [ZchunkSHA512_128]
	// (zck's default), [ZchunkSHA256] or [ZchunkSHA512].
	ChunkChecksum ZchunkChecksum
}

ZchunkOptions configures a ZchunkWriter. The zero value is a file of content-defined chunks compressed with zstd at level 9, without a dictionary and with SHA-512/128 chunk checksums, as zck writes by default.

type ZchunkRange added in v0.4.0

type ZchunkRange struct {
	Offset int64
	Length int64
}

ZchunkRange is a run of bytes of a zchunk file.

func ByteRanges added in v0.4.0

func ByteRanges(chunks []ZchunkChunk) []ZchunkRange

ByteRanges returns the ranges of the file that hold chunks, in the order given, with chunks that are adjacent in the file merged into one range so that a download makes as few requests as it can.

func (ZchunkRange) End added in v0.4.0

func (r ZchunkRange) End() int64

End is the offset after the last byte of the range.

func (ZchunkRange) String added in v0.4.0

func (r ZchunkRange) String() string

String is the range as an HTTP Range header value spells it: "bytes=first-last".

type ZchunkReadOptions added in v0.4.0

type ZchunkReadOptions struct {
	// MaxHeaderSize bounds the header, lead included;
	// [DefaultZchunkMaxHeader] when 0.
	MaxHeaderSize int64
	// MaxChunkSize bounds the decompressed size of a chunk;
	// [DefaultZchunkMaxChunk] when 0.
	MaxChunkSize int64
	// MaxSize bounds the decompressed size of the whole file;
	// [DefaultMaxDocument] when 0.
	MaxSize int64
}

ZchunkReadOptions bounds what the zchunk readers accept. The zero value selects the defaults.

type ZchunkReader added in v0.4.0

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

ZchunkReader decompresses a zchunk file as a stream, verifying the header, every chunk and the checksum of the data on the way. A chunk is held in memory while it is read, so the memory used is that of the largest chunk, never of the file.

func NewZchunkReader added in v0.4.0

func NewZchunkReader(r io.Reader, opts ZchunkReadOptions) (*ZchunkReader, error)

NewZchunkReader reads the header of the zchunk file r and its dictionary, and returns a reader of the decompressed content. An uncompressed size over opts.MaxSize is refused here with ErrTooLarge, since the header states it. A damaged file fails the read with ErrZchunkFormat or ErrZchunkChecksum, at the end of the content when it is the checksum of the data that does not match.

func (*ZchunkReader) Close added in v0.4.0

func (z *ZchunkReader) Close() error

Close releases the decoder. It does not close the underlying reader.

func (*ZchunkReader) Header added in v0.4.0

func (z *ZchunkReader) Header() *ZchunkHeader

Header returns the header of the file: its index lists the chunks.

func (*ZchunkReader) Read added in v0.4.0

func (z *ZchunkReader) Read(p []byte) (int, error)

Read implements io.Reader.

type ZchunkSignature added in v0.4.0

type ZchunkSignature struct {
	Type uint64
	Data []byte
}

ZchunkSignature is a signature of a zchunk header. The format defines no signature type; they are returned as found and not verified.

type ZchunkWriter added in v0.4.0

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

ZchunkWriter writes a zchunk file. The header carries the checksum and the size of every chunk, so it is only known once the last chunk is; the compressed chunks are held in memory until Close writes the file.

Example

Write a document as a zchunk file with a chunk per package, and read it back.

package main

import (
	"bytes"
	"fmt"
	"io"
	"log"

	"github.com/M0Rf30/pkgformat/rpm/repodata"
)

const zchunkExampleDoc = `<?xml version="1.0"?>
<metadata packages="3">
<package><name>a</name></package>
<package><name>b</name></package>
<package><name>c</name></package>
</metadata>`

func main() {
	var file bytes.Buffer

	zw, err := repodata.NewZchunkWriter(&file, repodata.ZchunkOptions{Chunking: repodata.ZchunkXMLPackages})
	if err != nil {
		log.Fatal(err)
	}

	if _, err := io.WriteString(zw, zchunkExampleDoc); err != nil {
		log.Fatal(err)
	}

	if err := zw.Close(); err != nil {
		log.Fatal(err)
	}

	zr, err := repodata.NewZchunkReader(bytes.NewReader(file.Bytes()), repodata.ZchunkReadOptions{})
	if err != nil {
		log.Fatal(err)
	}

	doc, err := io.ReadAll(zr)
	if err != nil {
		log.Fatal(err)
	}

	h := zr.Header()
	fmt.Println(len(h.Chunks), "chunks,", h.UncompressedSize() == int64(len(doc)), bytes.Equal(doc, []byte(zchunkExampleDoc)))
}
Output:
4 chunks, true true

func NewZchunkWriter added in v0.4.0

func NewZchunkWriter(w io.Writer, opts ZchunkOptions) (*ZchunkWriter, error)

NewZchunkWriter returns a writer of a zchunk file to w. Nothing is written to w before Close.

func (*ZchunkWriter) Close added in v0.4.0

func (z *ZchunkWriter) Close() error

Close ends the last chunk and writes the file to the destination. It does not close the destination. After Close, ZchunkWriter.Header describes the file.

func (*ZchunkWriter) EndChunk added in v0.4.0

func (z *ZchunkWriter) EndChunk() error

EndChunk ends the chunk being written, so that what follows starts a new one. A chunk shorter than the minimum chunk size is not ended, as in zck.

func (*ZchunkWriter) Header added in v0.4.0

func (z *ZchunkWriter) Header() *ZchunkHeader

Header returns the header of the file written, or nil before a successful Close. Its Checksum and Size are the header-checksum and header-size of the repomd.xml entry.

func (*ZchunkWriter) Write added in v0.4.0

func (z *ZchunkWriter) Write(p []byte) (int, error)

Write adds p to the document.

Jump to

Keyboard shortcuts

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