ocfl

package module
v0.13.0 Latest Latest
Warning

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

Go to latest
Published: Oct 16, 2026 License: MIT Imports: 35 Imported by: 4 modules, 9 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.

README

OCFL for Go

godocs doi

This is an implementation of the Oxford Common File Layout for Go. The module can be used in Go programs to support operations on OCFL storage roots and objects. It supports the local file system or s3 storage backends. Writes to the local backend replace files in one step: content goes to a temporary file that is renamed over the target, so a failed, canceled, or interrupted write leaves the previous file intact and never exposes a truncated one. Several complete example programs are included.

[!WARNING]
The API is under heavy development and will have constant breaking changes.

This module is used in the following projects:

Development

Requires Go >= v1.24.

Documentation

Overview

This module is an implementation of the Oxford Common File Layout (OCFL) specification. The top-level package provides version-independent functionality. The ocflv1 package provides the bulk of implementation.

Example (CustomStage)
package main

import (
	"context"
	"crypto/sha512"
	"encoding/hex"
	"fmt"
	"io/fs"
	"log"
	"os"
	"path"
	"path/filepath"

	"github.com/srerickson/ocfl-go"
	ocflfs "github.com/srerickson/ocfl-go/fs"
	"github.com/srerickson/ocfl-go/fs/local"
)

// uploadDir is a ContentSource for content that has already been uploaded to
// a directory, in files named by their sha512 digests.
type uploadDir struct {
	fsys ocflfs.FS
	dir  string
}

func (u uploadDir) GetContent(dig string) (ocflfs.FS, string) {
	return u.fsys, path.Join(u.dir, dig)
}

// uploadStage is a stage type of our own: it holds an update and the
// uploaded content for it, and files are added by name and digest, as they
// are listed in an upload manifest, without reading them again.
type uploadStage struct {
	update  *ocfl.ObjectUpdate
	content uploadDir
}

func (s *uploadStage) AddUploaded(name, sha512 string) error {
	return s.update.Add(name, sha512, nil)
}

func (s *uploadStage) Commit(ctx context.Context, fsys ocflfs.FS, dir, msg string, user ocfl.User) (*ocfl.Object, error) {
	if err := s.update.Finalize(msg, user); err != nil {
		return nil, err
	}
	return s.update.Apply(ctx, fsys, dir, s.content)
}

func main() {
	ctx := context.Background()
	tmp, err := os.MkdirTemp("", "ocfl-example-*")
	if err != nil {
		log.Fatal(err)
	}
	defer os.RemoveAll(tmp)
	fsys, err := local.NewFS(tmp)
	if err != nil {
		log.Fatal(err)
	}
	// a client uploaded a file and sent its digest
	full := sha512.Sum512([]byte("hello"))
	dig := hex.EncodeToString(full[:])
	if err := os.MkdirAll(filepath.Join(tmp, "uploads"), 0o755); err != nil {
		log.Fatal(err)
	}
	if err := os.WriteFile(filepath.Join(tmp, "uploads", dig), []byte("hello"), 0o644); err != nil {
		log.Fatal(err)
	}

	update, _, err := ocfl.NewObjectUpdate(ctx, fsys, "object", "ark:/example")
	if err != nil {
		log.Fatal(err)
	}
	stage := uploadStage{
		update:  update,
		content: uploadDir{fsys: fsys, dir: "uploads"},
	}
	if err := stage.AddUploaded("greeting.txt", dig); err != nil {
		log.Fatal(err)
	}
	obj, err := stage.Commit(ctx, fsys, "object", "first version", ocfl.User{Name: "Example"})
	if err != nil {
		log.Fatal(err)
	}
	vfs, err := obj.VersionFS(ctx, 0)
	if err != nil {
		log.Fatal(err)
	}
	b, err := fs.ReadFile(vfs, "greeting.txt")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(obj.ID(), obj.Head(), string(b))
}
Output:
ark:/example v1 hello

Index

Examples

Constants

View Source
const (
	NamasteTypeObject = "ocfl_object" // type string for OCFL Object declaration
	NamasteTypeRoot   = "ocfl"        // type string for OCFL Storage Root declaration
)
View Source
const (
	// HasNamaste indicates that an object root directory includes a NAMASTE
	// object declaration file
	HasNamaste objectStateFlag = 1 << iota
	// HasInventory indicates that an object root includes an "inventory.json"
	// file
	HasInventory
	// HasSidecar indicates that an object root includes an "inventory.json.*"
	// file (the inventory sidecar).
	HasSidecar
	// HasExtensions indicates that an object root includes a directory named
	// "extensions"
	HasExtensions
	//HasLogs indicates that an object root includes a directory named "logs"
	HasLogs
)
View Source
const (
	// package version
	Version = "0.13.0"

	Spec1_0 = Spec("1.0")
	Spec1_1 = Spec("1.1")
)

Variables

View Source
var (
	ErrNamasteNotExist = fmt.Errorf("missing NAMASTE declaration: %w", fs.ErrNotExist)
	ErrNamasteContents = errors.New("invalid NAMASTE declaration contents")
	ErrNamasteMultiple = errors.New("multiple NAMASTE declarations found")
)
View Source
var (
	ErrOCFLNotImplemented    = errors.New("unimplemented or missing version of the OCFL specification")
	ErrObjectNamasteExists   = fmt.Errorf("found existing OCFL object declaration: %w", fs.ErrExist)
	ErrObjectNamasteNotExist = fmt.Errorf("the OCFL object declaration does not exist: %w", ErrNamasteNotExist)
	ErrObjRootStructure      = errors.New("object includes invalid files or directories")
)
View Source
var (
	ErrSpecInvalid  = errors.New("invalid OCFL spec version")
	ErrSpecNotFound = errors.New("OCFL spec file not found")
)
View Source
var (
	// ErrFinalized is returned when an [ObjectUpdate] that has been finalized
	// is edited or finalized again.
	ErrFinalized = errors.New("object update is finalized")

	// ErrNotFinalized is returned when an [ObjectUpdate] that hasn't been
	// finalized is applied or reverted.
	ErrNotFinalized = errors.New("object update is not finalized")

	// ErrObjectIncomplete is returned when an update can't be started because
	// the object in storage is half-written, for example because an earlier
	// update was interrupted. The interrupted update can be resumed or
	// reverted with [ObjectUpdate.Apply] or [ObjectUpdate.Revert].
	ErrObjectIncomplete = errors.New("incomplete OCFL object: an update may have been interrupted")

	// ErrUpdateConflict is returned by [ObjectUpdate.Apply] and
	// [ObjectUpdate.Revert] when the object in storage matches neither the
	// update's base inventory nor its new inventory: the object was changed
	// by something else. It is also returned by [NewObjectUpdate] when the
	// object doesn't match [NewUpdateWithExpectedBase].
	ErrUpdateConflict = errors.New("object in storage has changed since the update was started")

	// ErrUpdateCompleted is returned by [ObjectUpdate.Revert] when the update has
	// already been committed to storage.
	ErrUpdateCompleted = errors.New("the update has completed and cannot be reverted")

	// ErrMissingContent is returned when an update can't be applied because
	// the [ContentSource] doesn't provide content for one or more digests
	// that are new in the update.
	ErrMissingContent = errors.New("content source is missing required content")

	// ErrContentChanged is returned by [ObjectUpdate.Apply] when content from
	// its [ContentSource] doesn't match the content's digest: for example,
	// because the file it was staged from has changed.
	ErrContentChanged = errors.New("content doesn't match its digest")

	// ErrUnexpectedHead is returned by [NewObjectUpdate] when the version
	// number of the new object version does not match the number expected by
	// [NewUpdateWithExpectedHead].
	ErrUnexpectedHead = errors.New("unexpected object version number")

	// ErrObjectSpecExceedsRoot is returned when an update would give an object
	// an OCFL specification version that is newer than the specification
	// version of the storage root that contains it (OCFL E081).
	ErrObjectSpecExceedsRoot = errors.New("object's OCFL spec cannot be newer than the storage root's OCFL spec")
)
View Source
var (
	ErrVNumInvalid = errors.New(`invalid version`)
	ErrVNumPadding = errors.New(`inconsistent version padding in version sequence`)
	ErrVNumMissing = errors.New(`missing version in version sequence`)
	ErrVerEmpty    = errors.New("no versions found")
)
View Source
var (
	// ErrInventorySidecarContents indicates the inventory sidecar contents is
	// not formatted correctly.
	ErrInventorySidecarContents = errors.New("invalid contents of inventory sidecar file")
)
View Source
var ErrLayoutUndefined = errors.New("storage root's layout is undefined")
View Source
var ErrMapMakerExists = errors.New("path and digest exist")

ErrMapMakerExists is returned when calling Add with a path and digest that are already present in the MapMaker

View Source
var ErrNoObjectID = errors.New("object does not exist: an explicit ID is required but was not provided")

Functions

func NewObjectUpdate added in v0.13.0

func NewObjectUpdate(ctx context.Context, fsys ocflfs.FS, dir, id string, opts ...NewUpdateOption) (*ObjectUpdate, *Object, error)

NewObjectUpdate returns a new draft *ObjectUpdate for the object at dir in fsys and an *Object for the object. It reads and validates the object's root inventory once: the update's base inventory and the returned Object describe the same inventory. If the object changes in storage after NewObjectUpdate returns, applying the update fails with an error wrapping ErrUpdateConflict. Callers that only need the update can discard the Object.

If the object exists, the update starts from the object's head version state, and the object's ID must match id (if id is not empty). If the object doesn't exist, id is required, the update starts with an empty state and creates version 1, the digest algorithm is sha512 unless NewUpdateWithDigestAlgorithm is used, and the returned Object's Exists method returns false and its ID is id. If the object exists, the update uses the object's digest algorithm, and NewUpdateWithDigestAlgorithm, if used, must match it. NewObjectUpdate returns an error if dir isn't empty and doesn't hold an OCFL object, or if the object is incomplete (an error wrapping ErrObjectIncomplete).

func ParseVNum

func ParseVNum(v string, vn *VNum) error

ParseVNum parses string as an a VNum and sets the value referenced by vn.

func ReadInventorySidecar added in v0.9.0

func ReadInventorySidecar(ctx context.Context, fsys ocflfs.FS, dir, alg string) (string, error)

ReadInventorySidecar reads the digest from an inventory sidecar file in dir, using the digest algorithm alg.

func ValidateInventoryBytes added in v0.7.0

func ValidateInventoryBytes(byts []byte) (*StoredInventory, *Validation)

ValidateInventoryBytes parses and fully validates the byts as contents of an inventory.json file. This is mostly used for testing.

func ValidateNamaste added in v0.1.0

func ValidateNamaste(ctx context.Context, fsys ocflfs.FS, name string) (err error)

ValidateNamaste validates a namaste declaration

func WriteDeclaration

func WriteDeclaration(ctx context.Context, root ocflfs.FS, dir string, d Namaste) error

func WriteSpecFile

func WriteSpecFile(ctx context.Context, fsys ocflfs.WriteFS, dir string, n Spec) (string, error)

Types

type ApplyUpdateOption added in v0.13.0

type ApplyUpdateOption func(*applyUpdateOptions)

ApplyUpdateOption is an optional argument for ObjectUpdate.Apply, ObjectUpdate.Revert, Root.Apply and Root.Revert.

func ApplyWithGoLimit added in v0.13.0

func ApplyWithGoLimit(gos int) ApplyUpdateOption

ApplyWithGoLimit sets the number of goroutines used by ObjectUpdate.Apply and ObjectUpdate.Revert to copy and remove files concurrently. Without it, or if gos is less than 1, runtime.GOMAXPROCS(0) is used.

func ApplyWithLogger added in v0.13.0

func ApplyWithLogger(logger *slog.Logger) ApplyUpdateOption

ApplyWithLogger sets the logger used to log each step of ObjectUpdate.Apply and ObjectUpdate.Revert. Without it, or if logger is nil, nothing is logged.

func ApplyWithTrustedContent added in v0.13.0

func ApplyWithTrustedContent() ApplyUpdateOption

ApplyWithTrustedContent makes ObjectUpdate.Apply copy new content without verifying its digests. Content is copied with ocflfs.Copy, which lets a storage backend copy content within the backend without reading it (for example, from one S3 bucket to another). Use it only when the content source's content can't have changed since it was staged: content that has changed is written into the object under its old digest. It is ignored by ObjectUpdate.Revert, which doesn't copy content.

type ContentSource added in v0.0.23

type ContentSource interface {
	// GetContent returns an FS and path to a file in FS for a file with the given digest.
	// If no content is associated with the digest, fsys is nil and path is an empty string.
	GetContent(digest string) (fsys ocflfs.FS, path string)
}

ContentSource is used to access content with a given digest when creating and updating objects.

type DigestMap

type DigestMap map[string][]string

DigestMap maps digests to file paths.

func (DigestMap) AllPaths added in v0.8.0

func (m DigestMap) AllPaths() []string

AllPaths returns a sorted slice of all path names in the DigestMap.

func (DigestMap) Clone added in v0.0.23

func (m DigestMap) Clone() DigestMap

Clone returns a copy of dm

func (DigestMap) DigestFor added in v0.8.0

func (m DigestMap) DigestFor(p string) string

DigestFor returns the digest for path p or an empty string if the digest is not present.

func (DigestMap) Eq

func (m DigestMap) Eq(other DigestMap) bool

Eq returns true if m and the other have the same content: they have the same (normalized) digests corresponding to the same set of paths. If either map has a digest conflict (same digest appears twice with different case), Eq returns false.

func (DigestMap) Merge

func (m1 DigestMap) Merge(m2 DigestMap, replace bool) (DigestMap, error)

Merge returns a new DigestMap constructed by normalizing and merging m1 and m2. If a paths has different digests in m1 and m2, an error returned unless replace is true, in which case the value from m2 is used.

func (DigestMap) Mutate added in v0.8.0

func (m DigestMap) Mutate(fns ...PathMutation)

Mutate applies each path mutation function to paths for each digest in m. If the mutations remove all paths for the digest, the digest key is deleted from m. Mutate may make m invalid.

func (DigestMap) Normalize

func (m DigestMap) Normalize() (norm DigestMap, err error)

Normalize checks if m is valid and returns a normalized copy (with lowercase digests) and sorted paths.

func (DigestMap) NumPaths added in v0.0.23

func (m DigestMap) NumPaths() int

NumPaths returns the number of paths in m

func (DigestMap) PathMap

func (m DigestMap) PathMap() PathMap

PathMap returns a PathMap with m's paths and corresponding digests. The returned PathMap may be invalid.

func (DigestMap) Paths

func (m DigestMap) Paths() iter.Seq2[string, string]

Paths is an iterator that yields path/digest pairs in m. The order paths are yielded is not defined.

func (DigestMap) Valid

func (m DigestMap) Valid() error

Valid returns a non-nil error if m is invalid.

type FinalizeUpdateOption added in v0.13.0

type FinalizeUpdateOption func(*finalizeUpdateOptions)

FinalizeUpdateOption is an optional argument for ObjectUpdate.Finalize.

func FinalizeWithContentPathFunc added in v0.13.0

func FinalizeWithContentPathFunc(mutate PathMutation) FinalizeUpdateOption

FinalizeWithContentPathFunc sets a function for enforcing naming conventions for content paths in the new inventory. The function is called with the logical paths for each new digest. A nil mutate is ignored.

func FinalizeWithOCFLSpec added in v0.13.0

func FinalizeWithOCFLSpec(s Spec) FinalizeUpdateOption

FinalizeWithOCFLSpec sets the OCFL specification for the new object version. Without it, or if s is empty, an existing object keeps its spec, and a new object uses its storage root's spec (if known) or the latest spec.

func FinalizeWithUnchangedVersionState added in v0.13.0

func FinalizeWithUnchangedVersionState() FinalizeUpdateOption

FinalizeWithUnchangedVersionState allows updates that don't change the version state. Without it, ObjectUpdate.Finalize returns an error if the new version state is the same as the head version's. It has no effect for a new object.

func FinalizeWithVersionCreated added in v0.13.0

func FinalizeWithVersionCreated(t time.Time) FinalizeUpdateOption

FinalizeWithVersionCreated sets the 'created' timestamp for the new version. The timestamp is truncated to the second. Without it, or if t is the zero time, the current time is used.

type Inventory added in v0.7.0

type Inventory struct {
	ID               string                     `json:"id"`
	Type             InventoryType              `json:"type"`
	DigestAlgorithm  string                     `json:"digestAlgorithm"`
	Head             VNum                       `json:"head"`
	ContentDirectory string                     `json:"contentDirectory,omitempty"`
	Manifest         DigestMap                  `json:"manifest"`
	Versions         map[VNum]*InventoryVersion `json:"versions"`
	Fixity           map[string]DigestMap       `json:"fixity,omitempty"`
}

Inventory represents the contents of an object's inventory.json file

func (Inventory) GetFixity added in v0.9.0

func (inv Inventory) GetFixity(dig string) digest.Set

GetFixity provides alternate digests associated with all files with the given primary digest.

func (*Inventory) Validate added in v0.9.0

func (inv *Inventory) Validate() *Validation

Validate validates inv using its declarate OCFL spec.

type InventoryType added in v0.7.0

type InventoryType struct {
	Spec
}

InventoryType represents an inventory type string for example: https://ocfl.io/1.0/spec/#inventory

func (InventoryType) MarshalText added in v0.7.0

func (invT InventoryType) MarshalText() ([]byte, error)

func (InventoryType) String added in v0.7.0

func (inv InventoryType) String() string

func (*InventoryType) UnmarshalText added in v0.7.0

func (invT *InventoryType) UnmarshalText(t []byte) error

type InventoryVersion added in v0.9.0

type InventoryVersion struct {
	Created time.Time `json:"created"`
	State   DigestMap `json:"state"`
	Message string    `json:"message,omitempty"`
	User    *User     `json:"user,omitempty"`
}

Version represents object version state and metadata

type MapDigestConflictErr

type MapDigestConflictErr struct {
	Digest string
}

MapDigestConflictErr indicates same digest found multiple times in the digest map (i.e., with different cases)

func (*MapDigestConflictErr) Error

func (d *MapDigestConflictErr) Error() string

type MapPathConflictErr

type MapPathConflictErr struct {
	Path string
}

MapPathConflictErr indicates a path appears more than once in the digest map. It's also used in cases where the path as used as a directory in one instance and a file in another.

func (*MapPathConflictErr) Error

func (p *MapPathConflictErr) Error() string

type MapPathInvalidErr

type MapPathInvalidErr struct {
	Path string
}

MapPathInvalidErr indicates an invalid path in a Map.

func (*MapPathInvalidErr) Error

func (p *MapPathInvalidErr) Error() string

type Namaste added in v0.0.24

type Namaste struct {
	Type    string
	Version Spec
}

Namaste represents a NAMASTE declaration

func FindNamaste added in v0.0.24

func FindNamaste(items []fs.DirEntry) (Namaste, error)

FindNamaste returns the NAMASTE declaration from a fs.DirEntry slice. An error is returned if the number of declarations is not one.

func ParseNamaste added in v0.0.24

func ParseNamaste(name string) (n Namaste, err error)

func (Namaste) Body added in v0.0.24

func (n Namaste) Body() string

Body returns the expected file contents of the namaste declaration

func (Namaste) IsObject added in v0.5.0

func (n Namaste) IsObject() bool

IsObject returs true if n's type is 'ocfl_object'

func (Namaste) IsRoot added in v0.8.0

func (n Namaste) IsRoot() bool

IsRoot returns true if n's type is 'ocfl'

func (Namaste) Name added in v0.0.24

func (n Namaste) Name() string

Name returns the filename for n ('0=TYPE_VERSION') or an empty string if n is empty

type NewUpdateOption added in v0.13.0

type NewUpdateOption func(*newUpdateOptions)

NewUpdateOption is an optional argument for NewObjectUpdate and Root.NewObjectUpdate.

func NewUpdateMustExist added in v0.13.0

func NewUpdateMustExist() NewUpdateOption

NewUpdateMustExist makes NewObjectUpdate return an error wrapping [fs.ErrNotExist] if the object doesn't exist, instead of starting an update that creates it.

func NewUpdateWithDigestAlgorithm added in v0.13.0

func NewUpdateWithDigestAlgorithm(alg digest.Algorithm) NewUpdateOption

NewUpdateWithDigestAlgorithm sets the primary digest algorithm (sha512 or sha256) for a new object. Without it, a new object uses sha512. If the object exists, alg must be the object's digest algorithm, or NewObjectUpdate returns an error: changing an existing object's digest algorithm isn't supported. A nil alg is ignored.

func NewUpdateWithExpectedBase added in v0.13.0

func NewUpdateWithExpectedBase(inventoryDigest string) NewUpdateOption

NewUpdateWithExpectedBase sets the expected digest of the object's root inventory. NewObjectUpdate returns an error wrapping ErrUpdateConflict if the inventory it reads has a different digest. An empty digest means the object must not exist. Use it to start an update for an object that was read earlier, such as with NewObject:

u, _, err := ocfl.NewObjectUpdate(ctx, obj.FS(), obj.Path(), obj.ID(),
	ocfl.NewUpdateWithExpectedBase(obj.InventoryDigest()))

Without it, the update's base is the inventory that NewObjectUpdate reads, so changes committed after the object was read would go undetected.

func NewUpdateWithExpectedHead added in v0.13.0

func NewUpdateWithExpectedHead(v int) NewUpdateOption

