Kristina Chodorow | a028ae2 | 2016-12-13 18:59:51 +0000 | [diff] [blame] | 1 | # 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 | |
| 16 | import fileinput |
| 17 | import re |
| 18 | import subprocess |
| 19 | import sys |
| 20 | |
| 21 | |
| 22 | class 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 |
jingwen | 89cd56c | 2019-06-20 05:27:17 -0700 | [diff] [blame] | 31 | graph = b"" |
Kristina Chodorow | a028ae2 | 2016-12-13 18:59:51 +0000 | [diff] [blame] | 32 | 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) |
jingwen | 89cd56c | 2019-06-20 05:27:17 -0700 | [diff] [blame] | 42 | output = dot.communicate(graph)[0].decode() |
Kristina Chodorow | a028ae2 | 2016-12-13 18:59:51 +0000 | [diff] [blame] | 43 | 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 |
jingwen | 89cd56c | 2019-06-20 05:27:17 -0700 | [diff] [blame] | 49 | graph = b"" |
Kristina Chodorow | a028ae2 | 2016-12-13 18:59:51 +0000 | [diff] [blame] | 50 | block_num += 1 |
| 51 | continue |
| 52 | |
| 53 | if collect: |
jingwen | 89cd56c | 2019-06-20 05:27:17 -0700 | [diff] [blame] | 54 | graph += str.encode(line) |
Kristina Chodorow | a028ae2 | 2016-12-13 18:59:51 +0000 | [diff] [blame] | 55 | else: |
| 56 | sys.stdout.write(line) |