@@ -14,25 +14,7 @@ def convert(
1414 graph_to_convert : AGraph | str | TextIOBase | Path | TextIO ,
1515 layout_prog : str = "dot" ,
1616) -> str :
17- if isinstance (graph_to_convert , AGraph ):
18- graph = graph_to_convert
19- elif isinstance (graph_to_convert , str ):
20- # This fixes a pygraphviz bug where a string beginning with a comment
21- # is mistakenly identified as a filename.
22- # https://github.com/pygraphviz/pygraphviz/issues/536
23- pattern = re .compile (
24- r"(?:\s*(?:/\*[^*]*\*+(?:[^/*][^*]*\*+)*/|//[^\r\n]*|\#[^\r\n]*)\s*)*\s*(strict)?\s*(graph|digraph).*?\{.*\}\s*" ,
25- re .DOTALL | re .MULTILINE | re .VERBOSE ,
26- )
27- if pattern .match (graph_to_convert ):
28- graph = AGraph (string = graph_to_convert )
29- else :
30- graph = AGraph (filename = graph_to_convert )
31- elif hasattr (graph_to_convert , "read" ):
32- graph = AGraph (string = graph_to_convert .read ())
33- else :
34- # Use builtin type detection which includes: hasattr(thing, "open")
35- graph = AGraph (graph_to_convert )
17+ graph = _load_pygraphviz_graph (graph_to_convert )
3618
3719 graph_edges : dict [str , dict ] = {
3820 f"{ e [0 ]} ->{ e [1 ]} -"
@@ -65,3 +47,26 @@ def convert(
6547 # Put clusters first, so that nodes are drawn in front
6648 mx_graph = MxGraph (clusters , nodes , edges )
6749 return mx_graph .value ()
50+
51+
52+ def _load_pygraphviz_graph (
53+ graph_to_convert : AGraph | str | TextIOBase | Path | TextIO ,
54+ ) -> AGraph :
55+ if isinstance (graph_to_convert , AGraph ):
56+ return graph_to_convert
57+ if isinstance (graph_to_convert , str ):
58+ # This fixes a pygraphviz bug where a string beginning with a comment
59+ # is mistakenly identified as a filename.
60+ # https://github.com/pygraphviz/pygraphviz/issues/536
61+ pattern = re .compile (
62+ r"(?:\s*(?:/\*[^*]*\*+(?:[^/*][^*]*\*+)*/|//[^\r\n]*|\#[^\r\n]*)\s*)*\s*(strict)?\s*(graph|digraph).*?\{.*\}\s*" ,
63+ re .DOTALL | re .MULTILINE | re .VERBOSE ,
64+ )
65+ if pattern .match (graph_to_convert ):
66+ return AGraph (string = graph_to_convert )
67+ return AGraph (filename = graph_to_convert )
68+ # pyrefly: ignore # missing-attribute
69+ if hasattr (graph_to_convert , "read" ) and callable (graph_to_convert .read ):
70+ return AGraph (string = graph_to_convert .read ())
71+ # Use builtin type detection which includes: hasattr(thing, "open")
72+ return AGraph (graph_to_convert )
0 commit comments