File size: 4,542 Bytes
8eb365e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
"""Refuse a folder whose meta.json is missing required keys.

Required: name, source, date, sample, shape, dtype, permission
  (permission.received, permission.from, permission.collectors,
  permission.date). from and collectors are one or more names.
Optional: sampling, units, and optics keys.
"""

from __future__ import annotations

import json
import re
from pathlib import Path

REQUIRED = ("name", "source", "date", "sample", "shape", "dtype", "permission")
PERMISSION_REQUIRED = ("received", "from", "collectors", "date")
DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")


def _name_list(value: object) -> list[str] | None:
    """Accept one name or a list of names. Empty is missing."""

    if isinstance(value, str) and value.strip():
        return [value.strip()]
    if isinstance(value, list) and value and all(isinstance(item, str) and item.strip() for item in value):
        return [item.strip() for item in value]
    return None


def check_meta(folder: Path) -> list[str]:
    """Return a list of problems. Empty means the sidecar is complete."""

    problems: list[str] = []
    path = folder / "meta.json"
    if not path.is_file():
        return [f"missing {path}"]
    try:
        meta = json.loads(path.read_text(encoding="utf-8"))
    except json.JSONDecodeError as exc:
        return [f"{path} is not JSON: {exc}"]
    if not isinstance(meta, dict):
        return [f"{path} must be a JSON object"]
    for key in REQUIRED:
        value = meta.get(key)
        if value in (None, "", []):
            problems.append(f"missing {key}")
    if "name" in meta and not isinstance(meta.get("name"), str):
        problems.append("name must be a string")
    if "source" in meta and not isinstance(meta.get("source"), str):
        problems.append("source must be a string")
    if "sample" in meta and not isinstance(meta.get("sample"), str):
        problems.append("sample must be a string")
    permission = meta.get("permission")
    if permission not in (None, "", []):
        if not isinstance(permission, dict):
            problems.append("permission must be an object")
        else:
            for key in PERMISSION_REQUIRED:
                value = permission.get(key)
                if value in (None, "", []):
                    problems.append(f"missing permission.{key}")
            if permission.get("received") is not True:
                problems.append("permission.received must be true")
            if permission.get("from") not in (None, "", []) and _name_list(permission.get("from")) is None:
                problems.append("permission.from must be one name or a list of names")
            if permission.get("collectors") not in (None, "", []) and _name_list(permission.get("collectors")) is None:
                problems.append("permission.collectors must be one name or a list of names")
            perm_date = permission.get("date")
            if perm_date not in (None, "") and not (isinstance(perm_date, str) and DATE_RE.match(perm_date)):
                problems.append("permission.date must be YYYY-MM-DD")
    date = meta.get("date")
    if date not in (None, "", []) and not (isinstance(date, str) and DATE_RE.match(date)):
        problems.append("date must be YYYY-MM-DD")
    shape = meta.get("shape")
    if shape not in (None, "", []):
        if not (
            isinstance(shape, list)
            and len(shape) >= 2
            and all(isinstance(n, int) and not isinstance(n, bool) for n in shape)
        ):
            problems.append("shape must be a list of ints, length >= 2")
    dtype = meta.get("dtype")
    if dtype not in (None, "", []) and not isinstance(dtype, str):
        problems.append("dtype must be a string")
    sampling = meta.get("sampling")
    if sampling not in (None, "", []):
        if not (isinstance(sampling, list) and all(isinstance(n, (int, float)) and not isinstance(n, bool) for n in sampling)):
            problems.append("sampling must be a list of numbers")
        if isinstance(shape, list) and isinstance(sampling, list) and len(sampling) != len(shape):
            problems.append("sampling length must match shape length")
    units = meta.get("units")
    if units not in (None, "", []):
        if not (isinstance(units, list) and all(isinstance(u, str) for u in units)):
            problems.append("units must be a list of strings")
        if isinstance(shape, list) and isinstance(units, list) and len(units) != len(shape):
            problems.append("units length must match shape length")
    return problems