mirror of
https://github.com/IfcOpenShell/IfcOpenShell.git
synced 2026-09-25 08:52:27 +00:00
ifcquery/ifcedit: enable shell scripting by composing query and edit commands
Add --format ids to ifcquery to output step IDs suitable for piping into ifcedit parameters. Add ifcedit foreach to apply an operation to every element in a query result. Extend clash and relations output so --format ids extracts all involved element IDs, enabling one-liners like clash detection piped directly into render. Generated with the assistance of an AI coding tool.
This commit is contained in:
@@ -28,6 +28,7 @@ import ifcopenshell
|
||||
from ifcedit.discover import function_docs, list_functions, list_modules
|
||||
from ifcedit.quantify import list_rules, run_quantify
|
||||
from ifcedit.run import run_api
|
||||
from ifcedit.foreach import run_foreach
|
||||
|
||||
|
||||
def format_output(data, fmt: str) -> str:
|
||||
@@ -138,6 +139,42 @@ def _parse_extra_args(extra: list[str]) -> dict[str, str]:
|
||||
return kwargs
|
||||
|
||||
|
||||
def cmd_foreach(args, extra_args):
|
||||
try:
|
||||
model = ifcopenshell.open(args.ifc_file)
|
||||
except Exception as e:
|
||||
print(f"Error: Could not open IFC file: {e}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
parts = args.function_path.split(".")
|
||||
if len(parts) != 2:
|
||||
print("Error: function path must be 'module.function' (e.g. root.create_entity)", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
module, function = parts
|
||||
|
||||
raw_kwargs_template = _parse_extra_args(extra_args)
|
||||
|
||||
try:
|
||||
stdin_data = json.load(sys.stdin)
|
||||
except json.JSONDecodeError as e:
|
||||
print(f"Error: Could not parse JSON from stdin: {e}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
if not isinstance(stdin_data, list):
|
||||
print("Error: stdin must be a JSON array", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
result = run_foreach(model, module, function, raw_kwargs_template, stdin_data)
|
||||
|
||||
if result["ok"]:
|
||||
output_path = args.output or args.ifc_file
|
||||
model.write(output_path)
|
||||
|
||||
print(format_output(result, args.output_format))
|
||||
if not result["ok"]:
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def cmd_quantify(args, extra_args):
|
||||
if args.quantify_command == "list":
|
||||
result = list_rules()
|
||||
@@ -191,6 +228,15 @@ def main():
|
||||
run_parser.add_argument("-o", "--output", help="Output file path (default: overwrite input)")
|
||||
run_parser.add_argument("--dry-run", action="store_true", help="Validate without executing or saving")
|
||||
|
||||
# foreach
|
||||
foreach_parser = subparsers.add_parser(
|
||||
"foreach",
|
||||
help="Apply an API function to each element in a JSON array read from stdin",
|
||||
)
|
||||
foreach_parser.add_argument("ifc_file", help="Path to the IFC file")
|
||||
foreach_parser.add_argument("function_path", help="module.function (e.g. attribute.edit_attributes)")
|
||||
foreach_parser.add_argument("-o", "--output", help="Output file path (default: overwrite input)")
|
||||
|
||||
# quantify
|
||||
quantify_parser = subparsers.add_parser("quantify", help="Quantity take-off (QTO) using ifc5d rules")
|
||||
quantify_sub = quantify_parser.add_subparsers(dest="quantify_command")
|
||||
@@ -209,6 +255,8 @@ def main():
|
||||
cmd_docs(args)
|
||||
elif args.command == "run":
|
||||
cmd_run(args, extra)
|
||||
elif args.command == "foreach":
|
||||
cmd_foreach(args, extra)
|
||||
elif args.command == "quantify":
|
||||
cmd_quantify(args, extra)
|
||||
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
# IfcEdit - CLI wrapper for ifcopenshell.api mutation functions
|
||||
# Copyright (C) 2026 Bruno Postle <bruno@postle.net>
|
||||
#
|
||||
# This file is part of IfcEdit.
|
||||
#
|
||||
# IfcEdit is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Lesser General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# IfcEdit is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Lesser General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Lesser General Public License
|
||||
# along with IfcEdit. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ifcopenshell
|
||||
|
||||
from ifcedit.run import run_api
|
||||
|
||||
|
||||
def _substitute(template: str, item: dict) -> str:
|
||||
"""Replace {key} placeholders in template with values from item."""
|
||||
for key, value in item.items():
|
||||
template = template.replace(f"{{{key}}}", str(value))
|
||||
return template
|
||||
|
||||
|
||||
def run_foreach(
|
||||
model: ifcopenshell.file,
|
||||
module: str,
|
||||
function: str,
|
||||
raw_kwargs_template: dict[str, str],
|
||||
items: list[dict],
|
||||
) -> dict:
|
||||
"""Apply an API function to each item in a list, substituting {field} placeholders.
|
||||
|
||||
Opens the model once, applies the mutation for every item, and returns a summary.
|
||||
The caller is responsible for saving the model.
|
||||
|
||||
Args:
|
||||
model: The open IFC model (mutated in place).
|
||||
module: API module name (e.g. "root").
|
||||
function: Function name (e.g. "remove_product").
|
||||
raw_kwargs_template: Arg templates with {field} placeholders, e.g. {"product": "{id}"}.
|
||||
items: List of dicts (e.g. from ifcquery select output).
|
||||
|
||||
Returns:
|
||||
{"ok": True, "count": N, "errors": []} on full success,
|
||||
{"ok": False, "count": N, "errors": [{...}]} if any item failed.
|
||||
"""
|
||||
errors = []
|
||||
count = 0
|
||||
|
||||
for i, item in enumerate(items):
|
||||
if not isinstance(item, dict):
|
||||
errors.append({"index": i, "item": item, "error": "item is not a dict"})
|
||||
continue
|
||||
|
||||
substituted = {k: _substitute(v, item) for k, v in raw_kwargs_template.items()}
|
||||
result = run_api(model, module, function, substituted)
|
||||
|
||||
if result["ok"]:
|
||||
count += 1
|
||||
else:
|
||||
errors.append({"index": i, "item": item, "error": result["error"]})
|
||||
|
||||
return {
|
||||
"ok": len(errors) == 0,
|
||||
"count": count,
|
||||
"errors": errors,
|
||||
}
|
||||
Reference in New Issue
Block a user