Skip to content

Instantly share code, notes, and snippets.

@geographika
Created May 11, 2020 22:04
Show Gist options
  • Save geographika/eb15df2f22937d07f7eb07a9ff7ecc9c to your computer and use it in GitHub Desktop.
Save geographika/eb15df2f22937d07f7eb07a9ff7ecc9c to your computer and use it in GitHub Desktop.
import re
import os
import glob
# https://stackoverflow.com/questions/53082965/how-can-i-match-a-restructuredtext-code-block-with-regex-and-python
def update_index_directive(directive):
"""
Add a name reference to an index directive
Input:
.. index::
pair: CLASS; BACKGROUNDCOLOR
Output:
.. index::
pair: CLASS; BACKGROUNDCOLOR
:name: mapfile-class-background
"""
mylist = directive.split("\n")
spacer_length = len(mylist[1]) - len(mylist[1].lstrip())
spacer = " " * spacer_length
type_ = mylist[1].split(":")[0].strip()
if type_ != "pair":
# only update for index directives that are not "single"
return directive
params = mylist[1].split(":")[1].split(";")
# ignore some non-mapfile index directives - these are all uppercase
for p in params:
if p.upper() != p:
return directive
ref = "-".join([p.lower().strip() for p in params])
name = "{}:name: mapfile-{}".format(spacer, ref)
mylist.insert(2, name)
updated_directive = "\n".join(mylist)
return updated_directive
def main(input_folder, output_folder):
for fn in glob.glob(input_folder + "/*.txt"):
if os.path.basename(fn) not in [
"encoding.txt",
"expressions.txt",
"fontset.txt",
"geotransform.txt",
"include.txt",
"projection.txt",
"styleitem.txt",
"template.txt",
"validation.txt",
"union.txt",
"xml_mapfile.txt",
"xmp_metadata.txt"
]: # exlude certain files
with open(fn, encoding="utf8") as f:
txt = f.read()
pattern = r"(\.\. index::\s\s)(.*\s.+).*?\n\s"
matches = re.finditer(pattern, txt, re.M)
replacements = []
for m, match in enumerate(matches):
directive = match.group(0)
updated_directive = update_index_directive(directive)
replacements.append((directive, updated_directive))
for old, new in replacements:
txt = txt.replace(old, new)
output_file = os.path.join(output_folder, os.path.basename(fn))
with open(output_file, "w", newline="\n", encoding="utf8") as f:
f.write(txt)
input_folder = r"D:\GitHub\docs\en\mapfile"
output_folder = r"D:\GitHub\docs\en\mapfile\new"
main(input_folder, output_folder)
print("Done!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment