From 945454da9dc68f9319d0c07dbefa6f8e8a6d9e5b Mon Sep 17 00:00:00 2001 From: Jim Hague Date: Wed, 2 Nov 2016 14:59:31 +0000 Subject: [PATCH] Give ABC file directory when expanding markdown. specifies a file in the same directory as the file being processed. --- abcfield.py | 27 +++++++++++++-------------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/abcfield.py b/abcfield.py index 8511620..6a3ee77 100755 --- a/abcfield.py +++ b/abcfield.py @@ -168,17 +168,18 @@ def convertMarkdown(t, latex): res = re.sub(r'\\href{(.*?).abc}', r'\\hyperlink{\1}', res) else: res = re.sub(r'href="(.*?).abc"', r'href="\1.html"', res) - return res + return res.strip() # Implement a custom Markdown shorthand for referencing ABC files. # will expand to ['title of foo'](foo.abc). -def expandCustomMarkdown(t, latex): +def expandCustomMarkdown(t, dir, latex): # Given a match to (foo.abc), return a markdown link to the tune with the # title of the tune as the text of the link. def getTitle(m): fname = m.group(1) + ".abc" - with pathlib.Path(fname).open() as f: - return "[" + getFieldDisplayText(f, "T", latex) + "](" + fname + ")" + path = pathlib.Path(dir, fname) + with path.open() as f: + return "[" + getFieldDisplayText(f, dir, "T", latex) + "](" + fname + ")" return re.sub(r'<(.*?).abc>', getTitle, t) # Return the raw text for a given field. Optionally the nth field is taken, @@ -212,7 +213,7 @@ def getFieldText(inf, field, n = 1, starts = None): return res # Return display text for a given field. -def getFieldDisplayText(inf, field, n = 1, starts = None, latex = False): +def getFieldDisplayText(inf, dir, field, n = 1, starts = None, latex = False): res = getFieldText(inf, field, n, starts) if res: res = convertAccents(res, latex) @@ -221,13 +222,13 @@ def getFieldDisplayText(inf, field, n = 1, starts = None, latex = False): elif field.upper() == "K": res = convertKeyToDisplay(res) elif field.upper() in ["H", "N"]: - res = convertMarkdown(expandCustomMarkdown(res, latex), latex) + res = convertMarkdown(expandCustomMarkdown(res, dir, latex), latex) return res if __name__ == "__main__": - def process(inf, options): + def process(inf, dir, options): if options.display: - line = getFieldDisplayText(inf, options.field, options.index, options.starts, options.latex) + line = getFieldDisplayText(inf, dir, options.field, options.index, options.starts, options.latex) else: line = getFieldText(inf, options.field, options.index, options.starts) if line: @@ -260,11 +261,9 @@ if __name__ == "__main__": res = False if len(args) > 0: for arg in args: - try: - inf = open(arg, "r") - res = res or process(inf, options) - finally: - inf.close() + path = pathlib.Path(arg) + with path.open() as f: + res = res or process(f, path.parent, options) else: - res = process(sys.stdin, options) + res = process(sys.stdin, ".", options) sys.exit(int(not res))