Validating a document

Check a document against the format’s rules as you open, edit, and save it, so that Keynote opens it as you wrote it.

The format places rules on every document, from the type of each field to the slides that links point to. The library checks those rules when you open a document and as you edit it. It also checks them before you save, when you pass validate_document to save.

Opening a document checks the file, and a failure raises an error that says why. Constructing or changing a model instance checks it immediately. Passed to save as a hook, validate_document checks the whole document before save writes it, including items added to a list in place and references across the document.

The format defines each type in a JSON Schema. Any JSON Schema validator can check a file against it, one file at a time. Unlike that check, validate_document covers the values that a document’s presets supply and the references between its files.

Handle errors from opening a document

When opening a document fails, the error it raises says why. A DocumentVersionError means the file needs a newer version of the library.

The following example reports each error:

from pydantic import ValidationError

from creator_studio_doc_format.core import (
    DocumentPackageError,
    DocumentPackageErrorKind,
    DocumentVersionError,
    KeyxDocument,
)

path = "not-a-presentation.keyx"
try:
    doc = KeyxDocument.open(path)
except DocumentVersionError:
    print(f"{path} needs a newer version of the library.")
except DocumentPackageError as exc:
    # Branch on `kind`. The message text varies.
    if exc.kind is DocumentPackageErrorKind.NOT_A_PACKAGE:
        print(f"{path} isn't a document.")
    else:
        print(f"{path} is corrupt ({exc.kind.value}).")
except ValidationError:
    print(f"{path} doesn't match this library's models.")
except OSError as exc:
    print(f"Can't read {path}: {exc.strerror}.")

Catch errors as you edit

When you construct a model instance, it validates types, required fields, and constraints, such as slides needing at least one entry. Types are strict. A field typed Text doesn’t accept a value of type str.

A model instance checks again whenever you set a field. Both checks raise pydantic.ValidationError at the statement responsible:

Slide(depth="deep")  # Raises `pydantic.ValidationError`.
slide.depth = "deep"  # Raises the same error at the assignment.

A model instance doesn’t check an item added to one of its lists in place, such as with slides.append. validate_document() does.

Validate the document before you save

Pass validate_document in the pre_save_hooks argument of every save. Without it, an edit that breaks the format’s rules reaches the saved file unnoticed. One example is deleting a slide that a link points to. save calls each function in its pre_save_hooks parameter with the document and the JSON it’s about to write.

The following example validates a document before saving it as a new file:

from creator_studio_doc_format.validation import validate_document

doc = KeyxDocument.open("presentation.keyx")

# Writes nothing if the document is invalid.
doc.save("out.keyx", pre_save_hooks=[validate_document])