packfile

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2026 License: BSD-3-Clause Imports: 26 Imported by: ? 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 packfile reads a pack stream as git-receive-pack does and builds the pack and its version 2 index: the equivalent of `git index-pack --stdin --strict --fix-thin`, bounded.

Formats: gitformat-pack(5) (object entry header, OFS_DELTA and REF_DELTA, delta instructions, idx v2, trailer). Every object id is recomputed from the inflated content; nothing the client says about an id is believed. Every resource is bounded by Limits and each bound is refused with ErrLimit.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrLimit: a configured bound was exceeded.
	ErrLimit = errors.New("packfile: limit exceeded")
	// ErrCorrupt: the stream is not a valid pack, or an object is invalid.
	ErrCorrupt = errors.New("packfile: corrupt pack")
	// ErrMissingBase: a delta's base is neither in the pack nor in the store.
	ErrMissingBase = errors.New("packfile: unresolved delta base")
	// ErrBusy: a Result is in use by another call (Walk, a connectivity
	// check): they share the push's budget, which is not for concurrent use.
	ErrBusy = errors.New("packfile: result in use by another call")
)

Refusals. All are wrapped with %w and a precise message.

View Source
var DefaultLimits = Limits{
	MaxObjects:     2_000_000,
	MaxPackBytes:   2 << 30,
	MaxObjectBytes: 128 << 20,
	MaxTotalBytes:  4 << 30,
	MaxDeltaDepth:  4095,
	MaxLiveBytes:   512 << 20,
	MaxLinks:       4 << 20,
	Timeout:        10 * time.Minute,
}

DefaultLimits are used for every zero field of Limits.

View Source
var ErrCollision = fmt.Errorf("%w: SHA-1 collision", ErrCorrupt)

ErrCollision wraps ErrCorrupt: the SHA-1 of an object showed the signature of a collision attack (the detection git uses, SHA-1DC), or an object had the id of a different one already in the store.

View Source
var ErrNotFound = errors.New("packfile: object not found")

ErrNotFound is returned by Store.Read for an absent object.

Functions

func ApplyDelta

func ApplyDelta(base, delta []byte, maxResult int) ([]byte, error)

ApplyDelta applies a git delta to base and returns the result. The delta's base size must equal len(base), its result size must not exceed maxResult (checked before the result is allocated), and the instructions must produce exactly the announced size: a copy outside the base, an insert past the end, the reserved instruction 0x00 and trailing bytes are refused.

Types

type ID

type ID [sha1.Size]byte

ID is a SHA-1 object id.

func ParseID

func ParseID(s string) (ID, error)

ParseID parses 40 lowercase hex digits.

func (ID) String

func (id ID) String() string

String returns the 40 lowercase hex digits.

type Limits

type Limits struct {
	// MaxObjects bounds the object count the header may announce.
	MaxObjects int
	// MaxPackBytes bounds the bytes read from the stream.
	MaxPackBytes int64
	// MaxObjectBytes bounds one object's inflated size, and one delta
	// payload's, and one delta result. It is at most math.MaxInt32.
	MaxObjectBytes int
	// MaxTotalBytes bounds the work of one call: every byte inflated (entries
	// and delta streams, in both passes), every delta result produced and
	// every thin base read from the store, and every byte a Walk produces.
	// Left at zero it is autoFloor plus 256 times the bytes received so far
	// (never more than the formula of MaxPackBytes).
	MaxTotalBytes int64
	// MaxDeltaDepth bounds a delta chain.
	MaxDeltaDepth int
	// MaxLiveBytes bounds what one call holds in memory at once, in bytes:
	// the entry, id, link and index tables, the scratch buffer, delta
	// streams, delta results and bases, and the resolver's stack, one frame
	// per delta level). A fixed overhead of under 1 MiB (the stream buffer
	// and the inflater's window) is on top of it. Left at zero it is
	// autoFloor plus 32 times the bytes received so far (never more than the
	// formula of MaxPackBytes).
	MaxLiveBytes int64
	// MaxLinks bounds the references (tree entries, parents, tag targets)
	// collected for the connectivity check.
	MaxLinks int
	// MaxQuarantineBytes bounds what the call writes to its directory: the
	// pack as received plus the thin bases appended to it (a few bytes of
	// delta can name a base of any size in the store, and the base is written
	// whole). Left at zero it is autoFloor plus 9 times the bytes received so
	// far, at most twice MaxPackBytes; a thin base above that needs it set.
	MaxQuarantineBytes int64
	// Timeout bounds the whole call, on top of the context's deadline. It is
	// the deadline of the push: Result.Walk and the connectivity checks run
	// under the same one, which starts when Index starts.
	Timeout time.Duration
	// contains filtered or unexported fields
}

Limits bound what one pack may cost. A zero field means the default; a negative one is refused by Validate.

func (Limits) Validate

func (l Limits) Validate() error

Validate refuses negative limits and a MaxObjectBytes above MaxInt32 (sizes are held in 32 bits).

type Link struct {
	// To is the referenced object.
	To ID
	// Want is the type the reference requires (a tree entry of mode 40000
	// must be a tree), or 0 when any type is acceptable.
	Want Type
}

Link is a reference from one object to another, as `git fsck` follows them.

func ParseObject

func ParseObject(t Type, data []byte) ([]Link, error)

