]>
git.proxmox.com Git - ceph.git/blob - ceph/src/seastar/fmt/support/rst2md.py
1 # reStructuredText (RST) to GitHub-flavored Markdown converter
4 from docutils
import core
, nodes
, writers
7 def is_github_ref(node
):
8 return re
.match('https://github.com/.*/(issues|pull)/.*', node
['refuri'])
11 class Translator(nodes
.NodeVisitor
):
12 def __init__(self
, document
):
13 nodes
.NodeVisitor
.__init
__(self
, document
)
16 self
.preserve_newlines
= False
18 def write(self
, text
):
19 self
.output
+= text
.replace('\n', '\n' + ' ' * self
.indent
)
21 def visit_document(self
, node
):
24 def depart_document(self
, node
):
27 def visit_section(self
, node
):
30 def depart_section(self
, node
):
31 # Skip all sections except the first one.
32 raise nodes
.StopTraversal
34 def visit_title(self
, node
):
35 self
.version
= re
.match(r
'(\d+\.\d+\.\d+).*', node
.children
[0]).group(1)
36 raise nodes
.SkipChildren
38 def depart_title(self
, node
):
41 def visit_Text(self
, node
):
42 if not self
.preserve_newlines
:
43 node
= node
.replace('\n', ' ')
46 def depart_Text(self
, node
):
49 def visit_bullet_list(self
, node
):
52 def depart_bullet_list(self
, node
):
55 def visit_list_item(self
, node
):
59 def depart_list_item(self
, node
):
63 def visit_paragraph(self
, node
):
66 def depart_paragraph(self
, node
):
69 def visit_reference(self
, node
):
70 if not is_github_ref(node
):
73 def depart_reference(self
, node
):
74 if not is_github_ref(node
):
75 self
.write('](' + node
['refuri'] + ')')
77 def visit_target(self
, node
):
80 def depart_target(self
, node
):
83 def visit_literal(self
, node
):
86 def depart_literal(self
, node
):
89 def visit_literal_block(self
, node
):
91 if 'c++' in node
['classes']:
94 self
.preserve_newlines
= True
96 def depart_literal_block(self
, node
):
98 self
.preserve_newlines
= False
100 def visit_inline(self
, node
):
103 def depart_inline(self
, node
):
106 def visit_image(self
, node
):
107 self
.write('![](' + node
['uri'] + ')')
109 def depart_image(self
, node
):
112 def write_row(self
, row
, widths
):
113 for i
, entry
in enumerate(row
):
114 text
= entry
[0][0] if len(entry
) > 0 else ''
117 self
.write('{:{}}'.format(text
, widths
[i
]))
120 def visit_table(self
, node
):
121 table
= node
.children
[0]
122 colspecs
= table
[:-2]
125 widths
= [int(cs
['colwidth']) for cs
in colspecs
]
126 sep
= '|'.join(['-' * w
for w
in widths
]) + '\n'
128 self
.write_row(thead
[0], widths
)
131 self
.write_row(row
, widths
)
132 raise nodes
.SkipChildren
134 def depart_table(self
, node
):
137 class MDWriter(writers
.Writer
):
138 """GitHub-flavored markdown writer"""
141 """Formats this writer supports."""
144 translator
= Translator(self
.document
)
145 self
.document
.walkabout(translator
)
146 self
.output
= (translator
.output
, translator
.version
)
149 def convert(rst_path
):
150 """Converts RST file to Markdown."""
151 return core
.publish_file(source_path
=rst_path
, writer
=MDWriter())