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\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 ¶
- Constants
- func IsMarkdown(name string) bool
- func ValidatePath(name string) error
- type Archive
- func (a *Archive) Bytes() ([]byte, error)
- func (a *Archive) EditManifest() *Manifest
- func (a *Archive) Entries() []Entry
- func (a *Archive) EntryPoint() (string, error)
- func (a *Archive) Has(path string) bool
- func (a *Archive) Manifest() *Manifest
- func (a *Archive) Mode() Mode
- func (a *Archive) ReadFile(path string) ([]byte, error)
- func (a *Archive) ReadText(path string) (string, error)
- func (a *Archive) Remove(path string) error
- func (a *Archive) Resolve(from, dest string) (Link, error)
- func (a *Archive) Save(path string) error
- func (a *Archive) SetEntryPoint(path string) error
- func (a *Archive) Warnings() []Finding
- func (a *Archive) WriteFile(name string, data []byte) error
- func (a *Archive) WriteTo(w io.Writer) (int64, error)
- type Code
- type Entry
- type EntryKind
- type Error
- type Finding
- type Limits
- type Link
- type LinkKind
- type Manifest
- func (m *Manifest) Cover() string
- func (m *Manifest) Delete(name string)
- func (m *Manifest) Description() string
- func (m *Manifest) EntryPoint() string
- func (m *Manifest) Language() string
- func (m *Manifest) Lookup(pointer string) (any, bool)
- func (m *Manifest) MarshalJSON() ([]byte, error)
- func (m *Manifest) Mode() Mode
- func (m *Manifest) Set(name string, value any) error
- func (m *Manifest) SetApplication(name, version, url string)
- func (m *Manifest) SetMode(mode Mode) error
- func (m *Manifest) SetTitle(title string)
- func (m *Manifest) SpecVersion() string
- func (m *Manifest) Title() string
- func (m *Manifest) Warnings() []Finding
- type Mode
- type Reason
- type Report
- type Severity
Examples ¶
Constants ¶
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).
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 ¶
IsMarkdown reports whether name has a .md or .markdown extension, compared ASCII case-insensitively (Section 7.3).
func ValidatePath ¶
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 OpenBytes ¶
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 ¶
Bytes returns the archive as an .mdz file. See Archive.Save.
func (*Archive) EditManifest ¶
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 ¶
Entries lists the archive's entries in order: stored files, directories and special entries, then new ones.
func (*Archive) EntryPoint ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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.
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.
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 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.
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 ¶
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 ¶
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 ¶
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) Description ¶
Description returns the description, or "".
func (*Manifest) EntryPoint ¶
EntryPoint returns the declared entryPoint with any leading "./" removed, or "" when there is none. Archive.EntryPoint resolves it.
func (*Manifest) Lookup ¶
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 ¶
MarshalJSON returns the manifest as written to manifest.json: standard JSON, two-space indentation, LF line endings and no duplicate members.
func (*Manifest) Set ¶
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 ¶
SetApplication records the application writing the archive in producer.application, keeping any other fields there (Section 14.1).
func (*Manifest) SetTitle ¶
SetTitle sets the title. An empty title removes the field, since the specification doesn't allow an empty one.
func (*Manifest) SpecVersion ¶
SpecVersion returns spec.version, or "" when the manifest has none.
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 ¶
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 ¶
ValidateFile validates the archive at path. The error is only for failing to read the file (ErrIO).