File: update-links.py

package info (click to toggle)
icinga2 2.15.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 20,032 kB
  • sloc: cpp: 97,877; sql: 3,261; cs: 1,636; yacc: 1,584; sh: 1,009; ansic: 890; lex: 420; python: 80; makefile: 62; javascript: 12
file content (41 lines) | stat: -rwxr-xr-x 1,112 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#!/usr/bin/env python
# Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+

import os
import sys
import re

if len(sys.argv) < 2:
    print "Syntax: %s <md-files>" % sys.argv[0]
    print ""
    print "Updates inter-chapter links in the specified Markdown files."
    sys.exit(1)

anchors = {}

for file in sys.argv[1:]:
    text = open(file).read()
    for match in re.finditer(r"<a id=\"(?P<id>.*?)\">", text):
        id = match.group("id")

        if id in anchors:
            print "Error: Anchor '%s' is used multiple times: in %s and %s" % (id, file, anchors[id])

        anchors[match.group("id")] = file

def update_anchor(match):
    id = match.group("id")

    try:
        file = os.path.basename(anchors[id])
    except KeyError:
        print "Error: Unmatched anchor: %s" % (id)
        file = ""

    return "[%s](%s#%s)" % (match.group("text"), file, id)

for file in sys.argv[1:]:
    text = open(file).read()
    print "> Processing file '%s'..." % (file)
    new_text = re.sub(r"\[(?P<text>.*?)\]\((?P<file>[0-9-a-z\.]+)?#(?P<id>[^#\)]+)\)", update_anchor, text)
    open(file, "w").write(new_text)