NewUpdateWithExpectedHead sets the expected version number (without padding) of the version the update creates. NewObjectUpdate returns an error wrapping ErrUnexpectedHead if the update would create a version with a different number. For a new object, the expected version number is 1. It is the version-number counterpart of NewUpdateWithExpectedBase, for callers that know the object's head but not its inventory digest. Values of v less than 1 are ignored.

type Object added in v0.1.0

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

Object is a read-only view of an OCFL Object, typically part of a Root, as described by one inventory. An Object never changes: to create a new version, create an ObjectUpdate with NewObjectUpdate or Root.NewObjectUpdate and apply it with ObjectUpdate.Apply, which returns a new *Object. The previous *Object remains a valid but out-of-date view.

func NewObject added in v0.1.0

func NewObject(ctx context.Context, fsys ocflfs.FS, dir string, opts ...ObjectOption) (*Object, error)

NewObject returns an *Object for reading the OCFL object at directory dir in fsys. The object doesn't need to exist when NewObject is called if its ID is given with ObjectWithID. To create or update the object, use NewObjectUpdate with NewUpdateWithExpectedBase, or use NewObjectUpdate instead of NewObject: it returns an Object along with the update.

func (Object) ContentDirectory added in v0.9.0

func (obj Object) ContentDirectory() string

ContentDirectory return "content" or the value set in the root inventory.

func (Object) DigestAlgorithm added in v0.9.0

func (obj Object) DigestAlgorithm() digest.Algorithm

DigestAlgorithm returns sha512 unless sha256 is set in the root inventory.

func (Object) Exists added in v0.1.0

func (obj Object) Exists() bool

Exists returns true if the object has an existing version.

func (Object) ExtensionNames added in v0.1.0

func (obj Object) ExtensionNames(ctx context.Context) ([]string, error)

ExtensionNames returns the names of directories in the object's extensions directory.

func (Object) FS added in v0.1.0

func (obj Object) FS() ocflfs.FS

FS returns the FS where object is stored.

func (Object) FixityAlgorithms added in v0.9.0

func (obj Object) FixityAlgorithms() []string

FixityAlgorithms returns a slice of the keys from the `fixity` block of obj's return inventory. If obj does not have an inventory (i.e., because one has not been created yet), it returns nil.

func (Object) Head added in v0.9.0

func (obj Object) Head() VNum

Head returns the most recent version number. If obj has no root inventory, it returns the zero value.

func (Object) ID added in v0.7.1

func (obj Object) ID() string

ID returns obj's inventory ID if the obj exists (its inventory is not nil). If obj does not exist but was constructed with Root.NewObject or with the ObjectWithID option, the ID given as an argument is returned. Otherwise, it returns an empty string.

func (Object) InventoryDigest added in v0.9.0

func (obj Object) InventoryDigest() string

InventoryDigest returns the digest of the object's root inventory using the declarate digest algorithm. It is the expected content of the root inventory's sidecar file.

func (Object) Manifest added in v0.9.0

func (obj Object) Manifest() DigestMap

Manifest returns a copy of the root inventory manifest. If the object has no root inventory (e.g., it doesn't yet exist), nil is returned.

func (Object) Path added in v0.1.0

func (obj Object) Path() string

Path returns the Object's path relative to its FS.

func (Object) Root added in v0.7.0

func (o Object) Root() *Root

Root returns the object's Root, if known. It is nil unless the *Object was created using Root.NewObject

func (Object) Spec added in v0.9.0

func (o Object) Spec() Spec

Spec returns the OCFL spec number from the object's root inventory, or an empty Spec if the root inventory does not exist.

func (Object) Version added in v0.9.0

func (obj Object) Version(v int) *ObjectVersion

Version returns an *ObjectVersion that can be used to access details for the version with the given number (1...HEAD) from the root inventory. For example, v == 1 refers to "v1" or "v001" version block. If v < 1, the most recent version is returned. If the version does not exist, nil is returned.

func (*Object) VersionFS added in v0.9.0

func (obj *Object) VersionFS(ctx context.Context, v int) (fs.FS, error)

VersionFS returns an io/fs.FS representing the logical state for the version with the given number (1...HEAD). If v < 1, the most recent version is used.

type ObjectOption added in v0.1.0

type ObjectOption func(*newObjectConfig)

ObjectOptions are used to configure the behavior of NewObject()

func ObjectMustExist added in v0.5.0

func ObjectMustExist() ObjectOption

ObjectMustExists is an ObjectOption used to indicate that the initialized object instance must be an existing OCFL object.

func ObjectSkipRootSidecarValidation added in v0.9.1

func ObjectSkipRootSidecarValidation() ObjectOption

ObjectSkipRootSidecarValidation is used to skip validating the inventory.json digest with the root inventory sidecar file during initialization.

func ObjectWithID added in v0.9.0

func ObjectWithID(id string) ObjectOption

ObjectWithID is an ObjectOption used to set an explict object ID in contexts where the object ID is not known or must match a certain value.

func ObjectWithInventory added in v0.9.1

func ObjectWithInventory(inv *StoredInventory) ObjectOption

ObjectWithInventory is used to initialize an *Object using an existing *StoredInventory value. It can be used with an inventory cache to minimize requests to the object's storage backed. Unless it is combined with the ObjectSkipRootSidecarValidation option, inv's digest will be validated against the root inventory sidecar file.

type ObjectState

type ObjectState struct {
	Spec        Spec            // the OCFL spec from the object's NAMASTE declaration file
	VersionDirs VNums           // version directories found in the object directory
	SidecarAlg  string          // digest algorithm used by the inventory sidecar file
	Invalid     []string        // non-conforming directory entries in the object root (max of 8)
	Flags       objectStateFlag // boolean attributes of the object root
}

ObjectState provides details of an OCFL object root based on the names of files and directories in the object's root. ParseObjectDir is typically used to create a new ObjectState from a slice of fs.DirEntry values.

func ParseObjectDir added in v0.1.0

func ParseObjectDir(entries []fs.DirEntry) *ObjectState

ParseObjectDir returns a new ObjectState based on contents of an object root directory.

func (ObjectState) Empty added in v0.1.0

func (state ObjectState) Empty() bool

Empty returns true if the object root directory is empty

func (ObjectState) HasExtensions added in v0.1.0

func (state ObjectState) HasExtensions() bool

HasExtensions returns true if state's HasExtensions flag is set

func (ObjectState) HasInventory added in v0.1.0

func (state ObjectState) HasInventory() bool

HasInventory returns true if state's HasInventory flag is set

func (ObjectState) HasLogs added in v0.3.1

func (state ObjectState) HasLogs() bool

HasLogs returns true if state's HasLogs flag is set

func (ObjectState) HasNamaste added in v0.1.0

func (state ObjectState) HasNamaste() bool

HasNamaste returns true if state's HasNamaste flag is set

func (ObjectState) HasSidecar added in v0.1.0

func (state ObjectState) HasSidecar() bool

HasSidecar returns true if state's HasSidecar flag is set

func (ObjectState) HasVersionDir added in v0.1.0

func (state ObjectState) HasVersionDir(v VNum) bool

HasVersionDir returns true if the state's VersionDirs includes v

func (ObjectState) Namaste added in v0.6.0

func (state ObjectState) Namaste() Namaste

Namaste returns state's Namaste value, which may be a zero value.

type ObjectUpdate added in v0.13.0

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

ObjectUpdate is a pending version of an OCFL object. It is created with NewObjectUpdate or Root.NewObjectUpdate, or restored from JSON. It has two phases. As a draft, it holds the new version state and fixity for new content, which are changed with ObjectUpdate.Add, ObjectUpdate.Remove, ObjectUpdate.Rename, and ObjectUpdate.Clear. ObjectUpdate.Finalize settles the version metadata and builds the new inventory, after which the update is read-only and can be applied to storage with ObjectUpdate.Apply or, if interrupted, resumed with Apply or undone with ObjectUpdate.Revert.

An ObjectUpdate is serializable as JSON in both phases. The saved form includes the object's inventory at the time the update was started (the base inventory), so nothing needs to be read from storage to finalize it. A finalized update should be saved before it is applied: if the process is interrupted, the saved update is all that is needed to resume or revert. Content for new digests is not part of the ObjectUpdate: it is provided by the ContentSource passed to Apply. ObjectUpdate.NewContentDigests lists the digests of the content the update needs, and ObjectUpdate.NeedsContent reports whether it needs content with a given digest. A content source may hold content the update doesn't need: Apply only asks it for the digests the update needs.

This package doesn't synchronize updates: only one update may be applied to or reverted from an object at a time (see ObjectUpdate.Apply).

The stage package digests files, adds them to an update, and records the content it needs, in files or in memory: its stage.FileContentMap can be saved as JSON. ObjectUpdate.AddAll adds files whose digests are already known. To save an update with its content, or to keep them together, define a type of your own that holds both.

func (*ObjectUpdate) Add added in v0.13.0

func (u *ObjectUpdate) Add(name, dig string, fixity digest.Set) error

Add sets the digest for the file name in the new version state, replacing any existing digest for name. The digest must use the update's digest algorithm. Fixity values for the content are saved unless the content is already in the object. fixity may include a value for the update's digest algorithm, which isn't saved and must be dig. Add returns an error if name is invalid or conflicts with an existing path (a file can't also be a directory), and ErrFinalized if u has been finalized.

