2015-01-22 09:40:25 +01:00
|
|
|
#!/usr/bin/env python
|
2019-02-25 16:30:40 +01:00
|
|
|
# Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+
|
2015-01-22 09:40:25 +01:00
|
|
|
|
|
|
|
import os
|
|
|
|
import sys
|
|
|
|
import re
|
|
|
|
|
|
|
|
if len(sys.argv) < 2:
|
2016-08-28 15:11:46 +02:00
|
|
|
print "Syntax: %s <md-files>" % sys.argv[0]
|
2015-01-22 09:40:25 +01:00
|
|
|
print ""
|
2015-01-22 16:09:28 +01:00
|
|
|
print "Updates inter-chapter links in the specified Markdown files."
|
2015-01-22 09:40:25 +01:00
|
|
|
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:
|
2016-08-13 15:59:06 +02:00
|
|
|
print "Error: Anchor '%s' is used multiple times: in %s and %s" % (id, file, anchors[id])
|
2015-01-22 09:40:25 +01:00
|
|
|
|
|
|
|
anchors[match.group("id")] = file
|
|
|
|
|
|
|
|
def update_anchor(match):
|
|
|
|
id = match.group("id")
|
|
|
|
|
|
|
|
try:
|
|
|
|
file = os.path.basename(anchors[id])
|
|
|
|
except KeyError:
|
2016-08-13 15:59:06 +02:00
|
|
|
print "Error: Unmatched anchor: %s" % (id)
|
2015-01-22 09:40:25 +01:00
|
|
|
file = ""
|
|
|
|
|
|
|
|
return "[%s](%s#%s)" % (match.group("text"), file, id)
|
|
|
|
|
|
|
|
for file in sys.argv[1:]:
|
|
|
|
text = open(file).read()
|
2016-08-13 15:59:06 +02:00
|
|
|
print "> Processing file '%s'..." % (file)
|
2015-01-22 16:23:23 +01:00
|
|
|
new_text = re.sub(r"\[(?P<text>.*?)\]\((?P<file>[0-9-a-z\.]+)?#(?P<id>[^#\)]+)\)", update_anchor, text)
|
2015-01-22 09:40:25 +01:00
|
|
|
open(file, "w").write(new_text)
|