# mkxref.py # # Generate crossreferences.asc # as a global include file for all text files here. # import os, sys, re # find all work package files, like # B6.wp02_cpython_to_python.txt START_STR = "B6.7.wp".lower() def get_wps_from_dir(as_html=False): res = {} for fname in os.listdir("."): flow = fname.lower() pre, ext = os.path.splitext(flow) if flow.startswith(START_STR) and ext == ".txt": num = flow[len(START_STR):].split("_", 1)[0] if len(num)==2 and num.isdigit(): if as_html: pre, ext = os.path.splitext(fname) newfname = pre + ".html" else: newfname = fname res["WP"+num] = newfname return res REF_FILE = "B6.5_workpackage_list.txt" def get_wps_from_file(): # read the file and find all WPnn_ references txt = file(REF_FILE).read() res = {} for piece in txt.split("WP"): num = piece.split("_", 1)[0] if len(num)==2 and num.isdigit(): res["WP"+num] = "" return res # read the existing xref file, find the WP section and replace it. XREF_FILE = "crossreferences.asc" def split_xref_text(): """ split the xref file into three parts: before, in, and after the workpackages """ try: lines = file(XREF_FILE).readlines() except IOError: lines = [] pre = [] pat = "..\s+_WP\d\d\:|.. attention::" for line in lines: if re.match(pat, line): break pre.append(line) post = lines[len(pre):] mid = [] for line in post[:]: if re.match(pat, line): mid.append(post.pop(0)) else: break return pre, mid, post def build_xref_file(): pre, old, post = split_xref_text() wps = get_wps_from_file() wps.update(get_wps_from_dir(as_html=True)) wplist = wps.items() wplist.sort() mid = [ ".. _%s: %s\n" % (name, url) for name, url in wplist] empties = [name for name, url in wplist if not url] if empties: n = len(empties) mid.append(".. attention:: **%d file%s missing: %s**\n" % (n, "s"[0:n>1], " ".join(empties))) if mid != old: file(XREF_FILE, "w").writelines( pre + mid + post) if __name__ == "__main__": build_xref_file()