|
| 1 | +#!/usr/bin/env python3 |
| 2 | +import argparse |
| 3 | +import re |
| 4 | +from pathlib import Path |
| 5 | + |
| 6 | + |
| 7 | +class Element(): |
| 8 | + def __init__(self, line): |
| 9 | + self.startline = line |
| 10 | + self.children = [] |
| 11 | + self.current_child = None |
| 12 | + self.endline = None |
| 13 | + |
| 14 | + def parse(self, line): |
| 15 | + |
| 16 | + if self.current_child is None: |
| 17 | + for Childtype in self._contains: |
| 18 | + if Childtype._startswith.match(line): |
| 19 | + self.current_child = Childtype(line) |
| 20 | + else: |
| 21 | + print(f"{Childtype} did not match {line} for {self.__class__}") |
| 22 | + assert self.current_child is not None, f"should have found type for line {line}" |
| 23 | + elif self.current_child._endswith.match(line): |
| 24 | + self.current_child.endline = line |
| 25 | + self.children.append(self.current_child) |
| 26 | + self.current_child = None |
| 27 | + else: |
| 28 | + self.current_child.parse(line) |
| 29 | + |
| 30 | + def __str__(self): |
| 31 | + return self.startline + "".join(sorted([str(c) for c in self.children])) + self.endline |
| 32 | + |
| 33 | + |
| 34 | +class Loop(Element): |
| 35 | + _startswith = re.compile("^\s+(?:outer|inner) loop$") |
| 36 | + _endswith = re.compile("^\s+endloop$") |
| 37 | + _footer = "endloop" |
| 38 | + |
| 39 | + def parse(self, line): |
| 40 | + self.children.append(line) |
| 41 | + |
| 42 | + def __str__(self): |
| 43 | + return self.startline + "".join(self.children) + self.endline |
| 44 | + |
| 45 | + |
| 46 | +class Facet(Element): |
| 47 | + _startswith = re.compile("^\s+facet\s+(.*)$") |
| 48 | + _endswith = re.compile("^\s+endfacet$") |
| 49 | + _contains = (Loop,) |
| 50 | + |
| 51 | + |
| 52 | +class Model(Element): |
| 53 | + _startswith = re.compile("^\s*solid\s+(.*)$") |
| 54 | + _endswith = re.compile("^\s*endsolid\s+(.*)$") |
| 55 | + _contains = (Facet,) |
| 56 | + |
| 57 | + |
| 58 | +class STL(Element): |
| 59 | + _contains = (Model,) |
| 60 | + endline = "" |
| 61 | + |
| 62 | + def __init__(self, filename): |
| 63 | + self.startline = "" |
| 64 | + data = open(filename, "r").readlines() |
| 65 | + self.children = [] |
| 66 | + self.current_child = None |
| 67 | + self.read(data) |
| 68 | + |
| 69 | + def read(self, data): |
| 70 | + for line in data: |
| 71 | + self.parse(line) |
| 72 | + |
| 73 | + |
| 74 | +if __name__ == "__main__": |
| 75 | + parser = argparse.ArgumentParser(description="stl sorter for deterministic diffing") |
| 76 | + parser.add_argument('stlfile', metavar="STLFILE", type=Path, help="path of the STL to sort (in place)") |
| 77 | + args = parser.parse_args() |
| 78 | + |
| 79 | + s = STL(args.stlfile) |
| 80 | + s_as_str = str(s) |
| 81 | + open(args.stlfile, "w").write(s_as_str) |
0 commit comments