mdzip

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: Apache-2.0 Imports: 20 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.

README

mdzip-core-go

A Go library for reading, writing and validating MDZip (.mdz) archives: ZIP files that hold one or more Markdown documents, the files they use and a manifest.json. It follows the MDZip specification 1.2 and passes its conformance fixtures.

It doesn't render Markdown; your application does that.

go get github.com/mdzip-project/mdzip-core-go

Requires Go 1.26 or later. Dependencies: the standard library's archive/zip, plus golang.org/x/text for Unicode NFC normalization and case folding, which the standard library lacks.

Example

import mdzip "github.com/mdzip-project/mdzip-core-go"

// Create
a := mdzip.New()
a.EditManifest().SetApplication("My App", "1.0.0", "https://example.com")
a.WriteFile("index.md", []byte("# Field notes\n\n![map](images/map.png)\n"))
a.WriteFile("images/map.png", pngBytes)
if err := a.Save("notes.mdz"); err != nil { ... }

// Open and read
b, err := mdzip.Open("notes.mdz")
ep, err := b.EntryPoint()               // "index.md"
text, err := b.ReadText(ep)
link, err := b.Resolve(ep, "images/map.png") // LinkInternal, Entry "images/map.png"

// Modify
b.WriteFile("index.md", []byte(text+"\nMore notes.\n"))
b.Manifest().SetTitle("Field notes, revised")
err = b.Save("notes.mdz") // untouched entries keep their bytes

// Validate without opening
report, err := mdzip.ValidateFile("notes.mdz")
for _, f := range report.Findings { fmt.Println(f.Severity, f.Code, f.Path) }

Contract operations (R1–R7)

How the core library contract maps to this API:

ID Operation API
R1 Open/read an archive Open(path), OpenBytes(data). The archive is read into memory. Opening checks the container and manifest and fails with the first error.
R2 Inspect entries and metadata Archive.Entries() (stored names; KindFile, KindDir, KindSpecial), Has, ReadFile, ReadText, Manifest() (typed getters plus Lookup(jsonPointer) for any field), EntryPoint(), Mode(), Warnings()
R3 Resolve a link Archive.Resolve(from, dest) → Link{Kind, Entry, Fragment, Reason}
R4 Validate Validate(data), ValidateFile(path) → Report with every Finding (severity, code, path); ParseManifest, ValidatePath for single parts
R5 Create an archive New(), then WriteFile, SetEntryPoint, EditManifest(); write with Save, Bytes or WriteTo
R6 Modify an archive WriteFile (add or replace), Remove, SetEntryPoint, Manifest()/EditManifest() setters, Set, Delete; then Save, Bytes or WriteTo
R7 Safety rules Applied by Open, OpenBytes, Validate and every read: path rules, NFC duplicates and conflicts, compression methods, encryption, symbolic links, and the limits in DefaultLimits()

How it behaves

Errors. Every error is an *mdzip.Error with a stable Code, such as ERR_ENTRYPOINT_MISSING. Check it without reading the message:

if errors.Is(err, mdzip.ErrEntryPointMissing) { ... }
switch mdzip.CodeOf(err) { case mdzip.ErrZipInvalid: ... }

The codes are those in Section 16.5 of the specification. A path error has Code ERR_PATH_INVALID and a Detail saying what's wrong (ERR_PATH_TRAVERSAL, ERR_PATH_LEADING_SLASH, ERR_PATH_RESERVED_CHAR, ERR_PATH_CONTROL_CHAR, ERR_PATH_EMPTY); errors.Is matches either. The library adds ERR_ENTRYPOINT_CHANGED, ERR_NOT_FOUND (also matches fs.ErrNotExist), ERR_TEXT_INVALID and ERR_IO. Warnings (WARN_FIELD_IGNORED, WARN_DUPLICATE_MEMBER, WARN_SPECIAL_ENTRY, WARN_CASE_COLLISION, WARN_COVER_MISSING, WARN_VERSION_OLDER) never stop an archive opening.

