blob: 75addbf8897af9fe0f8c0ace99be3665cce2bbaa [file] [log] [blame]
Kristina Chodorowa028ae22016-12-13 18:59:51 +00001# Copyright 2016 The Bazel Authors. All rights reserved.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14"""Graphviz documentation converter library."""
15
16import fileinput
17import re
18import subprocess
19import sys
20
21
22class DotConverter(object):
23 """Converts dot graphs to SVG format inline."""
24
25 def __init__(self, dot_command, dot_env):
26 self.dot_command = dot_command
27 self.dot_env = dot_env
28
29 def convert(self):
30 collect = False
jingwen89cd56c2019-06-20 05:27:17 -070031 graph = b""
Kristina Chodorowa028ae22016-12-13 18:59:51 +000032 block_num = 0
33
34 for line in fileinput.input():
35 if re.search(r"div class='graphviz dot'><!--", line):
36 collect = True
37 continue
38 elif collect and re.search(r"--></div>", line):
39 dot = subprocess.Popen(
40 self.dot_command,
41 stdin=subprocess.PIPE, stdout=subprocess.PIPE, env=self.dot_env)
jingwen89cd56c2019-06-20 05:27:17 -070042 output = dot.communicate(graph)[0].decode()
Kristina Chodorowa028ae22016-12-13 18:59:51 +000043 if dot.returncode == 0:
44 # cut the first few lines (svg header + comments)
45 sys.stdout.write(output.split("\n", 6)[6])
46 else:
47 sys.stderr.write("inlining block %d failed.\n" % (block_num + 1))
48 collect = False
jingwen89cd56c2019-06-20 05:27:17 -070049 graph = b""
Kristina Chodorowa028ae22016-12-13 18:59:51 +000050 block_num += 1
51 continue
52
53 if collect:
jingwen89cd56c2019-06-20 05:27:17 -070054 graph += str.encode(line)
Kristina Chodorowa028ae22016-12-13 18:59:51 +000055 else:
56 sys.stdout.write(line)