func (*ObjectUpdate) AddAll added in v0.13.0

func (u *ObjectUpdate) AddAll(entries []UpdateEntry) error

AddAll adds each entry to the new version state, as with ObjectUpdate.Add. Either all entries are added, or none of them are and AddAll returns an error. Entries are added in order, so if two entries have the same name, the last one is kept.

func (*ObjectUpdate) Apply added in v0.13.0

func (u *ObjectUpdate) Apply(ctx context.Context, fsys ocflfs.FS, dir string, src ContentSource, opts ...ApplyUpdateOption) (*Object, error)

Apply writes the finalized update to the object at dir in fsys, using src for new content, and returns the updated object. If an earlier Apply was interrupted, Apply resumes it.

What Apply does depends on the object's root inventory sidecar in storage. If it holds the update's base inventory digest, the update has not been committed: every step is run again, overwriting anything written by an earlier attempt. If it holds the new inventory digest, the update was committed and there is nothing to do. Any other value means the object was changed by something else, and Apply returns an error wrapping ErrUpdateConflict without writing anything. For a new object, which has no sidecar until the update is committed, dir must also be missing or empty, or hold only files and directories that the update writes (an error wrapping ErrUpdateConflict otherwise).

Concurrent applies to the same object are not safe. Apply doesn't lock the object, and it checks the sidecar only before writing: if two updates with the same base are applied at the same time, both may succeed, leaving an object with only the last update's version and with content from both in its version directory. Callers must make sure that only one update is applied to (or reverted from) an object at a time.

Apply returns an error wrapping ErrMissingContent, without writing anything, if src doesn't provide content for every digest that is new in the update. src may be nil if the update doesn't add new content. A stage.FileContentMap loaded from JSON must be opened with stage.FileContentMap.OpenFS first.

By default, Apply digests new content as it copies it into the object, and returns an error wrapping ErrContentChanged if any content doesn't match its digest: for example, because the file it was staged from changed after it was staged. The mismatched file is removed, and the update can be applied again once the content is restored, or reverted. Content is verified on every attempt, including when an interrupted update is resumed. Use ApplyWithTrustedContent to skip verification and let storage backends copy content without reading it.

func (*ObjectUpdate) BaseInventoryDigest added in v0.13.0

func (u *ObjectUpdate) BaseInventoryDigest() string

BaseInventoryDigest returns the digest of the object's inventory.json at the time the update was started. It is empty if the update creates a new object.

func (*ObjectUpdate) BaseState added in v0.13.0

func (u *ObjectUpdate) BaseState() DigestMap

BaseState returns a copy of the object's head version state at the time the update was started. It is empty if the update creates a new object. Its digests use the update's digest algorithm, so it can be compared with ObjectUpdate.NewState without reading the object.

func (*ObjectUpdate) Clear added in v0.13.0

func (u *ObjectUpdate) Clear() error

Clear removes all files from the new version state. It returns ErrFinalized if u has been finalized.

func (*ObjectUpdate) DigestAlgorithm added in v0.13.0

func (u *ObjectUpdate) DigestAlgorithm() digest.Algorithm

DigestAlgorithm returns the primary digest algorithm for the new version.

func (*ObjectUpdate) Finalize added in v0.13.0

func (u *ObjectUpdate) Finalize(msg string, user User, opts ...FinalizeUpdateOption) error

Finalize settles the new version's metadata (the message, user, created timestamp and OCFL spec) and the content paths for new content, builds the new inventory, and makes u read-only. It does no I/O. If Finalize returns an error, u is unchanged.

func (*ObjectUpdate) Finalized added in v0.13.0

func (u *ObjectUpdate) Finalized() bool

Finalized returns true if u has been finalized.

func (*ObjectUpdate) Fixity added in v0.13.0

func (u *ObjectUpdate) Fixity(dig string) digest.Set

Fixity returns a copy of the fixity values for new content with the given digest. It returns nil for content that is already in the object.

func (*ObjectUpdate) ID added in v0.13.0

func (u *ObjectUpdate) ID() string

ID returns the ID of the object being updated.

func (ObjectUpdate) MarshalJSON added in v0.13.0

func (u ObjectUpdate) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler for ObjectUpdate.

func (*ObjectUpdate) NeedsContent added in v0.13.0

func (u *ObjectUpdate) NeedsContent(dig string) bool

NeedsContent returns true if content with the digest dig is in the new version state but not in the object, so that it must be provided by the ContentSource used to apply u.

func (*ObjectUpdate) NewContentDigests added in v0.13.0

func (u *ObjectUpdate) NewContentDigests() []string

NewContentDigests returns the sorted digests of all content that is in the new version state but not in the object: the content that must be provided by the ContentSource used to apply u.

func (*ObjectUpdate) NewInventoryDigest added in v0.13.0

func (u *ObjectUpdate) NewInventoryDigest() string

NewInventoryDigest returns the digest of the new inventory.json, or an empty string if u has not been finalized.

func (*ObjectUpdate) NewState added in v0.13.0

func (u *ObjectUpdate) NewState() DigestMap

NewState returns a copy of the new version's state. See ObjectUpdate.BaseState for the state of the version the update is based on.

func (*ObjectUpdate) NextHead added in v0.13.0

func (u *ObjectUpdate) NextHead() VNum

