Functional Weave
Code in Python

form.file-check@1.0.0

impl/rust/validate_files.rs

4,649 bytes · the Rust 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.

use super::funejson::Value;  ← the fune runtime: the JSON value the test vectors use; fune build keeps it only where a signature takes one
use super::form_file_check_accepts_file::{accept_tokens, describe_accept, file_info_from_value, matches_accept};  ← acceptsFile, another function of this group · built into the same file, even by a slim install
use super::form_file_check_format_file_size::format_file_size;  ← formatFileSize, another function of this group · built into the same file, even by a slim install

/// 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).
///
/// # Panics
/// Panics on bad rules (negative maxBytes, maxFiles below 1 or without
/// multiple), a malformed accept token, or a negative file size.
pub fn validate_files(files: &[FileInfo], rules: &FileRules) -> FileCheck {
    if let Some(max) = rules.max_bytes {
        if max < 0 {
            panic!("rules.maxBytes must be a size of 0 or more, got {}", max);
        }
    }
    if let Some(max) = rules.max_files {
        if !rules.multiple {
            panic!("rules.maxFiles only applies when rules.multiple is true");
        }
        if max < 1 {
            panic!("rules.maxFiles must be at least 1, got {}", max);
        }
    }
    let tokens = accept_tokens(rules.accept.as_deref().unwrap_or(""));
    for file in files {
        if file.size < 0 {
            panic!("file size must be a whole number of bytes, 0 or more, got {} for \"{}\"", file.size, file.name);
        }
    }

    let mut errors: Vec<FileError> = Vec::new();
    let field = |code: &str, message: String| FileError { index: -1, name: None, code: code.to_string(), message };
    if files.is_empty() {
        if rules.required {
            let message = if rules.multiple { "Select at least one file" } else { "Select a file" };
            errors.push(field("required", message.to_string()));
        }
    } else if !rules.multiple && files.len() > 1 {
        errors.push(field("one-file", "Select only one file".to_string()));
    } else if let Some(max) = rules.max_files {
        if files.len() as i64 > max {
            let noun = if max == 1 { "file" } else { "files" };
            errors.push(field("too-many", format!("You can only select up to {} {}", max, noun)));
        }
    }

    for (index, file) in files.iter().enumerate() {
        let subject = if files.len() == 1 { "The selected file" } else { file.name.as_str() };
        let found = if !matches_accept(&tokens, file) {
            Some(("type", format!("{} must be {}", subject, describe_accept(&tokens))))
        } else if file.size == 0 {
            Some(("empty", format!("{} is empty", subject)))
        } else {
            match rules.max_bytes {
                Some(max) if file.size > max => {
                    Some(("too-large", format!("{} must be {} or smaller", subject, format_file_size(max))))
                }
                _ => None,
            }
        };
        if let Some((code, message)) = found {
            errors.push(FileError { index: index as i64, name: Some(file.name.clone()), code: code.to_string(), message });
        }
    }

    let message = errors.first().map(|e| e.message.clone());
    FileCheck { valid: errors.is_empty(), message, errors }
}

pub fn file_check_to_value(check: &FileCheck) -> Value {
    let text = |v: &Option<String>| v.as_deref().map(Value::str).unwrap_or(Value::Null);
    Value::obj(vec![
        ("valid", Value::Bool(check.valid)),
        ("message", text(&check.message)),
        (
            "errors",
            Value::Arr(
                check
                    .errors
                    .iter()
                    .map(|e| {
                        Value::obj(vec![
                            ("index", Value::Int(e.index)),
                            ("name", text(&e.name)),
                            ("code", Value::str(&e.code)),
                            ("message", Value::str(&e.message)),
                        ])
                    })
                    .collect(),
            ),
        ),
    ])
}

pub fn fune_vector(args: &[Value]) -> Value {
    let files: Vec<FileInfo> = args[0].as_arr().iter().map(file_info_from_value).collect();
    let r = &args[1];
    let int = |key: &str| match r.get(key) {
        Value::Int(n) => Some(*n),
        Value::Null => None,
        other => panic!("rules.{} must be a whole number, got {:?}", key, other),
    };
    let rules = FileRules {
        required: r.get("required").as_bool(),
        accept: match r.get("accept") {
            Value::Str(s) => Some(s.clone()),
            _ => None,
        },
        max_bytes: int("maxBytes"),
        multiple: r.get("multiple").as_bool(),
        max_files: int("maxFiles"),
    };
    file_check_to_value(&validate_files(&files, &rules))
}