| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
import argparse |
| 15 |
import glob |
| 16 |
import os |
| 17 |
import re |
| 18 |
import sys |
| 19 |
|
| 20 |
from scriptCommon import catchPath |
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
minTocEntries = 4 |
| 25 |
|
| 26 |
headingExcludeDefault = [1,3,4,5] |
| 27 |
headingExcludeRelease = [1,3,4,5] |
| 28 |
|
| 29 |
documentsDefault = os.path.join(os.path.relpath(catchPath), 'docs/*.md') |
| 30 |
releaseNotesName = 'release-notes.md' |
| 31 |
|
| 32 |
contentTitle = '**Contents**' |
| 33 |
contentLineNo = 4 |
| 34 |
contentLineNdx = contentLineNo - 1 |
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
VALIDS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-&' |
| 39 |
|
| 40 |
def readLines(in_file): |
| 41 |
"""Returns a list of lines from a input markdown file.""" |
| 42 |
|
| 43 |
with open(in_file, 'r') as inf: |
| 44 |
in_contents = inf.read().split('\n') |
| 45 |
return in_contents |
| 46 |
|
| 47 |
def removeLines(lines, remove=('[[back to top]', '<a class="mk-toclify"')): |
| 48 |
"""Removes existing [back to top] links and <a id> tags.""" |
| 49 |
|
| 50 |
if not remove: |
| 51 |
return lines[:] |
| 52 |
|
| 53 |
out = [] |
| 54 |
for l in lines: |
| 55 |
if l.startswith(remove): |
| 56 |
continue |
| 57 |
out.append(l) |
| 58 |
return out |
| 59 |
|
| 60 |
def removeToC(lines): |
| 61 |
"""Removes existing table of contents starting at index contentLineNdx.""" |
| 62 |
if not lines[contentLineNdx ].startswith(contentTitle): |
| 63 |
return lines[:] |
| 64 |
|
| 65 |
result_top = lines[:contentLineNdx] |
| 66 |
|
| 67 |
pos = contentLineNdx + 1 |
| 68 |
while lines[pos].startswith('['): |
| 69 |
pos = pos + 1 |
| 70 |
|
| 71 |
result_bottom = lines[pos + 1:] |
| 72 |
|
| 73 |
return result_top + result_bottom |
| 74 |
|
| 75 |
def dashifyHeadline(line): |
| 76 |
""" |
| 77 |
Takes a header line from a Markdown document and |
| 78 |
returns a tuple of the |
| 79 |
'#'-stripped version of the head line, |
| 80 |
a string version for <a id=''></a> anchor tags, |
| 81 |
and the level of the headline as integer. |
| 82 |
E.g., |
| 83 |
>>> dashifyHeadline('### some header lvl3') |
| 84 |
('Some header lvl3', 'some-header-lvl3', 3) |
| 85 |
|
| 86 |
""" |
| 87 |
stripped_right = line.rstrip('#') |
| 88 |
stripped_both = stripped_right.lstrip('#') |
| 89 |
level = len(stripped_right) - len(stripped_both) |
| 90 |
stripped_wspace = stripped_both.strip() |
| 91 |
|
| 92 |
|
| 93 |
|
| 94 |
|
| 95 |
|
| 96 |
|
| 97 |
dashified = '' |
| 98 |
for c in stripped_wspace: |
| 99 |
if c in VALIDS: |
| 100 |
dashified += c.lower() |
| 101 |
elif c.isspace(): |
| 102 |
dashified += '-' |
| 103 |
else: |
| 104 |
|
| 105 |
continue |
| 106 |
|
| 107 |
return [stripped_wspace, dashified, level] |
| 108 |
|
| 109 |
def tagAndCollect(lines, id_tag=True, back_links=False, exclude_h=None): |
| 110 |
""" |
| 111 |
Gets headlines from the markdown document and creates anchor tags. |
| 112 |
|
| 113 |
Keyword arguments: |
| 114 |
lines: a list of sublists where every sublist |
| 115 |
represents a line from a Markdown document. |
| 116 |
id_tag: if true, creates inserts a the <a id> tags (not req. by GitHub) |
| 117 |
back_links: if true, adds "back to top" links below each headline |
| 118 |
exclude_h: header levels to exclude. E.g., [2, 3] |
| 119 |
excludes level 2 and 3 headings. |
| 120 |
|
| 121 |
Returns a tuple of 2 lists: |
| 122 |
1st list: |
| 123 |
A modified version of the input list where |
| 124 |
<a id="some-header"></a> anchor tags where inserted |
| 125 |
above the header lines (if github is False). |
| 126 |
|
| 127 |
2nd list: |
| 128 |
A list of 3-value sublists, where the first value |
| 129 |
represents the heading, the second value the string |
| 130 |
that was inserted assigned to the IDs in the anchor tags, |
| 131 |
and the third value is an integer that represents the headline level. |
| 132 |
E.g., |
| 133 |
[['some header lvl3', 'some-header-lvl3', 3], ...] |
| 134 |
|
| 135 |
""" |
| 136 |
out_contents = [] |
| 137 |
headlines = [] |
| 138 |
for l in lines: |
| 139 |
saw_headline = False |
| 140 |
|
| 141 |
orig_len = len(l) |
| 142 |
l_stripped = l.lstrip() |
| 143 |
|
| 144 |
if l_stripped.startswith(('# ', '## ', '### ', '#### ', '##### ', '###### ')): |
| 145 |
|
| 146 |
|
| 147 |
|
| 148 |
|
| 149 |
if not l.lstrip('#').startswith(' '): |
| 150 |
continue |
| 151 |
|
| 152 |
if len(l) - len(l.lstrip('#')) > 6: |
| 153 |
continue |
| 154 |
|
| 155 |
if orig_len - len(l_stripped) > 3: |
| 156 |
continue |
| 157 |
|
| 158 |
|
| 159 |
if not set(l) - {'#', ' '}: |
| 160 |
continue |
| 161 |
|
| 162 |
saw_headline = True |
| 163 |
dashified = dashifyHeadline(l) |
| 164 |
|
| 165 |
if not exclude_h or not dashified[-1] in exclude_h: |
| 166 |
if id_tag: |
| 167 |
id_tag = '<a class="mk-toclify" id="%s"></a>'\ |
| 168 |
% (dashified[1]) |
| 169 |
out_contents.append(id_tag) |
| 170 |
headlines.append(dashified) |
| 171 |
|
| 172 |
out_contents.append(l) |
| 173 |
if back_links and saw_headline: |
| 174 |
out_contents.append('[[back to top](#table-of-contents)]') |
| 175 |
return out_contents, headlines |
| 176 |
|
| 177 |
def positioningHeadlines(headlines): |
| 178 |
""" |
| 179 |
Strips unnecessary whitespaces/tabs if first header is not left-aligned |
| 180 |
""" |
| 181 |
left_just = False |
| 182 |
for row in headlines: |
| 183 |
if row[-1] == 1: |
| 184 |
left_just = True |
| 185 |
break |
| 186 |
if not left_just: |
| 187 |
for row in headlines: |
| 188 |
row[-1] -= 1 |
| 189 |
return headlines |
| 190 |
|
| 191 |
def createToc(headlines, hyperlink=True, top_link=False, no_toc_header=False): |
| 192 |
""" |
| 193 |
Creates the table of contents from the headline list |
| 194 |
that was returned by the tagAndCollect function. |
| 195 |
|
| 196 |
Keyword Arguments: |
| 197 |
headlines: list of lists |
| 198 |
e.g., ['Some header lvl3', 'some-header-lvl3', 3] |
| 199 |
hyperlink: Creates hyperlinks in Markdown format if True, |
| 200 |
e.g., '- [Some header lvl1](#some-header-lvl1)' |
| 201 |
top_link: if True, add a id tag for linking the table |
| 202 |
of contents itself (for the back-to-top-links) |
| 203 |
no_toc_header: suppresses TOC header if True. |
| 204 |
|
| 205 |
Returns a list of headlines for a table of contents |
| 206 |
in Markdown format, |
| 207 |
e.g., [' - [Some header lvl3](#some-header-lvl3)', ...] |
| 208 |
|
| 209 |
""" |
| 210 |
processed = [] |
| 211 |
if not no_toc_header: |
| 212 |
if top_link: |
| 213 |
processed.append('<a class="mk-toclify" id="table-of-contents"></a>\n') |
| 214 |
processed.append(contentTitle + '<br>') |
| 215 |
|
| 216 |
for line in headlines: |
| 217 |
if hyperlink: |
| 218 |
item = '[%s](#%s)' % (line[0], line[1]) |
| 219 |
else: |
| 220 |
item = '%s- %s' % ((line[2]-1)*' ', line[0]) |
| 221 |
processed.append(item + '<br>') |
| 222 |
processed.append('\n') |
| 223 |
return processed |
| 224 |
|
| 225 |
def buildMarkdown(toc_headlines, body, spacer=0, placeholder=None): |
| 226 |
""" |
| 227 |
Returns a string with the Markdown output contents incl. |
| 228 |
the table of contents. |
| 229 |
|
| 230 |
Keyword arguments: |
| 231 |
toc_headlines: lines for the table of contents |
| 232 |
as created by the createToc function. |
| 233 |
body: contents of the Markdown file including |
| 234 |
ID-anchor tags as returned by the |
| 235 |
tagAndCollect function. |
| 236 |
spacer: Adds vertical space after the table |
| 237 |
of contents. Height in pixels. |
| 238 |
placeholder: If a placeholder string is provided, the placeholder |
| 239 |
will be replaced by the TOC instead of inserting the TOC at |
| 240 |
the top of the document |
| 241 |
|
| 242 |
""" |
| 243 |
if spacer: |
| 244 |
spacer_line = ['\n<div style="height:%spx;"></div>\n' % (spacer)] |
| 245 |
toc_markdown = "\n".join(toc_headlines + spacer_line) |
| 246 |
else: |
| 247 |
toc_markdown = "\n".join(toc_headlines) |
| 248 |
|
| 249 |
if placeholder: |
| 250 |
body_markdown = "\n".join(body) |
| 251 |
markdown = body_markdown.replace(placeholder, toc_markdown) |
| 252 |
else: |
| 253 |
body_markdown_p1 = "\n".join(body[:contentLineNdx ]) + '\n' |
| 254 |
body_markdown_p2 = "\n".join(body[ contentLineNdx:]) |
| 255 |
markdown = body_markdown_p1 + toc_markdown + body_markdown_p2 |
| 256 |
|
| 257 |
return markdown |
| 258 |
|
| 259 |
def outputMarkdown(markdown_cont, output_file): |
| 260 |
""" |
| 261 |
Writes to an output file if `outfile` is a valid path. |
| 262 |
|
| 263 |
""" |
| 264 |
if output_file: |
| 265 |
with open(output_file, 'w') as out: |
| 266 |
out.write(markdown_cont) |
| 267 |
|
| 268 |
def markdownToclify( |
| 269 |
input_file, |
| 270 |
output_file=None, |
| 271 |
min_toc_len=2, |
| 272 |
github=False, |
| 273 |
back_to_top=False, |
| 274 |
nolink=False, |
| 275 |
no_toc_header=False, |
| 276 |
spacer=0, |
| 277 |
placeholder=None, |
| 278 |
exclude_h=None): |
| 279 |
""" Function to add table of contents to markdown files. |
| 280 |
|
| 281 |
Parameters |
| 282 |
----------- |
| 283 |
input_file: str |
| 284 |
Path to the markdown input file. |
| 285 |
|
| 286 |
output_file: str (default: None) |
| 287 |
Path to the markdown output file. |
| 288 |
|
| 289 |
min_toc_len: int (default: 2) |
| 290 |
Minimum number of entries to create a table of contents for. |
| 291 |
|
| 292 |
github: bool (default: False) |
| 293 |
Uses GitHub TOC syntax if True. |
| 294 |
|
| 295 |
back_to_top: bool (default: False) |
| 296 |
Inserts back-to-top links below headings if True. |
| 297 |
|
| 298 |
nolink: bool (default: False) |
| 299 |
Creates the table of contents without internal links if True. |
| 300 |
|
| 301 |
no_toc_header: bool (default: False) |
| 302 |
Suppresses the Table of Contents header if True |
| 303 |
|
| 304 |
spacer: int (default: 0) |
| 305 |
Inserts horizontal space (in pixels) after the table of contents. |
| 306 |
|
| 307 |
placeholder: str (default: None) |
| 308 |
Inserts the TOC at the placeholder string instead |
| 309 |
of inserting the TOC at the top of the document. |
| 310 |
|
| 311 |
exclude_h: list (default None) |
| 312 |
Excludes header levels, e.g., if [2, 3], ignores header |
| 313 |
levels 2 and 3 in the TOC. |
| 314 |
|
| 315 |
Returns |
| 316 |
----------- |
| 317 |
changed: Boolean |
| 318 |
True if the file has been updated, False otherwise. |
| 319 |
|
| 320 |
""" |
| 321 |
cleaned_contents = removeLines( |
| 322 |
removeToC(readLines(input_file)), |
| 323 |
remove=('[[back to top]', '<a class="mk-toclify"')) |
| 324 |
|
| 325 |
processed_contents, raw_headlines = tagAndCollect( |
| 326 |
cleaned_contents, |
| 327 |
id_tag=not github, |
| 328 |
back_links=back_to_top, |
| 329 |
exclude_h=exclude_h) |
| 330 |
|
| 331 |
|
| 332 |
if len(raw_headlines) < min_toc_len: |
| 333 |
processed_headlines = [] |
| 334 |
else: |
| 335 |
leftjustified_headlines = positioningHeadlines(raw_headlines) |
| 336 |
|
| 337 |
processed_headlines = createToc( |
| 338 |
leftjustified_headlines, |
| 339 |
hyperlink=not nolink, |
| 340 |
top_link=not nolink and not github, |
| 341 |
no_toc_header=no_toc_header) |
| 342 |
|
| 343 |
if nolink: |
| 344 |
processed_contents = cleaned_contents |
| 345 |
|
| 346 |
cont = buildMarkdown( |
| 347 |
toc_headlines=processed_headlines, |
| 348 |
body=processed_contents, |
| 349 |
spacer=spacer, |
| 350 |
placeholder=placeholder) |
| 351 |
|
| 352 |
if output_file: |
| 353 |
outputMarkdown(cont, output_file) |
| 354 |
|
| 355 |
def isReleaseNotes(f): |
| 356 |
return os.path.basename(f) == releaseNotesName |
| 357 |
|
| 358 |
def excludeHeadingsFor(f): |
| 359 |
return headingExcludeRelease if isReleaseNotes(f) else headingExcludeDefault |
| 360 |
|
| 361 |
def updateSingleDocumentToC(input_file, min_toc_len, verbose=False): |
| 362 |
"""Add or update table of contents in specified file. Return 1 if file changed, 0 otherwise.""" |
| 363 |
if verbose : |
| 364 |
print( 'file: {}'.format(input_file)) |
| 365 |
|
| 366 |
output_file = input_file + '.tmp' |
| 367 |
|
| 368 |
markdownToclify( |
| 369 |
input_file=input_file, |
| 370 |
output_file=output_file, |
| 371 |
min_toc_len=min_toc_len, |
| 372 |
github=True, |
| 373 |
back_to_top=False, |
| 374 |
nolink=False, |
| 375 |
no_toc_header=False, |
| 376 |
spacer=False, |
| 377 |
placeholder=False, |
| 378 |
exclude_h=excludeHeadingsFor(input_file)) |
| 379 |
|
| 380 |
|
| 381 |
if sys.version_info >= (3, 3): |
| 382 |
os.replace(output_file, input_file) |
| 383 |
else: |
| 384 |
os.remove(input_file) |
| 385 |
os.rename(output_file, input_file) |
| 386 |
|
| 387 |
return 1 |
| 388 |
|
| 389 |
def updateDocumentToC(paths, min_toc_len, verbose): |
| 390 |
"""Add or update table of contents to specified paths. Return number of changed files""" |
| 391 |
n = 0 |
| 392 |
for g in paths: |
| 393 |
for f in glob.glob(g): |
| 394 |
if os.path.isfile(f): |
| 395 |
n = n + updateSingleDocumentToC(input_file=f, min_toc_len=min_toc_len, verbose=verbose) |
| 396 |
return n |
| 397 |
|
| 398 |
def updateDocumentToCMain(): |
| 399 |
"""Add or update table of contents to specified paths.""" |
| 400 |
|
| 401 |
parser = argparse.ArgumentParser( |
| 402 |
description='Add or update table of contents in markdown documents.', |
| 403 |
epilog="""""", |
| 404 |
formatter_class=argparse.RawTextHelpFormatter) |
| 405 |
|
| 406 |
parser.add_argument( |
| 407 |
'Input', |
| 408 |
metavar='file', |
| 409 |
type=str, |
| 410 |
nargs=argparse.REMAINDER, |
| 411 |
help='files to process, at default: docs/*.md') |
| 412 |
|
| 413 |
parser.add_argument( |
| 414 |
'-v', '--verbose', |
| 415 |
action='store_true', |
| 416 |
help='report the name of the file being processed') |
| 417 |
|
| 418 |
parser.add_argument( |
| 419 |
'--min-toc-entries', |
| 420 |
dest='minTocEntries', |
| 421 |
default=minTocEntries, |
| 422 |
type=int, |
| 423 |
metavar='N', |
| 424 |
help='the minimum number of entries to create a table of contents for [{default}]'.format(default=minTocEntries)) |
| 425 |
|
| 426 |
parser.add_argument( |
| 427 |
'--remove-toc', |
| 428 |
action='store_const', |
| 429 |
dest='minTocEntries', |
| 430 |
const=99, |
| 431 |
help='remove all tables of contents') |
| 432 |
|
| 433 |
args = parser.parse_args() |
| 434 |
|
| 435 |
paths = args.Input if args.Input else [documentsDefault] |
| 436 |
|
| 437 |
changedFiles = updateDocumentToC(paths=paths, min_toc_len=args.minTocEntries, verbose=args.verbose) |
| 438 |
|
| 439 |
if changedFiles > 0: |
| 440 |
print( "Processed table of contents in " + str(changedFiles) + " file(s)" ) |
| 441 |
else: |
| 442 |
print( "No table of contents added or updated" ) |
| 443 |
|
| 444 |
if __name__ == '__main__': |
| 445 |
updateDocumentToCMain() |
| 446 |
|
| 447 |
|