Functional Weave
Code in Rust

form.file-check@1.0.0

impl/python/validate_files.py

2,940 bytes · the Python implementation · view raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

from typing import List, Sequence

from .form_file_check_accepts_file import accept_tokens, describe_accept, matches_accept  ← acceptsFile, another function of this group · built into the same file, even by a slim install
from .form_file_check_format_file_size import format_file_size  ← formatFileSize, another function of this group · built into the same file, even by a slim install
from .form_file_check_types import FileCheck, FileError, FileInfo, FileRules


def _whole(value: object) -> bool:
    return isinstance(value, int) and not isinstance(value, bool)


def validate_files(files: Sequence[FileInfo], rules: FileRules) -> FileCheck:
    """The files chosen in an upload field, checked the way the GOV.UK Design
    System's file upload asks: the field's own errors first, then each
    file's, at most one each (type, then empty, then too large)."""
    if rules.max_bytes is not None and (not _whole(rules.max_bytes) or rules.max_bytes < 0):
        raise ValueError("rules.maxBytes must be a size of 0 or more, got %r" % (rules.max_bytes,))
    if rules.max_files is not None:
        if not rules.multiple:
            raise ValueError("rules.maxFiles only applies when rules.multiple is true")
        if not _whole(rules.max_files) or rules.max_files < 1:
            raise ValueError("rules.maxFiles must be at least 1, got %r" % (rules.max_files,))
    tokens = accept_tokens(rules.accept if rules.accept is not None else "")
    for file in files:
        if not _whole(file.size) or file.size < 0:
            raise ValueError(
                'file size must be a whole number of bytes, 0 or more, got %r for "%s"' % (file.size, file.name)
            )

    errors: List[FileError] = []
    if len(files) == 0:
        if rules.required:
            message = "Select at least one file" if rules.multiple else "Select a file"
            errors.append(FileError(index=-1, name=None, code="required", message=message))
    elif not rules.multiple and len(files) > 1:
        errors.append(FileError(index=-1, name=None, code="one-file", message="Select only one file"))
    elif rules.max_files is not None and len(files) > rules.max_files:
        noun = "file" if rules.max_files == 1 else "files"
        errors.append(
            FileError(index=-1, name=None, code="too-many", message="You can only select up to %d %s" % (rules.max_files, noun))
        )

    for index, file in enumerate(files):
        subject = "The selected file" if len(files) == 1 else file.name
        if not matches_accept(tokens, file):
            code, message = "type", "%s must be %s" % (subject, describe_accept(tokens))
        elif file.size == 0:
            code, message = "empty", "%s is empty" % subject
        elif rules.max_bytes is not None and file.size > rules.max_bytes:
            code, message = "too-large", "%s must be %s or smaller" % (subject, format_file_size(rules.max_bytes))
        else:
            continue
        errors.append(FileError(index=index, name=file.name, code=code, message=message))

    return FileCheck(valid=not errors, message=errors[0].message if errors else None, errors=errors)