Export and validation¶
export_menus() writes menus as PME’s JSON document. The validation
functions check a document against the bundled JSON Schema v2 and PME’s UID
rules, without changing or running it.
Function |
Purpose |
|---|---|
Exports menus as a JSON document, optionally to a file. |
|
Validates a JSON string. Returns
|
|
Validates already-parsed JSON data. |
|
Validates a UTF-8 JSON file. |
|
Checks the format of a menu UID. Described in Execution, user properties and identity. |
Export¶
Export menus as PME’s JSON document.
The exporter and file writer are those of the Export Menus dialog. The selected menu, Select Mode and the list filters are neither read nor changed.
- Parameters:
pm_uids (iterable of str or None) – UIDs of the menus to export, as a non-string iterable.
Noneexports every menu.include_referenced_menus (bool) – Also export the menus that the named menus refer to. See Referenced menus. No effect when
pm_uidsisNone.export_tags (bool) – Include tag names, tag UIDs and the tag registry.
filepath (str or None) – File to write the JSON text to.
.jsonis appended when the path does not end in.json(case-sensitive). An existing file is replaced.
- Returns:
The result described below.
- Return type:
- Raises:
TypeError –
pm_uidsis a string, bytes or not iterable;include_referenced_menusorexport_tagsis not a bool; orfilepathis not a non-empty string.ValueError –
pm_uidsis empty, a UID in it is rejected, or the data cannot be exported. See Errors.RuntimeError – Called off Blender’s main thread (
"Menu export requires Blender's main thread"), while PME runs its startup scripts ("Menu export requires PME to finish loading"), or whilepreferencesisNone("PME preferences are unavailable").KeyError –
ADDON_IDis not inbpy.context.preferences.addons, as forpreferences.OSError – The file cannot be written, for example
FileNotFoundErrorwhen its directory does not exist.
Result
Key
Type
Value
datadict
The document. See Exported document.
textstr
The exact JSON text of
data, as written to the file.pm_uidslist[str]
UIDs of the exported menus, in document order.
warningslist[str]
Problems that did not stop the export. See Warnings.
filepathstr or None
The path of the written file, including an appended
.json.Nonewhenfilepathwas not given.Errors
Every error is a
ValueError. Thepm_uidschecks run in the given order and name the first UID that fails.Message
Cause
pm_uids must name at least one menu; pass None to export allpm_uidsis empty.Menu UID is invalid: <uid>Not a menu UID in the format
validate_uid()accepts. The UID is shown withrepr().Menu UID is listed more than once in pm_uids: <uid>The UID appears twice in
pm_uids.Menu UID is missing: <uid>No saved menu has the UID.
Menu UID is ambiguous: <n> saved menus share <uid>Several saved menus have the UID.
PME: Context Router logic export failed for menu '<name>': <source> refers to <target>, which is outside the exported menu setA Context Router’s target menu is not exported.
<source>isbranch '<label>',otherwise '<label>'orcondition '<label>'.<target>ismenu '<current name>', ora menu that is not in Preferences (UID <uid>).PME: Context Router logic export failed for menu '<name>': <codes>The Context Router’s saved logic cannot be read or exported.
PME: <mode> export requires at most <n> slots: <name>A menu type with a fixed number of slots has more slots.
PME: Export blocked by invalid menu identity (<reason>, count=<n>)The saved menus fail PME’s menu identity check, such as a missing, invalid or duplicated menu UID.
<reason>names the check.A tag registry code, such as
tag_registry_export_plan_failedThe tag registry cannot be exported.
The data errors (Context Router and slot count) are
ExportDataError. An error raised after warnings were collected is anExportErrorwhosewarningsattribute holds them. Both classes subclassValueErrorand are not exported bypme; read the warnings withgetattr(error, "warnings", ()).Warnings
Message
Cause
PME: <n> Command/Custom slot(s) call menus that could not be resolved, so those menus were not included: <slots>A Command or Custom slot calls a menu that cannot be identified. Reason per slot:
menu not found,duplicate menu nameortarget not static.PME: <n> Command/Custom slot(s) reference properties that could not be resolved, so those properties were not included: <slots>A
props()reference in a Command or Custom slot cannot be identified. Reason per slot:prop id not found,display name ambiguousortarget not static.PME: Property Stack logic omitted for menu '<name>': <codes>The saved logic cannot be read. The menu is exported without it.
PME: Property Stack logic repaired for menu '<name>': <codes>The saved logic was read after normalization.
<slots>lists up to 10 slots as'<menu>' slot <position> '<slot name>' (<reasons>), thenand <n> more. The two slot warnings are produced only withpm_uidsandinclude_referenced_menus=True.Example
result = pme.export_menus([pm_uid], filepath="C:/exports/shading_pie") print(result["filepath"], result["pm_uids"], result["warnings"])
Notes
A Context Router’s target is exported when
include_referenced_menusisTrueor when its UID is inpm_uids; then the “outside the exported menu set” error does not occur for it.Before the export, a slot of an exported menu whose slot UID is missing, invalid or used twice in that menu receives a new UID. The new UID is kept in the saved menu.
Menus are written in the order of the menu list, not in the order of
pm_uids. The developer option Sort Exported Menus by Name sorts them by name.
Exported document¶
The document follows JSON Schema v2. Hotkeys of the exported menus are part of it. Script files that slots call are not; a recipient needs them as separate files.
Key |
Value |
|---|---|
|
|
|
|
|
PME version, such as |
|
UTC time of the export, such as |
|
One object per menu: |
|
|
|
All tag names used by the exported menus, when |
hotkey holds key, ctrl, shift, alt, oskey, any,
key_mod, chord, keymaps, activation and drag_direction, plus
repeat and tweak_direction when set.
Validation¶
valid=True means that the requested checks passed. It does not guarantee
that an import succeeds in the current Blender setup or that the stored
commands run.
Validation stages¶
Text (
validate_json()only). An empty or whitespace-only string, orNone, givesE102. Text that is not JSON givesE101.Root. An empty or false value (
{},[],"",0,null) givesE102. An object with$schemaorschema_versionis checked as Schema v2 (stages 3 to 5). A list, or an object with amenuslist and aversionstring of dot-separated integers such as"1.18.7", is a PME1 document: the result has warningW301and no further check runs. Anything else givesE206.Schema. The document is checked against the bundled schema
pme2-2.0.json. One failure is reported per call. When the failure is a missing required field, each missing field of that object is an issue with the same message. Failures of type and required fields are reported before failures of conditional rules. The next failure appears after the first is fixed.UIDs. Runs when the schema check passes. Menu UIDs must be valid and match the menu’s
mode, and must be unique in the document. Slot UIDs must be valid and unique within their menu. Several issues can be reported.References. Runs after the UID stage when
check_referencesisTrue. Several issues can be reported.A Menu slot whose target is a menu UID must find that UID in the same document. A target given as a name is not checked.
The logic of a Property Stack (
CONDITION) or Context Router (ROUTER) is decoded, and the menu UIDs it depends on must be in the same document. ACONDITIONwithout logic is skipped.
With strict=True, a result with any warning has valid=False. The
warnings stay in warnings.
- pme.validate_json(json_string, *, strict=False, check_references=True)¶
Validate a PME JSON document given as text.
The same function is
pme.validation.validate_json. The document is read only: it is not changed, its Python code is not run, and its$schemaURL is not downloaded.- Parameters:
json_string (str, bytes, bytearray or None) – The JSON text.
bytesandbytearrayare read asjson.loads()reads them.Nonecounts as empty text.strict (bool) – Make any warning invalidate the result.
check_references (bool) – Run the reference stage.
Falseskips it; the schema and UID stages still run.
- Returns:
The issues found and the document’s metadata.
- Return type:
- Raises:
TypeError –
json_stringis of another type, such as anintor an already-parseddict. The message names the type, for example"json_string must be str, bytes, bytearray or None, not dict". Validate parsed data withpme.validation.validate().
Example
result = pme.validate_json(pme.export_menus([pm_uid])["text"]) if not result.valid: print(result.format_report())
Notes
Problems in the document are returned as issues, not raised.
check_references=Falsefits a document whose target menus are supplied in another document, such as part of an export.Legacy name references and Blender menu type names are not resolved against the running Blender session.
W301means that the item contents and name references of the PME1 document have not been validated against Schema v2. Import has its own checks.The Extension bundles fastjsonschema 2.22.2. Blender can already have loaded its own 2.21 in the same Python process, so the version in use can differ. Validation uses their shared API and does not replace the loaded library.
- pme.validation.validate(data, *, strict=False, check_references=True)¶
Validate already-parsed JSON data.
Starts at the Root stage.
datais not changed.- Parameters:
- Returns:
The issues found and the document’s metadata.
- Return type:
- pme.validation.validate_file(filepath, *, strict=False, check_references=True)¶
Read a UTF-8 JSON file and validate its text as
pme.validate_json()does.- Parameters:
- Returns:
The issues found and the document’s metadata.
- Return type:
Notes
A file that cannot be read gives
E101with the message"File not found: <path>","Permission denied: <path>"or"Failed to read file: <error>". A file that is not UTF-8 gives the last form. Nothing is raised.
- pme.validation.ERROR_CODES: dict[str, str]¶
Issue code mapped to a short description. Lists the codes in Issue codes: every code the validator returns.
- class pme.validation.ValidationResult¶
Result of the validation functions. A dataclass, also available as
pme.types.ValidationResult.Attribute
Type
Value
validbool
Truewhenerrorsis empty, and withstrict=Truealsowarnings.errorslist[ValidationIssue]
Issues with severity
"error".warningslist[ValidationIssue]
Issues with severity
"warning". Kept whenstrict=Truemakes the result invalid.schema_versionstr or None
The document’s
schema_versionwhen it is a string; otherwiseNone, including for a PME1 document.menu_countint
Length of the document’s
menuslist, also when the document is invalid. 0 when there is no list.has_warningsbool
Read-only.
Truewhenwarningsis not empty.issue_countint
Read-only. Number of errors plus warnings.
- format_report(*, include_warnings=True, max_issues=50)¶
Return the result as readable text.
- Parameters:
- Returns:
Lines of text. The first line is
âś“ Valid (<n> menus), followed bySchema version: <version>, orâś— Invalid (<n> errors). The issues follow underErrors:andWarnings:, one per line as[<code>] <path>: <message>, and... and <n> more errorswhenmax_issuesis reached.- Return type:
- class pme.validation.ValidationIssue¶
One issue. A dataclass, also available as
pme.types.ValidationIssue.Attribute
Type
Value
severitystr
"error"or"warning".codestr
See Issue codes.
pathstr
Location in the document, such as
menus[0].items[0].action.value.""for the document as a whole.messagestr
Description. Schema issues carry the schema library’s message, such as
data must contain ['addon_version'] properties.suggestionstr or None
Nonein the issues the current validator returns.ValidationIssue(severity='error', code='E601', path='menus[0].items[0].action.value', message='PM UID reference is not present in this document: rm_6sshkekp', suggestion=None)
Issue codes¶
menus[i] is a menu and items[j] one of its slots.
|
Stage |
|
Cause |
|---|---|---|---|
|
Text |
|
Not JSON: |
|
Text, Root |
|
Empty text ( |
|
Root, Schema |
|
The root is not a recognized document; the message names the problem,
such as |
|
Schema |
|
|
|
Schema |
|
|
|
Schema |
|
|
|
Schema |
|
|
|
Schema |
|
|
|
Schema |
|
A required |
|
Schema, UIDs |
|
The UID fails the schema; or it is not a valid UID
( |
|
UIDs |
|
|
|
Schema |
|
|
|
Schema |
|
|
|
Schema |
|
|
|
Schema |
|
|
|
Schema |
|
|
|
Schema |
|
|
|
Schema |
|
|
|
Schema |
|
|
|
References |
|
|
|
References |
|
The logic cannot be decoded:
|
|
References |
|
Decoding the logic needed normalization. One warning per diagnostic
code: |
|
Root |
|
A PME1 document was recognized. Its contents were not validated. |