NextHead returns the version number of the new version.

func (*ObjectUpdate) Remove added in v0.13.0

func (u *ObjectUpdate) Remove(name string) error

Remove removes the file or directory name from the new version state. It returns an error wrapping [fs.ErrNotExist] if name isn't a file or directory in the state and ErrFinalized if u has been finalized.

func (*ObjectUpdate) Rename added in v0.13.0

func (u *ObjectUpdate) Rename(src, dst string) error

Rename renames the file or directory src in the new version state to dst. If src is ".", all files are moved into the directory dst. Rename returns an error wrapping [fs.ErrNotExist] if src doesn't exist, an error if the result has conflicting paths, and ErrFinalized if u has been finalized.

func (*ObjectUpdate) Revert added in v0.13.0

func (u *ObjectUpdate) Revert(ctx context.Context, fsys ocflfs.FS, dir string, opts ...ApplyUpdateOption) error

Revert removes everything written to the object at dir in fsys by an interrupted ObjectUpdate.Apply, restoring the object's base inventory (or, for a new object, removing the object directory). On success, u returns to being a draft, so it can be edited and finalized again.

Like Apply, Revert decides what to do from the object's root inventory sidecar. It returns ErrUpdateCompleted if the update was committed, and an error wrapping ErrUpdateConflict if the object was changed by something else. For a new object, Revert removes dir only if everything in it could have been written by the update, as described for Apply. As with Apply, Revert must not run at the same time as another update to the object. Revert ignores ApplyWithTrustedContent.

func (*ObjectUpdate) UnmarshalJSON added in v0.13.0

func (u *ObjectUpdate) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler for *ObjectUpdate. For a finalized update, the new inventory is rebuilt from the saved values and its digest is compared with the saved digest: if they don't match, the saved update was changed (or was saved by a version of this package that builds inventories differently) and an error is returned.

func (*ObjectUpdate) VersionInfo added in v0.13.0

func (u *ObjectUpdate) VersionInfo() (VersionInfo, bool)

VersionInfo returns the new version's metadata and true if u has been finalized, or the zero value and false if u is a draft.

type ObjectValidation added in v0.1.0

type ObjectValidation struct {
	Validation
	// contains filtered or unexported fields
}

ObjectValidation is used to configure and track results from an object validation process.

func ValidateObject added in v0.3.0

func ValidateObject(ctx context.Context, fsys ocflfs.FS, dir string, opts ...ObjectValidationOption) *ObjectValidation

ValidateObject fully validates the OCFL Object at dir in fsys

func (*ObjectValidation) Add added in v0.1.0

func (v *ObjectValidation) Add(v2 *Validation)

Add adds and logs all fatal errors and warning from the validation

func (*ObjectValidation) AddFatal added in v0.1.0

func (v *ObjectValidation) AddFatal(errs ...error)

AddFatal adds fatal errors to the validation

func (*ObjectValidation) AddWarn added in v0.1.0

func (v *ObjectValidation) AddWarn(errs ...error)

AddWarn adds warning errors to the object validation and logs the errors using the object validations logger, if set.

func (*ObjectValidation) DigestConcurrency added in v0.4.0

func (v *ObjectValidation) DigestConcurrency() int

DigestConcurrency returns the configured number of go routines used to read and digest contents during validation. The default value is runtime.GOMAXPROCS(0).

func (*ObjectValidation) Logger added in v0.1.0

func (v *ObjectValidation) Logger() *slog.Logger

Logger returns the validation's logger, which is nil by default.

func (*ObjectValidation) PrefixAdd added in v0.1.0

func (v *ObjectValidation) PrefixAdd(prefix string, v2 *Validation)

PrefixAdd adds and logs all fatal errors and warning from the validation, prepending each error with the prefix.

func (*ObjectValidation) SkipDigests added in v0.1.0

func (v *ObjectValidation) SkipDigests() bool

SkipDigests returns true if the validation is configured to skip digest checks. It is false by default.

func (*ObjectValidation) ValidationAlgorithms added in v0.4.0

func (v *ObjectValidation) ValidationAlgorithms() digest.AlgorithmRegistry

ValidationAlgorithms returns the registry of digest algorithms the object validation is configured to use. The default value is digest.DefaultRegistry

type ObjectValidationOption added in v0.1.0

type ObjectValidationOption func(*ObjectValidation)

func ValidationAlgorithms added in v0.4.0

func ValidationAlgorithms(reg digest.AlgorithmRegistry) ObjectValidationOption

ValidationAlgorithms sets registry of available digest algorithms for fixity validation.

func ValidationDigestConcurrency added in v0.4.0

func ValidationDigestConcurrency(num int) ObjectValidationOption

ValidationDigestConcurrency is used to set the number of go routines used to read and digest contents during validation. Without it, or if num is less than 1, runtime.GOMAXPROCS(0) is used.

func ValidationLogger added in v0.1.0

func ValidationLogger(logger *slog.Logger) ObjectValidationOption

ValidationLogger sets the *slog.Logger that should be used for logging validation errors and warnings.

func ValidationSkipDigest added in v0.1.0

func ValidationSkipDigest() ObjectValidationOption

type ObjectVersion added in v0.1.0

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

ObjectVersion is used to access version information from an object's root inventory.

func (ObjectVersion) Created added in v0.1.0

func (o ObjectVersion) Created() time.Time

Created returns the version's created timestamp

func (ObjectVersion) Message added in v0.1.0

func (o ObjectVersion) Message() string

Message returns the version's message

func (ObjectVersion) State added in v0.1.0

func (o ObjectVersion) State() DigestMap

State returns a copy of the version's state

func (ObjectVersion) User added in v0.1.0

func (o ObjectVersion) User() *User

User returns the version's user information, which may be nil

func (ObjectVersion) VNum added in v0.9.0

func (o ObjectVersion) VNum() VNum

VNum returns o's version number

type PathMap added in v0.0.23

type PathMap map[string]string

PathMap maps filenames to digest strings.

func (PathMap) DigestMap added in v0.0.23

func (pm PathMap) DigestMap() DigestMap

DigestMap returns a new DigestMap using the pathnames and digests in pm. The resulting DigestMap may be invalid if pm includes invalid paths or digests.

func (PathMap) SortedPaths added in v0.8.0

func (pm PathMap) SortedPaths() iter.Seq2[string, string]

SortedPaths is an iterator that yields the path/digest pairs in pm in sorted order (by pathname).

type PathMutation added in v0.8.0

type PathMutation func(oldPaths []string) (newPaths []string)

PathMutation is used with DigestMap.Mutate to change paths names in a DigestMap

func RemovePath added in v0.8.0

func RemovePath(name string) PathMutation

RemovePath returns a PathMutation that removes name

func RenamePaths added in v0.8.0

func RenamePaths(src, dst string) PathMutation

RenamePaths returns a PathMutation function that renames occurences of src to dst. If src matches a full path, it is replaced with dst. If src matches a directory (including '.'), all occurences of the directory prefix are replaced with dst (which may be '.').

type Root added in v0.1.0

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

Root represents an OCFL Storage Root.

func NewRoot added in v0.1.0

func NewRoot(ctx context.Context, fsys ocflfs.FS, dir string, opts ...RootOption) (*Root, error)