ParseObject checks an object the way `git index-pack --strict` (fsck) does, for the properties a forge relies on, and returns the references the connectivity check must follow. Blobs have none. It refuses: a commit without exactly one well-formed tree line, a malformed parent, author or committer line; a tag without a well-formed object, type, tag and tagger line; a tree with a malformed entry, a mode other than 100644, 100755, 120000, 40000 or 160000, an empty name or one containing "/", the names ".", ".." and ".git" (in any case, with the NTFS spellings "git~1", trailing spaces or dots, ":stream" and a '\' before the name, and the HFS+ spellings with ignorable code points), a symbolic link named ".gitmodules" (same spellings, with the short names "gitmod~1" to "gitmod~4" and "gi7eba~N"), entries out of git's order, or duplicate names. The spellings are ported from git's is_hfs_dotgit and is_ntfs_dotgit, and a test runs `git fsck --strict` on every one. The content of a .gitmodules blob is not checked.

type Result

type Result struct {
	// PackPath and IdxPath are the final files, "pack-<checksum>.pack" and
	// ".idx" in the directory given to Index.
	PackPath, IdxPath string
	// Checksum is the pack's SHA-1 trailer (it names the files).
	Checksum ID
	// Objects is the number of objects in the final pack (the announced
	// count plus the thin bases appended).
	Objects int
	// Appended is the number of thin-pack bases appended from the store.
	Appended int
	// Types maps every object of the pack to its type.
	Types map[ID]Type
	// Links are the references of the pack's objects, for CheckConnectivity.
	Links []Link
	// Bytes is the size of the pack stream that was read.
	Bytes int64
	// contains filtered or unexported fields
}

Result describes an indexed pack.

func Index

func Index(ctx context.Context, src io.Reader, dir string, st Store, lim Limits) (res *Result, err error)

Index reads a pack from src, verifies it, resolves its deltas (completing a thin pack from st, which may be nil when no thin pack is expected) and writes pack-<checksum>.pack and .idx into dir, which must exist and should be the caller's quarantine: nothing is written elsewhere. On error nothing is left in dir. src is read up to and including the pack trailer and no further, but it is read in buffered chunks: the pack must be the last thing in the stream.

One budget, made here and charged in bytes before every allocation and every inflate, bounds the call: MaxLiveBytes bounds what is held in memory at once (the tables of entries, ids and links, the scratch buffer, the delta streams, results and bases; a fixed overhead of under a MiB for the stream buffer and the inflater is on top) and MaxTotalBytes bounds the work (every byte inflated in either pass, delta streams included, every delta result produced and every thin base read). The announced object count, every size, the chain depth, the stream length and the elapsed time are bounded too; a pack that exceeds one is refused with an error wrapping ErrLimit. A pack that is not a valid, complete pack is refused with ErrCorrupt or ErrMissingBase.

The timeout and the context end a read of src that blocks, as far as src allows: a src with SetReadDeadline (a net.Conn) keeps the caller's read deadline, which is never touched while the context lives (an idle deadline of the caller's is an idle deadline of the call) and is what it was when Index returns; when the context ends the deadline is moved to the past to wake a blocked read, and cleared when Index returns (the caller's cannot be read back, and that call has failed: re-arm yours); otherwise a src with Close (an io.PipeReader, a file) is CLOSED when the context ends; a plain io.Reader cannot be interrupted, so it is only checked between reads, and a Read that never returns never lets Index return. Index starts no goroutine of its own that outlives it.

func (*Result) Has

func (r *Result) Has(id ID) bool

Has reports whether id is an object of the pack.

func (*Result) Walk

func (r *Result) Walk(ctx context.Context, fn func(id ID, t Type, data []byte) error) error

Walk calls fn once for every object of the indexed pack (thin bases appended from the store included), with its id, its type and its content, deltas resolved. The ids and types are the ones Index verified; the content is inflated again from the stored pack, bounded by the Limits Index ran with. data is only valid during the call: fn must copy what it keeps. An error from fn stops the walk and is returned.

A Walk is part of the push that Index began: it draws on the SAME budget (what it inflates and holds is charged to Index's MaxTotalBytes and MaxLiveBytes, on top of what Index charged: size them for Index and the walks that follow) and runs under the SAME deadline (Index's start plus Limits.Timeout), whatever ctx says. There is no way to walk with a budget of one's own: a fresh one per call let five walks deliver 47 MB beyond an exhausted MaxTotalBytes. A Result is not for concurrent use; a call made while another is running returns ErrBusy.

This is the "stream in, verified objects out" form of the indexer: a consumer that keeps objects in memory or in its own cache (rather than as a pack and idx on disk) calls Index into a scratch directory, then Walk.

type Store

type Store interface {
	// Type returns the type of the object, and whether it is present.
	Type(ctx context.Context, id ID) (Type, bool, error)
	// Read returns the object's content. It must not return more than max
	// bytes: a larger object is an error. A missing object is an error
	// wrapping ErrNotFound.
	Read(ctx context.Context, id ID, max int) (Type, []byte, error)
}

Store is the object store a thin pack is completed from, and the one the connectivity check asks about objects that are not in the pack.

Invariant the caller guarantees: an object a Store reports present has its whole closure present (a store only ever installs complete packs).

Every method takes the context of the call that asks: an implementation that can block (a disk, a network) must return when ctx ends, with ctx.Err().

type Type

type Type uint8

Type is a git object type.

const (
	Commit Type = 1
	Tree   Type = 2
	Blob   Type = 3
	Tag    Type = 4
)

The four object types, numbered as in the pack format.

func (Type) String

func (t Type) String() string

Jump to

Keyboard shortcuts

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