Entry point. EntryPoint() follows Section 5.5 on the archive as it is now. A manifest entryPoint that's invalid fails Open with ERR_ENTRYPOINT_INVALID. One that names a missing file returns ERR_ENTRYPOINT_MISSING from EntryPoint(), never a fallback to index.md or README.md, and an ambiguous archive returns ERR_ENTRYPOINT_UNRESOLVED. These two don't fail Open, so an application can still list the files, let the user choose, or repair the archive.

Paths. Lookups normalize to NFC and compare case-sensitively; a name that differs only in case never matches (the error message suggests it). Support file names and Markdown extensions are compared ASCII case-insensitively, never with locale rules.

Modes. Both modes are supported. In project mode each Markdown file is a document of its own; nothing joins them. An unknown mode fails Open with ERR_MODE_UNSUPPORTED.

Links. Resolve implements Section 9.3: fragment and query splitting, percent-decoding once per segment, and NFC case-sensitive matching. A .. that climbs above the archive root is never clamped; the link is unresolved with ReasonOutside. Links outside and into archives (Sections 9.4–9.5) are optional and not resolved here; a host application can resolve them under Section 9.6.

Symbolic links and special files are never followed or read. They're listed by Entries() as KindSpecial and reported as WARN_SPECIAL_ENTRY. Saving keeps them unchanged, so tell the user; Remove repairs the archive.

Limits. Reading enforces at most 100,000 entries, 1 GiB per entry, 4 GiB in total and a 1000:1 compression ratio above 1 MiB, checked on declared sizes when opening and on the bytes actually decompressed when reading. An entry never returns more than its declared size; one that expands past it fails with ERR_LIMIT_EXCEEDED. Entries that share data fail with ERR_ZIP_INVALID.