NewRoot returns a new *Root for working with the OCFL storage root at directory dir in fsys. It can be used to initialize new storage roots if the InitRoot option is used, fsys is an ocfl.WriteFS, and dir is a non-existing or empty directory.

func (*Root) Apply added in v0.13.0

func (r *Root) Apply(ctx context.Context, u *ObjectUpdate, src ContentSource, opts ...ApplyUpdateOption) (*Object, error)

Apply applies the finalized update u to the object in the root with u's ID, using src for new content, and returns the updated object. See ObjectUpdate.Apply. Apply returns an error wrapping ErrObjectSpecExceedsRoot, without writing anything, if u's new version has a newer OCFL spec than the root's (E081). This can happen if u wasn't created with Root.NewObjectUpdate.

func (*Root) Description added in v0.1.0

func (r *Root) Description() string

Description returns the description string from the storage roots `ocfl_layout.json` file, which may be empty.

func (*Root) FS added in v0.1.0

func (r *Root) FS() ocflfs.FS

FS returns the Root's FS

func (*Root) Layout added in v0.1.0

func (r *Root) Layout() extension.Layout

Layout returns the storage root's layout, which may be nil.

func (*Root) LayoutName added in v0.1.0

func (r *Root) LayoutName() string

LayoutName returns the name of the root's layout extension or an empty string if the root has no layout.

func (*Root) NewObject added in v0.1.0

func (r *Root) NewObject(ctx context.Context, id string, opts ...ObjectOption) (*Object, error)

NewObject returns an *Object for managing the OCFL object with the given ID in the root. If the object does not exist, the returned *Object can be used to create it. If the Root has not storage layout for resovling object IDs, the returned error is ErrLayoutUndefined.

func (*Root) NewObjectDir added in v0.3.0

func (r *Root) NewObjectDir(ctx context.Context, dir string, opts ...ObjectOption) (*Object, error)

NewObjectDir returns an *Object for managing the OCFL object at path dir in root. If the object does not exist, the returned *Object can be used to create it.

func (*Root) NewObjectUpdate added in v0.13.0

func (r *Root) NewObjectUpdate(ctx context.Context, id string, opts ...NewUpdateOption) (*ObjectUpdate, *Object, error)

NewObjectUpdate returns a new draft *ObjectUpdate for the object with the given ID in the root and an *Object for the object, as with NewObjectUpdate. The root's OCFL spec is recorded in the update, so the update can't give the object a newer spec than the root's (E081). A new object uses the root's spec unless FinalizeWithOCFLSpec is used. The object's Root method returns r. If the Root has no storage layout for resolving object IDs, the returned error is ErrLayoutUndefined.

func (*Root) ObjectDeclarations added in v0.6.0

func (r *Root) ObjectDeclarations(ctx context.Context) iter.Seq2[*ocflfs.FileRef, error]

ObjectDeclarations returns an iterator that yields all OCFL object declaration files in r. If an error occurs during iteration, it is returned by the error function.

func (*Root) Objects added in v0.1.0

func (r *Root) Objects(ctx context.Context, opts ...ObjectOption) iter.Seq2[*Object, error]

Objects returns an iterator that yields objects or an error for every object declaration file in the root. Objects are yielded in arbitrary order.

func (*Root) ObjectsBatch added in v0.6.0

func (r *Root) ObjectsBatch(ctx context.Context, numgos int, opts ...ObjectOption) iter.Seq2[*Object, error]

ObjectsBatch returns an iterator that yields objects or an error for every object declaration file in the root. Objects are read in numgos go routines and are yielded in arbitrary order.

func (*Root) Path added in v0.1.0

func (r *Root) Path() string

Path returns the root's dir relative to its FS

func (*Root) ResolveID added in v0.3.0

func (r *Root) ResolveID(id string) (string, error)

ResolveID resolves the object id to a path relative to the root. If the root has no layout, the returned error is ErrLayoutUndefined.

func (*Root) Revert added in v0.13.0

func (r *Root) Revert(ctx context.Context, u *ObjectUpdate, opts ...ApplyUpdateOption) error

Revert reverts the interrupted update u to the object in the root with u's ID. See ObjectUpdate.Revert.

func (*Root) Spec added in v0.1.0

func (r *Root) Spec() Spec

Spec returns the root's OCFL specification number

func (*Root) ValidateObject added in v0.3.0

func (r *Root) ValidateObject(ctx context.Context, id string, opts ...ObjectValidationOption) *ObjectValidation

ValidateObject validates the object with the given id. If the id cannot be resolved, the error is reported as a fatal error in the returned *ObjectValidation.

func (*Root) ValidateObjectDir added in v0.3.0

func (r *Root) ValidateObjectDir(ctx context.Context, dir string, opts ...ObjectValidationOption) *ObjectValidation

ValidateObjectDir validates the object at a path relative to the root.

type RootOption added in v0.1.0

type RootOption func(*Root)

RootOption is used to configure the behavior of NewRoot()

func InitRoot added in v0.1.0

func InitRoot(spec Spec, layoutDesc string, extensions ...extension.Extension) RootOption

InitRoot returns a RootOption for initializing a new storage root as part of the call to NewRoot().

type Spec

type Spec string

Spec represent an OCFL specification number

func (Spec) Cmp

func (v1 Spec) Cmp(v2 Spec) int

Cmp compares Spec v1 to another v2. - If v1 is less than v2, returns -1. - If v1 is the same as v2, returns 0 - If v1 is greater than v2, returns 1 - any valid spec is greater than an invalid spec. - if both specs are invlid, Cmp panics.

func (Spec) Empty

func (s Spec) Empty() bool

func (Spec) InventoryType added in v0.7.0

func (s Spec) InventoryType() InventoryType

InventoryType returns n as an InventoryType

func (Spec) Valid added in v0.0.24

func (s Spec) Valid() error

type StoredInventory added in v0.9.0

type StoredInventory struct {
	Inventory
	// contains filtered or unexported fields
}

StoredInventory is an unmarshaled inventory with the digest of its source data.

func NewStoredInventory added in v0.9.1

func NewStoredInventory(r io.Reader) (*StoredInventory, error)

NewStoredInventory reads all bytes from r and parses the contents as as Inventory. The returned *StoredInventory is valid and includes the a digest of the bytes read from r.

func ReadInventory added in v0.1.0

func ReadInventory(ctx context.Context, fsys ocflfs.FS, dir string) (*StoredInventory, error)

ReadInventory reads the inventory.json file in dir and validates it. It returns an error if the inventory can't be parsed or if it is invalid.

func (StoredInventory) Digest added in v0.9.0

func (inv StoredInventory) Digest() string

Digest returns the digest of inventory.json file used to create inv using the digest algorithm specified in the inventory.

func (StoredInventory) MarshalBinary added in v0.9.1

func (inv StoredInventory) MarshalBinary() ([]byte, error)

MarshalBinary implements encoding.BinaryMarshaler for StoredInventory. It returns the full contents of the inventory.json file used to create inv.

func (*StoredInventory) UnmarshalBinary added in v0.9.1

func (inv *StoredInventory) UnmarshalBinary(data []byte) error

UnmarshalBinary implements encoding.BinaryUnmarshaler for *StoredInventory. The data argument must be the full contents of an inventory.json, otherwise inv's Digest value may not match its sidecar. (BinaryUnmarshaler is used instead of json.Unmarshaler because the latter may not preserve the exact bytestream, for example leading or trailing whitespace.)

