devstate.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. from state.pystate import PyState
  2. from uuid import UUID
  3. class DevState(PyState):
  4. """
  5. Version of PyState that allows dumping to .dot files
  6. + node id's are generated sequentially to make writing tests easier
  7. """
  8. def __init__(self):
  9. self.free_id = 0
  10. super().__init__()
  11. def new_id(self) -> UUID:
  12. self.free_id += 1
  13. return UUID(int=self.free_id - 1)
  14. def dump(self, path: str, png_path: str = None):
  15. """Dumps the whole MV graph to a graphviz .dot-file
  16. Args:
  17. path (str): path for .dot-file
  18. png_path (str, optional): path for .png image generated from the .dot-file. Defaults to None.
  19. """
  20. with open(path, "w") as f:
  21. f.write("digraph main {\n")
  22. for n in sorted(self.nodes):
  23. if n in self.values:
  24. x = self.values[n]
  25. if isinstance(x, tuple):
  26. x = f"{x[0]}"
  27. else:
  28. x = repr(x)
  29. f.write("\"a_%s\" [label=\"%s\"];\n" % (
  30. n.int, x.replace('"', '\\"')))
  31. else:
  32. f.write("\"a_%s\" [label=\"\"];\n" % n)
  33. for i, e in sorted(list(self.edges.items())):
  34. f.write("\"a_%s\" [label=\"e_%s\" shape=point];\n" % (i.int, i.int))
  35. f.write("\"a_%s\" -> \"a_%s\" [arrowhead=none];\n" % (e[0].int, i.int))
  36. f.write("\"a_%s\" -> \"a_%s\";\n" % (i.int, e[1].int))
  37. f.write("}")
  38. if png_path != None:
  39. # generate png from dot-file
  40. bashCommand = f"dot -Tpng {path} -o {png_path}"
  41. import subprocess
  42. process = subprocess.Popen(
  43. bashCommand.split(), stdout=subprocess.PIPE)
  44. output, error = process.communicate()