From 5baf370cb8e77209dd45913c15c0397dce6eee65 Mon Sep 17 00:00:00 2001 From: Oleg Brutich Date: Mon, 3 Aug 2026 17:04:39 +0300 Subject: [PATCH] feat: add Toposolid script catalog --- .github/pull_request_template.md | 24 ++ .github/workflows/validate.yml | 25 ++ .gitignore | 3 + CONTRIBUTING.md | 70 +++++ README.md | 90 ++++--- catalog.json | 163 ++++++++++++ modeling/create_toposolid_from_model_lines.md | 60 +++++ modeling/create_toposolid_from_model_lines.py | 239 +++++++++++++++++ schemas/catalog.schema.json | 167 ++++++++++++ tools/validate_catalog.py | 243 ++++++++++++++++++ 10 files changed, 1038 insertions(+), 46 deletions(-) create mode 100644 .github/pull_request_template.md create mode 100644 .github/workflows/validate.yml create mode 100644 .gitignore create mode 100644 CONTRIBUTING.md create mode 100644 catalog.json create mode 100644 modeling/create_toposolid_from_model_lines.md create mode 100644 modeling/create_toposolid_from_model_lines.py create mode 100644 schemas/catalog.schema.json create mode 100644 tools/validate_catalog.py diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..6bd6b59 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,24 @@ +## What changed + + + +## User impact + + + +## Risk and scope + +- Catalog risk: +- Model changes: +- Intentional exclusions: + +## Validation + +- [ ] `python tools/validate_catalog.py` +- [ ] Tested manually in Revit + +Tested Revit versions: + +## Documentation + + diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml new file mode 100644 index 0000000..a02f29a --- /dev/null +++ b/.github/workflows/validate.yml @@ -0,0 +1,25 @@ +name: Validate script catalog + +on: + pull_request: + push: + branches: + - main + +permissions: + contents: read + +jobs: + validate: + runs-on: ubuntu-latest + steps: + - name: Check out repository + uses: actions/checkout@v7 + + - name: Set up Python + uses: actions/setup-python@v6 + with: + python-version: "3.12" + + - name: Validate catalog and script syntax + run: python tools/validate_catalog.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..98dbeb4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +__pycache__/ +*.py[cod] +.venv/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..29b1926 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,70 @@ +# Contributing scripts + +Contributions should remain easy to run manually through BIMO Run Python and predictable enough for future AI-agent discovery through BIMO MCP. + +## Add a script + +1. Choose an existing category or create a focused lowercase category folder. +2. Add a descriptively named `lower_snake_case.py` file. +3. Add a Markdown file with the same stem. +4. Register the script in `catalog.json`. +5. Run `python tools/validate_catalog.py`. +6. Describe any Revit testing performed in the pull request. Do not mark an untested version as tested. + +Existing files with historical naming are allowed to keep their paths so saved BIMO presets continue to work. + +## BIMO script contract + +New scripts should: + +- declare either `ironpython` or `dynamo-cpython3` in the catalog; +- use BIMO-provided Revit globals only when the selected engine supports them; +- read optional positional values from `IN` and document every index; +- assign a concise value to `OUT` for predictable manual and MCP results; +- validate required selection and inputs before changing the model; +- avoid modal prompts and hidden dependencies when preselection or `IN` can be used; +- open their own Revit transaction for model changes; +- roll back a started transaction when an operation fails; +- allow exceptions to reach BIMO so failed executions are not reported as successful; +- avoid secrets, credentials, machine-specific paths, and unrequested network access. + +IronPython scripts intended for BIMO may use these globals: + +| Global | Value | +| --- | --- | +| `__doc__` | Active Revit `Document` | +| `__uidoc__` | Active Revit `UIDocument` | +| `__revit__`, `__uiapp__` | Active `UIApplication` | +| `__selection__` | Active Revit selection object | +| `IN` | Positional input list | +| `OUT` | Script result assigned by the script | + +## Documentation contract + +The paired Markdown file must state: + +- purpose and expected user outcome; +- engine and minimum Revit version; +- whether the script reads, writes, or deletes model data; +- active-document and selection requirements; +- every `IN` value, type, order, and default; +- `OUT` format; +- important limitations and a manual Revit test scenario. + +## Catalog risk levels + +- `read`: inspects model state without intentionally changing it; +- `write`: creates or modifies model state; +- `destructive`: deletes elements or performs changes that are difficult to reverse. + +Risk metadata is guidance for users and agents. It does not replace BIMO authorization, code review, backups, or Revit transaction safety. + +## Validation + +Run: + +```shell +python tools/validate_catalog.py +``` + +The validator checks JSON syntax, required metadata, unique IDs and paths, paired documentation, catalog coverage for every script, and CPython-parsable syntax. It does not execute Revit API code or prove runtime compatibility. diff --git a/README.md b/README.md index 2e519a8..1d20459 100644 --- a/README.md +++ b/README.md @@ -1,68 +1,66 @@ - -![run_python_cover](https://github.com/user-attachments/assets/bfba335f-8ee6-4665-8fc6-f75f4372acd3) +![BIMO Run Python](https://github.com/user-attachments/assets/bfba335f-8ee6-4665-8fc6-f75f4372acd3) # BIMO Run Python Scripts -Welcome to the **BIMO Revit Python Scripts** repository! This repository is a collection of useful Python scripts designed to work with the **[Run Python](https://bimo.tools/tools?button=runPython)** command in the **[BIMO Add-in](https://bimo.tools)** for Autodesk Revit. The scripts aim to automate routine and complex tasks, streamlining workflows for Revit users. - -## 📋 About - -The **BIMO Add-in for Revit** includes a powerful **[Run Python](https://bimo.tools/tools?button=runPython)** command, which allows users to execute custom Python scripts within the Revit environment. This repository is intended to provide ready-to-use scripts for various tasks, along with examples to help you write your own. - -Feel free to explore the scripts, adapt them to your projects, or contribute by sharing your own scripts! - -## 🗂️ Repository Structure +Community-maintained Revit automation scripts for [BIMO Run Python](https://bimo.tools/docs/library/run-python). The repository is designed for both direct use by Revit users and machine discovery by AI agents that execute approved scripts through BIMO MCP. -The scripts in this repository are organized into categories to make it easier to find relevant code for your needs: +## Quick start -- **`wall_scripts/`**: Scripts related to wall management, such as counting walls, calculating wall areas, or modifying wall properties. -- **`door_scripts/`**: Scripts for managing doors, including swing direction checks, door schedules, and door counts. -- **`model_management/`**: Scripts to manage and optimize Revit models, like purging unused elements, auditing models, and adjusting views. -- **`room_scripts/`**: Scripts related to room management, such as calculating room volumes, adjusting room boundaries, and renaming rooms. -- **`miscellaneous/`**: Various scripts for tasks not covered in the other categories. +1. Download or clone this repository. +2. In Revit, open **BIMO > Run Python** and create a preset. +3. Select the engine declared for the script in [`catalog.json`](catalog.json). +4. Leave the inline **Script** field empty and set **Script file** to the `.py` file. +5. Add the documented `IN` values, prepare the required selection, and run the preset. -Each folder contains a README file with specific instructions on how to use the scripts in that category. +BIMO hosts the Python engine inside Revit, so users do not need a separate local Python installation just to run these scripts. Scripts that modify a model manage their own Revit transactions. -## 🛠️ How to Use the Scripts +## Script catalog -### Requirements +| Script | Category | Engine | Risk | +| --- | --- | --- | --- | +| [Create Toposolid from model lines](modeling/create_toposolid_from_model_lines.md) | Modeling | IronPython | Writes model | +| [Calculate selected lines length](miscellaneous/calculate_selected_lines_length_mm.md) | Miscellaneous | IronPython | Read-only | +| [Calculate element volume](miscellaneous/calculate_element_volume.md) | Miscellaneous | IronPython | Read-only | +| [Delete BIMO preview rays](miscellaneous/Delete_BIMO_PreviewRays_DirectShapes.md) | Miscellaneous | IronPython | Deletes elements | -- Autodesk Revit with the **BIMO Add-in** installed. -- Python installed on your system (if you plan to write your own scripts). +The authoritative machine-readable index is [`catalog.json`](catalog.json). Its contract is defined by [`schemas/catalog.schema.json`](schemas/catalog.schema.json). -### Running a Script +## Repository structure -1. Open Autodesk Revit. -2. Go to the **BIMO** tab on the Revit toolbar. -3. Click the **[Run Python](https://bimo.tools/tools?button=runPython)** button. -4. From the dropdown menu, select the Python script you want to execute (or load a new script from your computer). -5. Click **OK** to run the script and view the results. +```text +catalog.json Machine-readable script index +schemas/catalog.schema.json Catalog JSON Schema +modeling/ Model-creation and editing scripts +miscellaneous/ General-purpose scripts +tools/validate_catalog.py Dependency-free repository validator +.github/workflows/ Continuous validation +``` -### Example Scripts +Every executable script has a paired Markdown file explaining selection requirements, inputs, output, supported Revit versions, and model-change risk. Existing script paths are kept stable so saved BIMO presets do not break. -Here are some example scripts you can start with: +## Using the catalog from an AI agent -1. **Count Walls**: Counts the total number of walls in the active model. -2. **Door Swing Direction**: Checks the swing direction of all doors and stores the result in the door's parameters. -3. **Purge Unused Elements**: Cleans up the Revit model by purging unused families, materials, and styles. +An agent should: -## 🤝 Contributing +1. Filter `catalog.json` by category, tags, engine, Revit version, and risk. +2. Read the script documentation before execution. +3. Confirm required selection and inputs. +4. Treat `write` and `destructive` scripts as model-changing operations requiring explicit approval. +5. Load the exact file referenced by `path` and execute it through the supported BIMO Run Python or MCP operation. +6. Return the script's `OUT` value or execution error without claiming success before Revit confirms it. -We welcome contributions from the community! If you have a useful script that you'd like to share, please follow these steps: +The catalog helps discovery; it is not an execution allowlist or a security boundary. Review scripts before running them and use a test model for model-changing operations. -1. Fork the repository. -2. Create a new branch (`git checkout -b your-feature-branch`). -3. Add your script in the appropriate folder. -4. Commit your changes (`git commit -m 'Add new Python script'`). -5. Push to the branch (`git push origin your-feature-branch`). -6. Open a pull request and provide a brief description of your script. +## Contributing -## 💬 Support +See [CONTRIBUTING.md](CONTRIBUTING.md) for the script contract and submission checklist. Validate changes locally with: -If you encounter any issues or have questions about the scripts, feel free to open an issue in the GitHub repository or reach out to the community for support. +```shell +python tools/validate_catalog.py +``` -For more information on the **BIMO Add-in**, visit the [BIMO Tools website](https://bimo.tools). +The same check runs in GitHub Actions. -## 📜 License +## License -This repository is licensed under the [MIT License](LICENSE). +Distributed under the [MIT License](LICENSE). diff --git a/catalog.json b/catalog.json new file mode 100644 index 0000000..52e5380 --- /dev/null +++ b/catalog.json @@ -0,0 +1,163 @@ +{ + "$schema": "schemas/catalog.schema.json", + "version": 1, + "scripts": [ + { + "id": "modeling.create-toposolid-from-model-lines", + "name": "Create Toposolid from model lines", + "summary": "Samples selected model curves and creates a point-based Toposolid from their XYZ elevations.", + "category": "modeling", + "path": "modeling/create_toposolid_from_model_lines.py", + "documentation": "modeling/create_toposolid_from_model_lines.md", + "engine": "ironpython", + "revit": { + "minimum": 2024, + "tested": [] + }, + "risk": "write", + "requiresActiveDocument": true, + "selection": { + "required": true, + "description": "Three or more non-collinear XYZ points sampled from selected ModelCurve elements." + }, + "inputs": [ + { + "index": 0, + "name": "sampling_step_mm", + "type": "number-string", + "required": false, + "default": "1000", + "description": "Approximate sampling interval along each selected curve, in millimetres." + }, + { + "index": 1, + "name": "xy_tolerance_mm", + "type": "number-string", + "required": false, + "default": "1", + "description": "XY tolerance used to merge duplicate sampled points, in millimetres." + }, + { + "index": 2, + "name": "toposolid_type_name", + "type": "string", + "required": false, + "default": "", + "description": "Exact Toposolid type name. The first type alphabetically is used when omitted." + }, + { + "index": 3, + "name": "level_name", + "type": "string", + "required": false, + "default": "", + "description": "Exact level name. The active view level or nearest level is used when omitted." + } + ], + "output": { + "format": "text", + "description": "Created element ID and a summary of the sampled geometry, type, level, and Z range." + }, + "tags": [ + "site", + "terrain", + "topography", + "toposolid", + "model-curves", + "selection" + ] + }, + { + "id": "miscellaneous.calculate-selected-lines-length-mm", + "name": "Calculate selected lines length in millimetres", + "summary": "Calculates the total length of selected curve elements and prints millimetres.", + "category": "miscellaneous", + "path": "miscellaneous/calculate_selected_lines_length_mm.py", + "documentation": "miscellaneous/calculate_selected_lines_length_mm.md", + "engine": "ironpython", + "revit": { + "minimum": 2024, + "tested": [] + }, + "risk": "read", + "requiresActiveDocument": true, + "selection": { + "required": true, + "description": "One or more CurveElement instances. Non-curve elements are ignored." + }, + "inputs": [], + "output": { + "format": "text", + "description": "Total selected curve length in millimetres." + }, + "tags": [ + "curves", + "length", + "measurement", + "selection" + ] + }, + { + "id": "miscellaneous.calculate-element-volume", + "name": "Calculate element volume", + "summary": "Calculates solid volumes for selected family instances and prints cubic metres.", + "category": "miscellaneous", + "path": "miscellaneous/calculate_element_volume.py", + "documentation": "miscellaneous/calculate_element_volume.md", + "engine": "ironpython", + "revit": { + "minimum": 2024, + "tested": [] + }, + "risk": "read", + "requiresActiveDocument": true, + "selection": { + "required": true, + "description": "One or more FamilyInstance elements with valid solid geometry." + }, + "inputs": [], + "output": { + "format": "text", + "description": "A list containing cubic-metre volumes or per-element error messages." + }, + "tags": [ + "family-instance", + "geometry", + "measurement", + "selection", + "volume" + ] + }, + { + "id": "miscellaneous.delete-bimo-preview-rays-direct-shapes", + "name": "Delete BIMO preview rays", + "summary": "Deletes DirectShape elements whose ApplicationId is BIMO_PreviewRays.", + "category": "miscellaneous", + "path": "miscellaneous/Delete_BIMO_PreviewRays_DirectShapes.py", + "documentation": "miscellaneous/Delete_BIMO_PreviewRays_DirectShapes.md", + "engine": "ironpython", + "revit": { + "minimum": 2024, + "tested": [] + }, + "risk": "destructive", + "requiresActiveDocument": true, + "selection": { + "required": false, + "description": "No selection is required; all matching DirectShape elements in the active document are deleted." + }, + "inputs": [], + "output": { + "format": "text", + "description": "Number of deleted DirectShape elements, or a message when no match exists." + }, + "tags": [ + "bimo", + "cleanup", + "delete", + "direct-shape", + "preview-rays" + ] + } + ] +} diff --git a/modeling/create_toposolid_from_model_lines.md b/modeling/create_toposolid_from_model_lines.md new file mode 100644 index 0000000..1b234f8 --- /dev/null +++ b/modeling/create_toposolid_from_model_lines.md @@ -0,0 +1,60 @@ +# Create Toposolid from model lines + +Creates a point-based Revit `Toposolid` by sampling the elevations of selected model curves. + +## Compatibility + +- BIMO engine: `IronPython` +- Minimum Revit version: 2024 +- Active project document required +- Model-changing operation: yes +- Tested Revit versions: not yet recorded + +`Toposolid` was introduced in Revit 2024. This script does not provide a `TopographySurface` fallback for older Revit versions. + +## Before running + +1. Create model lines at the real Z elevations of the site contours. +2. Select the model lines. Detail lines and imported CAD elements are ignored. +3. Open a plan or 3D view associated with the intended level, or provide a level name in `IN[3]`. +4. Run the script through BIMO Run Python with the inline **Script** field empty. + +The selected curves do not have to form a closed boundary. The script samples points along them and lets Revit triangulate the resulting point cloud. + +## Inputs + +BIMO passes `IN` values as strings. All inputs are optional and positional. + +| Index | Meaning | Default | +| --- | --- | --- | +| `IN[0]` | Sampling step in millimetres | `1000` | +| `IN[1]` | XY tolerance for merging duplicate points, in millimetres | `1` | +| `IN[2]` | Exact `ToposolidType` name | First type alphabetically | +| `IN[3]` | Exact `Level` name | Active view level, otherwise nearest level | + +A smaller sampling step creates more points and may produce a more detailed but heavier Toposolid. + +## Processing + +The script: + +1. accepts selected `ModelCurve` elements; +2. samples every curve at approximately the configured interval; +3. merges points whose XY coordinates fall within the configured tolerance; +4. averages XYZ coordinates within each duplicate bucket; +5. rejects point sets with fewer than three unique XY locations or a collinear XY extent; +6. stops before creation when sampling would exceed the 50,000-point safety limit; +7. creates the Toposolid in a dedicated Revit transaction; +8. rolls the transaction back if creation fails. + +## Output + +On success, `OUT` contains the created element ID, curve and point counts, ignored selection count, chosen type and level, and elevation range in metres. Validation and Revit API failures are returned by BIMO as execution errors. + +## Limitations and safety + +- This creates a point-based Toposolid, not a user-defined closed sketch boundary. +- Coincident XY points are averaged, including their Z values. +- The result depends on Revit's triangulation of the sampled points. +- Very small sampling steps can create excessive geometry and slow down the model. +- Run model-changing scripts on a test copy before using them in production. diff --git a/modeling/create_toposolid_from_model_lines.py b/modeling/create_toposolid_from_model_lines.py new file mode 100644 index 0000000..e232181 --- /dev/null +++ b/modeling/create_toposolid_from_model_lines.py @@ -0,0 +1,239 @@ +"""Create a Revit Toposolid from points sampled along selected model curves. + +BIMO Run Python contract: +- Engine: IronPython +- IN[0]: sampling step in millimetres (optional, default: 1000) +- IN[1]: XY duplicate tolerance in millimetres (optional, default: 1) +- IN[2]: exact Toposolid type name (optional) +- IN[3]: exact level name (optional) +- OUT: human-readable result +""" + +import math + +from Autodesk.Revit.DB import ( + FilteredElementCollector, + Level, + ModelCurve, + Toposolid, + ToposolidType, + Transaction, + XYZ, +) +from System.Collections.Generic import List + + +MILLIMETRES_PER_FOOT = 304.8 +MAXIMUM_SAMPLED_POINTS = 50000 + + +def _input(index, default_value=None): + if index >= len(IN): + return default_value + + value = IN[index] + if value is None or str(value).strip() == "": + return default_value + + return value + + +def _positive_float(value, input_name): + try: + number = float(str(value).replace(",", ".")) + except (TypeError, ValueError): + raise ValueError("{0} must be a number.".format(input_name)) + + if number <= 0: + raise ValueError("{0} must be greater than zero.".format(input_name)) + + return number + + +def _sample_curve(curve, step_feet, maximum_points): + try: + segment_count = max(1, int(math.ceil(curve.Length / step_feet))) + if segment_count + 1 > maximum_points: + raise ValueError( + "Sampling would exceed the {0}-point safety limit. Increase IN[0].".format( + MAXIMUM_SAMPLED_POINTS + ) + ) + return [ + curve.Evaluate(float(index) / float(segment_count), True) + for index in range(segment_count + 1) + ] + except ValueError: + raise + except Exception: + points = list(curve.Tessellate()) + if len(points) > maximum_points: + raise ValueError( + "Tessellation would exceed the {0}-point safety limit.".format( + MAXIMUM_SAMPLED_POINTS + ) + ) + return points + + +def _deduplicate_xy(points, tolerance_feet): + buckets = {} + + for point in points: + key = ( + int(round(point.X / tolerance_feet)), + int(round(point.Y / tolerance_feet)), + ) + + if key not in buckets: + buckets[key] = [point.X, point.Y, point.Z, 1] + continue + + bucket = buckets[key] + bucket[0] += point.X + bucket[1] += point.Y + bucket[2] += point.Z + bucket[3] += 1 + + unique_points = [] + for key in sorted(buckets.keys()): + x_sum, y_sum, z_sum, count = buckets[key] + unique_points.append(XYZ(x_sum / count, y_sum / count, z_sum / count)) + + return unique_points + + +def _element_by_name(elements, requested_name, element_kind): + if requested_name: + normalized_name = requested_name.lower() + for element in elements: + if str(element.Name).lower() == normalized_name: + return element + + raise ValueError( + "{0} named '{1}' was not found.".format(element_kind, requested_name) + ) + + if not elements: + raise ValueError("No {0} is available in the active project.".format(element_kind)) + + return sorted(elements, key=lambda element: str(element.Name).lower())[0] + + +def _resolve_level(doc, requested_name, minimum_z): + levels = list(FilteredElementCollector(doc).OfClass(Level)) + + if requested_name: + return _element_by_name(levels, requested_name, "Level") + + active_view = doc.ActiveView + if active_view is not None and active_view.GenLevel is not None: + return active_view.GenLevel + + if not levels: + raise ValueError("No Level is available in the active project.") + + return min(levels, key=lambda level: abs(level.Elevation - minimum_z)) + + +def _create_toposolid(): + step_mm = _positive_float(_input(0, 1000.0), "IN[0] sampling step") + tolerance_mm = _positive_float(_input(1, 1.0), "IN[1] XY tolerance") + requested_type_name = str(_input(2, "")).strip() + requested_level_name = str(_input(3, "")).strip() + + selected_ids = list(__selection__.GetElementIds()) + if not selected_ids: + raise ValueError( + "Select model lines with real Z elevations before running this script." + ) + + curves = [] + ignored_count = 0 + for element_id in selected_ids: + element = __doc__.GetElement(element_id) + if isinstance(element, ModelCurve) and element.GeometryCurve is not None: + curves.append(element.GeometryCurve) + else: + ignored_count += 1 + + if not curves: + raise ValueError( + "The selection contains no model curves. Detail lines and imported CAD " + "geometry are not supported." + ) + + step_feet = step_mm / MILLIMETRES_PER_FOOT + tolerance_feet = tolerance_mm / MILLIMETRES_PER_FOOT + + sampled_points = [] + for curve in curves: + remaining_capacity = MAXIMUM_SAMPLED_POINTS - len(sampled_points) + if remaining_capacity < 2: + raise ValueError( + "Sampling would exceed the {0}-point safety limit. Increase IN[0].".format( + MAXIMUM_SAMPLED_POINTS + ) + ) + sampled_points.extend(_sample_curve(curve, step_feet, remaining_capacity)) + + points = _deduplicate_xy(sampled_points, tolerance_feet) + if len(points) < 3: + raise ValueError("At least three unique XY points are required.") + + min_x = min(point.X for point in points) + max_x = max(point.X for point in points) + min_y = min(point.Y for point in points) + max_y = max(point.Y for point in points) + min_z = min(point.Z for point in points) + max_z = max(point.Z for point in points) + + if max_x - min_x < tolerance_feet or max_y - min_y < tolerance_feet: + raise ValueError( + "The sampled points are collinear in XY. A Toposolid requires an area." + ) + + toposolid_types = list(FilteredElementCollector(__doc__).OfClass(ToposolidType)) + toposolid_type = _element_by_name( + toposolid_types, requested_type_name, "Toposolid type" + ) + level = _resolve_level(__doc__, requested_level_name, min_z) + + net_points = List[XYZ]() + for point in points: + net_points.Add(point) + + transaction = Transaction(__doc__, "Create Toposolid from selected model lines") + started = False + try: + transaction.Start() + started = True + toposolid = Toposolid.Create( + __doc__, net_points, toposolid_type.Id, level.Id + ) + transaction.Commit() + started = False + except Exception: + if started: + try: + transaction.RollBack() + except Exception: + pass + raise + + return ( + "Toposolid created. Id: {0}; curves: {1}; points: {2}; ignored " + "elements: {3}; type: {4}; level: {5}; Z range: {6:.3f}-{7:.3f} m." + ).format( + toposolid.Id, + len(curves), + len(points), + ignored_count, + toposolid_type.Name, + level.Name, + min_z * 0.3048, + max_z * 0.3048, + ) + + +OUT = _create_toposolid() diff --git a/schemas/catalog.schema.json b/schemas/catalog.schema.json new file mode 100644 index 0000000..20f1b1f --- /dev/null +++ b/schemas/catalog.schema.json @@ -0,0 +1,167 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/BIMO-Tools/Revit-Python-Scripts/blob/main/schemas/catalog.schema.json", + "title": "BIMO Run Python script catalog", + "type": "object", + "additionalProperties": false, + "required": ["$schema", "version", "scripts"], + "properties": { + "$schema": { + "type": "string" + }, + "version": { + "const": 1 + }, + "scripts": { + "type": "array", + "minItems": 1, + "items": { + "$ref": "#/$defs/script" + } + } + }, + "$defs": { + "script": { + "type": "object", + "additionalProperties": false, + "required": [ + "id", + "name", + "summary", + "category", + "path", + "documentation", + "engine", + "revit", + "risk", + "requiresActiveDocument", + "selection", + "inputs", + "output", + "tags" + ], + "properties": { + "id": { + "type": "string", + "pattern": "^[a-z0-9]+(?:[.-][a-z0-9]+)*$" + }, + "name": { + "type": "string", + "minLength": 1 + }, + "summary": { + "type": "string", + "minLength": 1 + }, + "category": { + "type": "string", + "pattern": "^[a-z][a-z0-9-]*$" + }, + "path": { + "type": "string", + "pattern": "^[^\\\\]+\\.py$" + }, + "documentation": { + "type": "string", + "pattern": "^[^\\\\]+\\.md$" + }, + "engine": { + "enum": ["ironpython", "dynamo-cpython3"] + }, + "revit": { + "type": "object", + "additionalProperties": false, + "required": ["minimum", "tested"], + "properties": { + "minimum": { + "type": "integer", + "minimum": 2024 + }, + "tested": { + "type": "array", + "uniqueItems": true, + "items": { + "type": "integer", + "minimum": 2024 + } + } + } + }, + "risk": { + "enum": ["read", "write", "destructive"] + }, + "requiresActiveDocument": { + "type": "boolean" + }, + "selection": { + "type": "object", + "additionalProperties": false, + "required": ["required", "description"], + "properties": { + "required": { + "type": "boolean" + }, + "description": { + "type": "string", + "minLength": 1 + } + } + }, + "inputs": { + "type": "array", + "items": { + "$ref": "#/$defs/input" + } + }, + "output": { + "type": "object", + "additionalProperties": false, + "required": ["format", "description"], + "properties": { + "format": { + "enum": ["text", "json", "object"] + }, + "description": { + "type": "string", + "minLength": 1 + } + } + }, + "tags": { + "type": "array", + "uniqueItems": true, + "items": { + "type": "string", + "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$" + } + } + } + }, + "input": { + "type": "object", + "additionalProperties": false, + "required": ["index", "name", "type", "required", "description"], + "properties": { + "index": { + "type": "integer", + "minimum": 0 + }, + "name": { + "type": "string", + "pattern": "^[a-z][a-z0-9_]*$" + }, + "type": { + "enum": ["string", "number-string", "integer-string", "boolean-string", "json-string"] + }, + "required": { + "type": "boolean" + }, + "default": {}, + "description": { + "type": "string", + "minLength": 1 + } + } + } + } +} diff --git a/tools/validate_catalog.py b/tools/validate_catalog.py new file mode 100644 index 0000000..4011264 --- /dev/null +++ b/tools/validate_catalog.py @@ -0,0 +1,243 @@ +"""Validate the BIMO Run Python script catalog without third-party packages.""" + +from __future__ import annotations + +import json +import sys +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[1] +CATALOG_PATH = ROOT / "catalog.json" + +SCRIPT_FIELDS = { + "id", + "name", + "summary", + "category", + "path", + "documentation", + "engine", + "revit", + "risk", + "requiresActiveDocument", + "selection", + "inputs", + "output", + "tags", +} +ENGINES = {"ironpython", "dynamo-cpython3"} +RISKS = {"read", "write", "destructive"} +OUTPUT_FORMATS = {"text", "json", "object"} +INPUT_TYPES = { + "string", + "number-string", + "integer-string", + "boolean-string", + "json-string", +} + + +def load_json(path: Path, errors: list[str]): + try: + return json.loads(path.read_text(encoding="utf-8-sig")) + except (OSError, json.JSONDecodeError) as exception: + errors.append(f"{path.relative_to(ROOT)}: {exception}") + return None + + +def repository_path(value: object, field: str, script_id: str, errors: list[str]): + if not isinstance(value, str) or not value: + errors.append(f"{script_id}: {field} must be a non-empty string") + return None + + path = Path(value) + if path.is_absolute() or ".." in path.parts or "\\" in value: + errors.append(f"{script_id}: {field} must be a repository-relative POSIX path") + return None + + return ROOT / path + + +def validate_inputs(script_id: str, inputs: object, errors: list[str]) -> None: + if not isinstance(inputs, list): + errors.append(f"{script_id}: inputs must be an array") + return + + indexes = [] + for input_value in inputs: + if not isinstance(input_value, dict): + errors.append(f"{script_id}: every input must be an object") + continue + + required = {"index", "name", "type", "required", "description"} + missing = required - input_value.keys() + if missing: + errors.append(f"{script_id}: input is missing {sorted(missing)}") + + index = input_value.get("index") + if not isinstance(index, int) or index < 0: + errors.append(f"{script_id}: input index must be a non-negative integer") + else: + indexes.append(index) + + if input_value.get("type") not in INPUT_TYPES: + errors.append(f"{script_id}: unsupported input type {input_value.get('type')!r}") + + if not isinstance(input_value.get("required"), bool): + errors.append(f"{script_id}: input required must be boolean") + + if indexes != list(range(len(indexes))): + errors.append(f"{script_id}: input indexes must be contiguous and ordered from zero") + + +def validate_script(script: object, seen_ids: set[str], seen_paths: set[str], errors: list[str]): + if not isinstance(script, dict): + errors.append("Every scripts entry must be an object") + return + + script_id = script.get("id", "") + missing = SCRIPT_FIELDS - script.keys() + extra = script.keys() - SCRIPT_FIELDS + if missing: + errors.append(f"{script_id}: missing fields {sorted(missing)}") + if extra: + errors.append(f"{script_id}: unknown fields {sorted(extra)}") + + if not isinstance(script_id, str) or not script_id: + errors.append("Script id must be a non-empty string") + elif script_id in seen_ids: + errors.append(f"Duplicate script id: {script_id}") + else: + seen_ids.add(script_id) + + if script.get("engine") not in ENGINES: + errors.append(f"{script_id}: unsupported engine {script.get('engine')!r}") + if script.get("risk") not in RISKS: + errors.append(f"{script_id}: unsupported risk {script.get('risk')!r}") + if not isinstance(script.get("requiresActiveDocument"), bool): + errors.append(f"{script_id}: requiresActiveDocument must be boolean") + + category = script.get("category") + script_path = repository_path(script.get("path"), "path", script_id, errors) + documentation_path = repository_path( + script.get("documentation"), "documentation", script_id, errors + ) + + if script_path is not None: + relative_path = script_path.relative_to(ROOT).as_posix() + if relative_path in seen_paths: + errors.append(f"Duplicate script path: {relative_path}") + else: + seen_paths.add(relative_path) + + if script_path.suffix != ".py": + errors.append(f"{script_id}: path must end with .py") + if not script_path.is_file(): + errors.append(f"{script_id}: script file does not exist: {relative_path}") + if script_path.parts[-2] != category: + errors.append(f"{script_id}: category must match the script directory") + + if documentation_path is not None: + if documentation_path.suffix != ".md": + errors.append(f"{script_id}: documentation must end with .md") + if not documentation_path.is_file(): + errors.append( + f"{script_id}: documentation file does not exist: " + f"{documentation_path.relative_to(ROOT).as_posix()}" + ) + if script_path is not None and documentation_path.stem != script_path.stem: + errors.append(f"{script_id}: script and documentation stems must match") + + revit = script.get("revit") + if not isinstance(revit, dict): + errors.append(f"{script_id}: revit must be an object") + else: + minimum = revit.get("minimum") + tested = revit.get("tested") + if not isinstance(minimum, int) or minimum < 2024: + errors.append(f"{script_id}: revit.minimum must be an integer >= 2024") + if not isinstance(tested, list) or any(not isinstance(v, int) for v in tested): + errors.append(f"{script_id}: revit.tested must be an integer array") + elif isinstance(minimum, int) and any(v < minimum for v in tested): + errors.append(f"{script_id}: tested versions cannot precede revit.minimum") + + selection = script.get("selection") + if not isinstance(selection, dict): + errors.append(f"{script_id}: selection must be an object") + elif not isinstance(selection.get("required"), bool) or not selection.get("description"): + errors.append(f"{script_id}: selection requires boolean required and description") + + validate_inputs(script_id, script.get("inputs"), errors) + + output = script.get("output") + if not isinstance(output, dict): + errors.append(f"{script_id}: output must be an object") + elif output.get("format") not in OUTPUT_FORMATS or not output.get("description"): + errors.append(f"{script_id}: output requires a supported format and description") + + tags = script.get("tags") + if not isinstance(tags, list) or any(not isinstance(tag, str) for tag in tags): + errors.append(f"{script_id}: tags must be a string array") + elif len(tags) != len(set(tags)): + errors.append(f"{script_id}: tags must be unique") + + +def validate_python(path: Path, errors: list[str]) -> None: + try: + source = path.read_text(encoding="utf-8-sig") + compile(source, str(path), "exec") + except (OSError, SyntaxError) as exception: + errors.append(f"{path.relative_to(ROOT).as_posix()}: {exception}") + + +def main() -> int: + errors: list[str] = [] + catalog = load_json(CATALOG_PATH, errors) + load_json(ROOT / "schemas" / "catalog.schema.json", errors) + + if not isinstance(catalog, dict): + scripts = [] + else: + if catalog.get("version") != 1: + errors.append("catalog.json: version must be 1") + if catalog.get("$schema") != "schemas/catalog.schema.json": + errors.append("catalog.json: $schema must reference schemas/catalog.schema.json") + scripts = catalog.get("scripts") + if not isinstance(scripts, list) or not scripts: + errors.append("catalog.json: scripts must be a non-empty array") + scripts = [] + + seen_ids: set[str] = set() + seen_paths: set[str] = set() + for script in scripts: + validate_script(script, seen_ids, seen_paths, errors) + + repository_scripts = { + path.relative_to(ROOT).as_posix() + for path in ROOT.rglob("*.py") + if path.relative_to(ROOT).parts[0] != "tools" + } + + uncatalogued = repository_scripts - seen_paths + missing_from_disk = seen_paths - repository_scripts + if uncatalogued: + errors.append(f"Uncatalogued scripts: {sorted(uncatalogued)}") + if missing_from_disk: + errors.append(f"Catalog paths missing from disk: {sorted(missing_from_disk)}") + + for path in sorted(repository_scripts | {"tools/validate_catalog.py"}): + validate_python(ROOT / path, errors) + + if errors: + print("Catalog validation failed:") + for error in errors: + print(f"- {error}") + return 1 + + print(f"Catalog validation passed for {len(scripts)} scripts.") + return 0 + + +if __name__ == "__main__": + sys.exit(main())