func (StoredInventory) ValidateSidecar added in v0.9.0

func (inv StoredInventory) ValidateSidecar(ctx context.Context, fsys ocflfs.FS, dir string) error

ValidateSidecar reads the inventory sidecar with inv's digest algorithm (e.g., inventory.json.sha512) in directory dir and return an error if the sidecar content is not formatted correctly or if the inv's digest doesn't match the value found in the sidecar.

type UpdateEntry added in v0.13.0

type UpdateEntry struct {
	Name   string     // path in the new version state
	Digest string     // digest of the content, using the update's algorithm
	Fixity digest.Set // optional fixity values for the content
}

UpdateEntry is a file to add to an update's new version state with ObjectUpdate.AddAll.

type User

type User struct {
	Name    string `json:"name"`
	Address string `json:"address,omitempty"`
}

User is a generic user information struct

type VNum

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

VNum represents an OCFL object version number (e.g., "v1", "v02"). A VNum has a sequence number (1,2,3...) and a padding number, which defaults to zero. The padding is the maximum number of numeric digits the version number can include (a padding of 0 is no maximum). The padding value constrains the maximum valid sequence number.

func MustParseVNum

func MustParseVNum(str string) VNum

MustParseVNum parses str as a VNUm and returns a new VNum. It panics if str cannot be parsed as a VNum.

func V

func V(ns ...int) VNum

V returns a new Vnum. The first argument is a sequence number. An optional second argument can be used to set the padding. Additional arguments are ignored. Without any arguments, V() returns a zero value VNum.

func (VNum) First

func (v VNum) First() bool

First returns true if v is a version 1.

func (VNum) IsZero

func (v VNum) IsZero() bool

IsZero returns if v is the zero value

func (VNum) Lineage added in v0.1.0

func (v VNum) Lineage() VNums

Lineage returns a VNums with v as the head.

func (VNum) MarshalText

func (v VNum) MarshalText() ([]byte, error)

func (VNum) Next

func (v VNum) Next() (VNum, error)

Next returns the next ocfl.VNum after v with the same padding. A non-nil error is returned if padding > 0 and next would overflow the padding

func (VNum) Num

func (v VNum) Num() int

Num returns v's number as an int

func (VNum) Padding

func (v VNum) Padding() int

Padding returns v's padding number.

func (VNum) String

func (v VNum) String() string

String returns string representation of v

func (*VNum) UnmarshalText

func (v *VNum) UnmarshalText(text []byte) error

func (VNum) Valid

func (v VNum) Valid() error

Valid returns an error if v is invalid

type VNums

type VNums []VNum

VNums is a slice of VNum elements

func (VNums) Head

func (vs VNums) Head() VNum

Head returns the last VNum in vs.

func (VNums) Len

func (vs VNums) Len() int

Len implements sort.Interface on VNums

func (VNums) Less

func (vs VNums) Less(i, j int) bool

Less implements sort.Interface on VNums

func (VNums) Padding

func (vs VNums) Padding() int

Padding returns the padding for the VNums in vs

func (VNums) Swap

func (vs VNums) Swap(i, j int)

Swap implements sort.Interface on VNums

func (VNums) Valid

func (vs VNums) Valid() error

Valid returns a non-nill error if VNums is empty, is not a continuous sequence (1,2,3...), has inconsistent padding or padding overflow.

type Validation added in v0.1.0

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

Validation represents multiple fatal errors and warning errors.

func (*Validation) Add added in v0.1.0

func (v *Validation) Add(v2 *Validation)

Add adds all fatal errors and warnings from another validation to v.

func (*Validation) AddFatal added in v0.1.0

func (v *Validation) AddFatal(errs ...error)

AddFatal adds fatal errors to the validation

func (*Validation) AddWarn added in v0.1.0

func (v *Validation) AddWarn(errs ...error)

AddWarn adds warning errors to the validation

func (*Validation) Err added in v0.1.0

func (v *Validation) Err() error

Err returns an error wrapping all the validation's fatal errors, or nil if there are no fatal errors.

func (*Validation) Errors added in v0.1.0

func (v *Validation) Errors() []error

Errors returns a slice of all the fatal errors.

func (*Validation) WarnErr added in v0.1.0

func (v *Validation) WarnErr() error

WarnErr returns an error wrapping all the validation's warning errors, or nil if there are none.

func (*Validation) WarnErrors added in v0.1.0

func (v *Validation) WarnErrors() []error

WarnErrors returns a slice of all the warning errors.

type ValidationError added in v0.1.0

type ValidationError struct {
	validation.ValidationCode
	Err error
}

ValidationError is an error that includes a reference to a validation error code from the OCFL spec.

func (*ValidationError) Error added in v0.1.0

func (ver *ValidationError) Error() string

func (*ValidationError) Unwrap added in v0.1.0

func (ver *ValidationError) Unwrap() error

type VersionInfo added in v0.13.0

type VersionInfo struct {
	Message string
	User    User
	// Created is truncated to the second, as it is written to the inventory.
	Created time.Time
	Spec    Spec
}

VersionInfo is the metadata settled by ObjectUpdate.Finalize for the new inventory version.

Directories

Path Synopsis
examples
listobjects command
update command
validate command
fs
config
Package config builds ocfl-go storage backends from URL-style configuration strings, and renders them back into those strings.
Package config builds ocfl-go storage backends from URL-style configuration strings, and renders them back into those strings.
http
package http implements and http-based backend that supports basic object access.
package http implements and http-based backend that supports basic object access.
internal/imptest
Package imptest is the fs implementation test suite: a set of assertions that every implementation of the ocflfs interfaces must satisfy, run against each backend from that backend's own tests.
Package imptest is the fs implementation test suite: a set of assertions that every implementation of the ocflfs interfaces must satisfy, run against each backend from that backend's own tests.
s3
Package s3 implements the ocflfs storage interfaces over an S3 bucket, so an OCFL storage root can live in a bucket instead of a directory.
Package s3 implements the ocflfs storage interfaces over an S3 bucket, so an OCFL storage root can live in a bucket instead of a directory.
s3/example/conformance command
conformance runs the shared fs implementation test suite (imptest) against a real S3 bucket, the same tests the backend's own unit tests run against the in-process mock in fs/s3/imptest_test.go.
conformance runs the shared fs implementation test suite (imptest) against a real S3 bucket, the same tests the backend's own unit tests run against the in-process mock in fs/s3/imptest_test.go.
s3/example/etag command
s3/example/rangeserver command
rangeserver is a simple HTTP server that serves objects from an S3 bucket with full support for HTTP Range requests.
rangeserver is a simple HTTP server that serves objects from an S3 bucket with full support for HTTP Range requests.
internal
Package stage provides high-level tools for staging content as part of an ocfl.ObjectUpdate: it changes an update's new version state and keeps the ocfl.ContentSource that provides the update's new content consistent with it, so the two can be passed to ocfl.ObjectUpdate.Apply together.
Package stage provides high-level tools for staging content as part of an ocfl.ObjectUpdate: it changes an update's new version state and keeps the ocfl.ContentSource that provides the update's new content consistent with it, so the two can be passed to ocfl.ObjectUpdate.Apply together.

Jump to

Keyboard shortcuts

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