Saving. Save writes a temporary file next to the target and renames it over the original only when it's complete, so a failed save leaves the original file as it was.

  • Creating (New) always writes a manifest with spec.version, entryPoint, mode, title (from the first # heading or the file name), created and producer.core.
  • Modifying an opened archive keeps every untouched entry's path and bytes (copied without recompressing, after checking its CRC), keeps unknown manifest fields, and refreshes modified.when. It fails with ERR_ENTRYPOINT_CHANGED if a change would move or break the entry point, unless you called SetEntryPoint. An archive without a manifest gets one naming the entry point it had before the change.
  • Written entries use stored or deflate only, have the UTF-8 flag on non-ASCII names, give sizes in the local header (no data descriptors), and carry no ZIP64 records unless a size needs one. Markdown files get LF line endings; other files are written as given.

Conformance

The fixtures in testdata/fixtures are copied from spec tag v1.2.1 with the spec's sync tool, and a test checks them against the SPEC-FIXTURES.json checksums. To update them:

node ../mdzip-spec/tools/sync-fixtures.mjs testdata/fixtures --ref <tag>

go test -v ./... runs every consumer test and producer check through the public API and prints a results table. When the mdz CLI is on the PATH, every archive the tests write is also checked with mdz validate. Results against v1.2.1:

Tests Result
T-001 – T-015, T-017, T-018 Passed
T-011 Passed for the 42 cases resolved from documents inside an archive, run as a consumer without links outside or into archives (those must come back unresolved). The 11 cases that resolve from a host file are not applicable.
T-016 Not applicable: it's for consumers that render Markdown
T-017 Passed; its extraction part doesn't apply, since the library has no extraction API
P-001 – P-008 Passed. mdz validate reports every archive the tests write as valid, except the P-008 output, which keeps the fixture's three symbolic links as the check allows, so mdz warns about them.

Not included

The contract's optional extensions are left out: image analysis, a workspace or editor model, asset helpers (MIME types, data URIs), packaging conveniences (folder scans, filters), configurable limits and host link resolution. Extraction to disk isn't provided either.

License

Apache-2.0. See LICENSE.

Documentation

Overview

Package mdzip reads, writes and validates MDZip (.mdz) archives: ZIP files holding one or more Markdown documents, the files they use and a manifest.json, as defined by the MDZip specification (https://github.com/mdzip-project/mdzip-spec).

Open an archive with Open or OpenBytes, find its primary document with Archive.EntryPoint, read entries with Archive.ReadFile and Archive.ReadText, and resolve links between documents with Archive.Resolve. Start a new archive with New. Change an archive with Archive.WriteFile, Archive.Remove, Archive.SetEntryPoint and Archive.EditManifest, then write it with Archive.Save. Check an archive without opening it with Validate.

Errors carry a stable Code, such as ErrEntryPointMissing, that callers check with errors.Is or CodeOf rather than by reading the message.

The package doesn't render Markdown; applications do that.

Example
package main

import (
	"errors"
	"fmt"

	mdzip "github.com/mdzip-project/mdzip-core-go"
)

func main() {
	// Create an archive.
	a := mdzip.New()
	a.EditManifest().SetApplication("Example App", "1.0.0", "")
	a.WriteFile("index.md", []byte("# Field notes\n\n![map](images/map.png)\n"))
	a.WriteFile("images/map.png", []byte("…image bytes…"))
	data, err := a.Bytes() // or a.Save("notes.mdz")
	if err != nil {
		panic(err)
	}

	// Open it again and read the primary document.
	b, err := mdzip.OpenBytes(data)
	if err != nil {
		panic(err)
	}
	ep, err := b.EntryPoint()
	if errors.Is(err, mdzip.ErrEntryPointMissing) {
		fmt.Println("the manifest names a file that isn't there")
		return
	}
	text, _ := b.ReadText(ep)
	link, _ := b.Resolve(ep, "images/map.png")

	fmt.Println(ep, b.Manifest().Title(), b.Mode())
	fmt.Printf("%q\n", text[:15])
	fmt.Println(link.Kind == mdzip.LinkInternal, link.Entry)
}
Output:
index.md Field notes document
"# Field notes\n\n"
true images/map.png

Index

Examples

Constants

View Source
const (
	LibraryName    = "mdzip-core-go"
	LibraryVersion = "0.1.0"
	LibraryURL     = "https://github.com/mdzip-project/mdzip-core-go"
)

Library identity, written to producer.core in archives this library creates (Section 14.1, item 16).

View Source
const SpecVersion = "1.2.0"

SpecVersion is the version of the MDZip specification this library implements and writes into new manifests.

Variables

This section is empty.

Functions

func IsMarkdown

func IsMarkdown(name string) bool

IsMarkdown reports whether name has a .md or .markdown extension, compared ASCII case-insensitively (Section 7.3).

func ValidatePath

func ValidatePath(name string) error

ValidatePath reports whether name is a valid stored entry path under Section 5.4. A name ending in "/" is a directory entry and is checked without that slash. The error is an *Error with Code ErrPathInvalid and, where one applies, a Detail such as ErrPathTraversal.

ValidatePath checks a single name. Whole-archive rules (NFC duplicates, a file that is also a directory) are checked when an archive is opened.

Types

type Archive

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

Archive is an MDZip archive held in memory. Open one with Open or OpenBytes, or start a new one with New. An Archive is not safe for concurrent use.

func New

func New() *Archive

New starts a new, empty archive. Add files with Archive.WriteFile, set metadata with Archive.EditManifest, then save it with Archive.Save, Archive.Bytes or Archive.WriteTo.

Saving a new archive is a creation (Section 14.1): it always writes a manifest.json with spec.version, entryPoint, mode, title, created and producer.core. The entry point is the one set with Archive.SetEntryPoint, or else the one discovery finds (index.md, or the only root-level Markdown file); saving fails with ErrEntryPointUnresolved when there is none. The title defaults to the entry point's first "# " heading, or its file name.

func Open

func Open(path string) (*Archive, error)

Open reads the archive at path. See OpenBytes.

func OpenBytes

func OpenBytes(data []byte) (*Archive, error)

OpenBytes reads an archive from memory. The Archive keeps data, so the caller must not change it afterwards.

OpenBytes checks the whole container and manifest and fails with the first error: ErrZipInvalid, ErrZipEncrypted, ErrPathInvalid, ErrDuplicatePath, ErrPathConflict, ErrLimitExceeded, ErrManifestInvalid, ErrVersionUnsupported, ErrModeUnsupported or ErrEntryPointInvalid.

An entry point that names a missing file, or that can't be determined, is not an open error: Archive.EntryPoint reports it, so an application can still show the files or repair the archive.

func (*Archive) Bytes

func (a *Archive) Bytes() ([]byte, error)

Bytes returns the archive as an .mdz file. See Archive.Save.

func (*Archive) EditManifest

func (a *Archive) EditManifest() *Manifest

EditManifest returns the manifest for editing, adding an empty one if the archive has none. Saving fills in what a conforming manifest needs.

func (*Archive) Entries

func (a *Archive) Entries() []Entry

Entries lists the archive's entries in order: stored files, directories and special entries, then new ones.

func (*Archive) EntryPoint

func (a *Archive) EntryPoint() (string, error)

EntryPoint returns the stored path of the primary Markdown file, using the discovery algorithm of Section 5.5 on the archive as it is now.

A manifest entryPoint that matches no file fails with ErrEntryPointMissing; it never falls back to index.md or another file. With no entryPoint, it uses index.md, then the only root-level Markdown file that isn't a support file (README, AGENTS, LICENSE, CHANGELOG, CONTRIBUTING), then the only root-level Markdown file. Otherwise it fails with ErrEntryPointUnresolved; list the Markdown files with Archive.Entries and let the user choose.

func (*Archive) Has

func (a *Archive) Has(path string) bool

Has reports whether a regular file exists at path, matched after NFC normalization and case-sensitively. It never matches a name that differs only in case.

func (*Archive) Manifest

func (a *Archive) Manifest() *Manifest

Manifest returns the archive's manifest, or nil when it has none. Changes made through it are written by the next save. See Archive.EditManifest.

func (*Archive) Mode

func (a *Archive) Mode() Mode

Mode returns the archive's mode: the manifest's, or ModeDocument when it declares none (Section 5.7.1). Both modes are supported: in project mode each Markdown file is a separate document, read on its own.

func (*Archive) ReadFile

func (a *Archive) ReadFile(path string) ([]byte, error)

ReadFile returns the bytes of the file at path. It fails with ErrNotFound when there is no such regular file (directories and special entries aren't files), and with ErrLimitExceeded or ErrZipInvalid when the entry's data is larger than declared or damaged.

func (*Archive) ReadText

func (a *Archive) ReadText(path string) (string, error)

ReadText returns the file at path as UTF-8 text, without a leading byte order mark. Line endings are returned as stored (LF or CRLF). It fails with ErrTextInvalid when the bytes aren't valid UTF-8.

func (*Archive) Remove

func (a *Archive) Remove(path string) error

Remove removes the entry at path: a file, a special entry such as a symbolic link, or a directory entry (name ending in "/"). Removing a directory entry doesn't remove the files under it. Removing manifest.json removes the manifest; saving then writes a new one. It fails with ErrNotFound when there is no such entry.

func (*Archive) Resolve

func (a *Archive) Resolve(from, dest string) (Link, error)

Resolve resolves a standard Markdown link destination (from a link, image, reference definition or HTML href/src) written in the document at from, using the algorithm of Section 9.3.

Paths are resolved against from's directory, percent-decoded once per segment and matched after NFC normalization, case-sensitively. A ".." that climbs above the archive root is never clamped: the link is unresolved with ReasonOutside. A destination of only a fragment or query refers to from itself.

Resolve fails with ErrNotFound only when from isn't a file in the archive.

func (*Archive) Save

func (a *Archive) Save(path string) error

Save writes the archive to path. It writes a temporary file next to path and renames it over the original only once it is complete, so a failed save leaves any existing file as it was.

For an opened archive, saving is a modification (Section 14.1): every entry you didn't change keeps its path and bytes, unknown manifest fields are kept, and manifest modified.when is updated when something changed. Saving fails with ErrEntryPointChanged if your changes would change which file the entry point resolves to, or leave it unresolvable, unless you called Archive.SetEntryPoint. An archive without a manifest gets one naming the entry point it resolved to when opened. Symbolic link entries are kept as they are (see WarnSpecialEntry): remove them to repair the archive. Every untouched entry is decompressed and checked first, so a damaged entry fails the save with its error rather than being copied.

func (*Archive) SetEntryPoint

func (a *Archive) SetEntryPoint(path string) error

SetEntryPoint makes path the entry point, writing it to the manifest's entryPoint (and adding a manifest if there is none). The path must be a valid entry point path; the file must exist when the archive is saved.

func (*Archive) Warnings

func (a *Archive) Warnings() []Finding

Warnings returns what opening the archive found that doesn't stop it being used, such as symbolic link entries (WarnSpecialEntry) or ignored manifest fields.

func (*Archive) WriteFile

func (a *Archive) WriteFile(name string, data []byte) error

WriteFile adds a file, or replaces the content of the file at that path.

The path must satisfy Section 5.4 (ValidatePath) and name a file, not a directory. It is stored in NFC; its capitalization is kept. A file that would also be a directory fails with ErrPathConflict. Replacing an existing file keeps its stored name; replacing a symbolic link entry turns it into a regular file. Markdown files (.md, .markdown) are stored with LF line endings (Section 12.2); other files are stored as given.

Writing manifest.json parses it as the new manifest; prefer Archive.EditManifest, which keeps unknown fields for you.

func (*Archive) WriteTo

func (a *Archive) WriteTo(w io.Writer) (int64, error)

WriteTo writes the archive as an .mdz file to w. Nothing is written when the archive can't be saved; see Archive.Save.

type Code

type Code string

Code is a stable error or warning code. The ERR_ codes in the first group are the ones the MDZip specification defines (Section 16.5); the rest are specific to this library.

A Code is itself an error, so callers check for one with errors.Is:

if errors.Is(err, mdzip.ErrEntryPointMissing) { ... }

or read it with CodeOf. Neither needs the message text.

const (
	// ErrZipInvalid: not a valid ZIP archive, or an entry uses a compression
	// method other than 0 (stored) or 8 (deflate).
	ErrZipInvalid Code = "ERR_ZIP_INVALID"
	// ErrZipEncrypted: the archive or an entry is encrypted.
	ErrZipEncrypted Code = "ERR_ZIP_ENCRYPTED"
	// ErrPathInvalid: an entry path breaks Section 5.4. [Error.Detail] may
	// carry one of the more specific ErrPath... codes below.
	ErrPathInvalid Code = "ERR_PATH_INVALID"
	// ErrManifestInvalid: manifest.json isn't UTF-8 JSON, its top-level value
	// isn't an object, or a critical field has the wrong type or value.
	ErrManifestInvalid Code = "ERR_MANIFEST_INVALID"
	// ErrEntryPointUnresolved: no unambiguous primary Markdown file.
	ErrEntryPointUnresolved Code = "ERR_ENTRYPOINT_UNRESOLVED"
	// ErrEntryPointInvalid: manifest entryPoint isn't a valid entry point path.
	ErrEntryPointInvalid Code = "ERR_ENTRYPOINT_INVALID"
	// ErrEntryPointMissing: entryPoint is valid but matches no file,
	// including a name that differs only in case.
	ErrEntryPointMissing Code = "ERR_ENTRYPOINT_MISSING"
	// ErrVersionUnsupported: spec.version has a major version above 1.
	ErrVersionUnsupported Code = "ERR_VERSION_UNSUPPORTED"
	// ErrPathConflict: a file's path is also a directory of another entry.
	ErrPathConflict Code = "ERR_PATH_CONFLICT"
	// ErrDuplicatePath: two entries are equal after NFC normalization.
	ErrDuplicatePath Code = "ERR_DUPLICATE_PATH"
	// ErrModeUnsupported: manifest mode isn't "document" or "project".
	ErrModeUnsupported Code = "ERR_MODE_UNSUPPORTED"
	// ErrLimitExceeded: a resource limit was exceeded (see [DefaultLimits]),
	// including an entry that decompresses to more than its declared size.
	ErrLimitExceeded Code = "ERR_LIMIT_EXCEEDED"
)

Error codes from the MDZip specification, Section 16.5.

const (
	ErrPathEmpty        Code = "ERR_PATH_EMPTY"
	ErrPathLeadingSlash Code = "ERR_PATH_LEADING_SLASH"
	ErrPathTraversal    Code = "ERR_PATH_TRAVERSAL"
	ErrPathReservedChar Code = "ERR_PATH_RESERVED_CHAR"
	ErrPathControlChar  Code = "ERR_PATH_CONTROL_CHAR"
)

Detail codes for ErrPathInvalid, shared with the other MDZip cores and used by the specification's path validation fixtures.

const (
	// ErrEntryPointChanged: a save would change which file the entry point
	// resolves to, or leave it unresolvable (Section 14.1). Call
	// [Archive.SetEntryPoint] to change it on purpose.
	ErrEntryPointChanged Code = "ERR_ENTRYPOINT_CHANGED"
	// ErrNotFound: no file entry has that path. errors.Is(err, fs.ErrNotExist)
	// is also true.
	ErrNotFound Code = "ERR_NOT_FOUND"
	// ErrTextInvalid: an entry read as text isn't valid UTF-8.
	ErrTextInvalid Code = "ERR_TEXT_INVALID"
	// ErrIO: reading or writing a file on disk failed; see [errors.Unwrap].
	ErrIO Code = "ERR_IO"
)

Library-specific error codes.

const (
	// WarnFieldIgnored: a descriptive manifest field has the wrong type or an
	// invalid value and is ignored (Section 6.4). Path is the field, such as
	// "title" or "created.by".
	WarnFieldIgnored Code = "WARN_FIELD_IGNORED"
	// WarnDuplicateMember: manifest.json repeats a member name; the last one
	// is used (Section 6.4). Path is a JSON Pointer to the member.
	WarnDuplicateMember Code = "WARN_DUPLICATE_MEMBER"
	// WarnSpecialEntry: an entry is a symbolic link or other special file. It
	// is never followed and is not a file for reading or links (Section 13.1).
	// Saving keeps it unchanged; remove it with [Archive.Remove] to repair the
	// archive.
	WarnSpecialEntry Code = "WARN_SPECIAL_ENTRY"
	// WarnCaseCollision: two entries differ only in case, so they collide when
	// extracted to a case-insensitive filesystem (Section 5.4).
	WarnCaseCollision Code = "WARN_CASE_COLLISION"
	// WarnCoverMissing: manifest cover names no file in the archive.
	WarnCoverMissing Code = "WARN_COVER_MISSING"
	// WarnVersionOlder: spec.version has a major version below 1 (Section 11.2).
	WarnVersionOlder Code = "WARN_VERSION_OLDER"
)

Warning codes, reported in [Finding]s. They never stop an archive opening.

func CodeOf

func CodeOf(err error) Code

CodeOf returns the Code of err, or "" if err doesn't come from this package.

func (Code) Error

func (c Code) Error() string

Error returns the code itself, for example "ERR_ZIP_INVALID".

type Entry

type Entry struct {
	// Name is the stored path, exactly as in the archive. Directory entries
	// end in "/".
	Name string
	Kind EntryKind
	// Size is the uncompressed size in bytes (as declared, for an entry read
	// from an archive).
	Size     uint64
	Modified time.Time
}

Entry describes one archive entry.

type EntryKind

type EntryKind int

EntryKind says what an archive entry is.

const (
	// KindFile is a regular file.
	KindFile EntryKind = iota
	// KindDir is a directory entry (its stored name ends in "/").
	KindDir
	// KindSpecial is a symbolic link or other special file. It is never
	// followed or read (Section 13.1); see WarnSpecialEntry.
	KindSpecial
)

type Error

type Error struct {
	// Code is the stable code, for example ErrEntryPointMissing.
	Code Code
	// Detail is a more specific code, or "". For ErrPathInvalid it says what
	// is wrong with the path, for example ErrPathTraversal.
	Detail Code
	// Path is the entry path or manifest field concerned, or "".
	Path string
	// Message describes the problem for people. Don't parse it.
	Message string
	// Err is the underlying error, if any.
	Err error
}

Error is the error type returned by this package.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Is

func (e *Error) Is(target error) bool

Is reports whether target is e's Code or Detail, so that errors.Is(err, mdzip.ErrPathTraversal) works. An ErrNotFound error also matches fs.ErrNotExist.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the underlying error.

type Finding

type Finding struct {
	Severity Severity
	// Code is a stable code: an ERR_ code for errors, a WARN_ code for
	// warnings.
	Code Code
	// Detail is a more specific code, or "" (see [Error.Detail]).
	Detail Code
	// Path is the entry path or manifest field concerned, or "".
	Path string
	// Message describes the problem for people. Don't parse it.
	Message string
	// contains filtered or unexported fields
}

Finding is one problem found while checking an archive.

type Limits

type Limits struct {
	// MaxEntries is the most central directory entries an archive may have.
	MaxEntries int
	// MaxEntryBytes is the largest uncompressed size of one entry.
	MaxEntryBytes uint64
	// MaxTotalBytes is the largest total uncompressed size of all entries.
	MaxTotalBytes uint64
	// MaxRatio is the highest uncompressed:compressed ratio allowed for an
	// entry larger than RatioAppliesAbove bytes.
	MaxRatio          uint64
	RatioAppliesAbove uint64
	// MaxManifestBytes is the largest manifest.json this library parses.
	MaxManifestBytes uint64
}

Limits are the resource limits applied while reading (Section 13.1). They check the bytes actually decompressed, not only the sizes an archive declares.

func DefaultLimits

func DefaultLimits() Limits

DefaultLimits returns the limits every archive is read with. They match the reference limits of the specification's conformance fixtures and are not configurable.

type Link struct {
	Kind LinkKind
	// Entry is the stored path of the target, for LinkInternal.
	Entry string
	// Fragment is the text after the first "#", or "". It never takes part
	// in resolving the path.
	Fragment string
	// Reason is why a LinkUnresolved link has no target.
	Reason Reason
}

Link is the result of Archive.Resolve.

type LinkKind

type LinkKind int

LinkKind says what a link destination resolved to.

const (
	// LinkUnresolved: the link has no target; see [Link.Reason]. Show it as
	// broken. Never substitute another target for it.
	LinkUnresolved LinkKind = iota
	// LinkInternal: an entry in the same archive, in [Link.Entry].
	LinkInternal
	// LinkURL: a URL with a scheme, such as https: or mailto:. It is not a
	// path and isn't resolved (Section 9.2).
	LinkURL
)

type Manifest

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

Manifest is a parsed manifest.json. It keeps every field, including ones this library doesn't know, so rewriting it preserves them (Section 6.3). The typed accessors return "" for a field that is absent or invalid.

func ParseManifest

func ParseManifest(data []byte) (*Manifest, error)

ParseManifest parses and validates manifest.json (Section 6.4).

It fails with ErrManifestInvalid when the data isn't UTF-8 JSON, the top-level value isn't an object, or spec or spec.version is wrong; with ErrVersionUnsupported for a spec.version major version above 1; with ErrModeUnsupported for an unknown mode string; and with ErrEntryPointInvalid for an entryPoint that isn't a valid entry point path. Wrong descriptive fields are ignored and reported in Manifest.Warnings, as are duplicate member names (the last one is used).

func (*Manifest) Cover

func (m *Manifest) Cover() string

Cover returns the cover image path with any leading "./" removed, or "" when it is absent or invalid. The file may still be missing; opening an archive warns about that.

func (*Manifest) Delete

func (m *Manifest) Delete(name string)

Delete removes a top-level field.

func (*Manifest) Description

func (m *Manifest) Description() string

Description returns the description, or "".

func (*Manifest) EntryPoint

func (m *Manifest) EntryPoint() string

EntryPoint returns the declared entryPoint with any leading "./" removed, or "" when there is none. Archive.EntryPoint resolves it.

func (*Manifest) Language

func (m *Manifest) Language() string

Language returns the BCP 47 language tag, or "".

func (*Manifest) Lookup

func (m *Manifest) Lookup(pointer string) (any, bool)

Lookup returns the value at a JSON Pointer (RFC 6901), such as "/title" or "/producer/application/name", as plain Go values: map[string]any, []any, string, json.Number, bool or nil. It reports false when nothing is there.

func (*Manifest) MarshalJSON

func (m *Manifest) MarshalJSON() ([]byte, error)

MarshalJSON returns the manifest as written to manifest.json: standard JSON, two-space indentation, LF line endings and no duplicate members.

func (*Manifest) Mode

func (m *Manifest) Mode() Mode

Mode returns the declared mode, or ModeDocument when there is none.

func (*Manifest) Set

func (m *Manifest) Set(name string, value any) error

Set sets a top-level field to any value encoding/json can marshal. Use it for fields without a typed setter. Setting a field the specification treats as critical checks it again: an invalid mode or entryPoint fails.

func (*Manifest) SetApplication

func (m *Manifest) SetApplication(name, version, url string)

SetApplication records the application writing the archive in producer.application, keeping any other fields there (Section 14.1).

func (*Manifest) SetMode

func (m *Manifest) SetMode(mode Mode) error

SetMode sets the mode. It accepts only ModeDocument and ModeProject.

func (*Manifest) SetTitle

func (m *Manifest) SetTitle(title string)

SetTitle sets the title. An empty title removes the field, since the specification doesn't allow an empty one.

func (*Manifest) SpecVersion

func (m *Manifest) SpecVersion() string

SpecVersion returns spec.version, or "" when the manifest has none.

func (*Manifest) Title

func (m *Manifest) Title() string

Title returns the title, or "" if it is absent or invalid.

func (*Manifest) Warnings

func (m *Manifest) Warnings() []Finding

Warnings returns the problems found that don't stop the manifest being used: ignored descriptive fields and duplicate member names.

type Mode

type Mode string

Mode is an archive's interpretation mode (Section 5.7).

const (
	// ModeDocument: one logical publication (the default).
	ModeDocument Mode = "document"
	// ModeProject: a collection of independent documents.
	ModeProject Mode = "project"
)

type Reason

type Reason string

Reason says why a link is unresolved. Reasons are informative; the kind is what conformance depends on.

const (
	// ReasonNotFound: the path is well formed but names no file, including a
	// name that differs only in case, a directory or a symbolic link entry.
	ReasonNotFound Reason = "not-found"
	// ReasonInvalid: the destination isn't a valid relative link, for
	// example "/x.md", "a\b.md", "%ZZ" or an encoded "/".
	ReasonInvalid Reason = "invalid"
	// ReasonOutside: the link climbs above the archive root. This library
	// doesn't resolve links outside or into archives (Sections 9.4 and 9.5,
	// both optional), so they stay unresolved; a host application may
	// resolve them itself under the rules of Section 9.6.
	ReasonOutside Reason = "unsupported"
)

type Report

type Report struct {
	Findings []Finding
}

Report is the result of Validate.

func Validate

func Validate(data []byte) *Report

Validate checks an archive against the specification and returns every finding instead of stopping at the first, as OpenBytes does. On top of what OpenBytes checks, it reports an entry point that is missing or can't be determined as an error.

Some checks depend on others: when the container or entry names are broken, the manifest and entry point aren't checked.

func ValidateFile

func ValidateFile(path string) (*Report, error)

ValidateFile validates the archive at path. The error is only for failing to read the file (ErrIO).

func (*Report) Errors

func (r *Report) Errors() []Finding

Errors returns the findings with SeverityError.

func (*Report) Valid

func (r *Report) Valid() bool

Valid reports whether the archive has no errors. Warnings don't count.

func (*Report) Warnings

func (r *Report) Warnings() []Finding

Warnings returns the findings with SeverityWarning.

type Severity

type Severity int

Severity says whether a finding makes an archive non-conforming.

const (
	// SeverityError: the archive breaks a rule of the specification.
	SeverityError Severity = iota
	// SeverityWarning: allowed, but worth telling the user about.
	SeverityWarning
)

func (Severity) String

func (s Severity) String() string

Jump to

Keyboard shortcuts

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