From ec48864f761bc1c6de7685295dc9d531f299f97b Mon Sep 17 00:00:00 2001 From: Luthaf Date: Fri, 4 Jul 2014 18:38:49 +0100 Subject: [PATCH] Use datadirs as base search path for included content --- patacrep/content/include.py | 27 ++++++++++++++++----------- songbook | 6 ++---- 2 files changed, 18 insertions(+), 15 deletions(-) diff --git a/patacrep/content/include.py b/patacrep/content/include.py index ac81c940..b1e1f1cd 100644 --- a/patacrep/content/include.py +++ b/patacrep/content/include.py @@ -11,10 +11,22 @@ import os import sys import logging -from patacrep.content import process_content +from patacrep.content import process_content, ContentError LOGGER = logging.getLogger(__name__) +def load_from_datadirs(path, config=None): + if not config or not config["datadir"]: + LOGGER.error("No datadir in the configuration.") + sys.exit(1) + for datadir in config["datadir"]: + filepath = os.path.join(datadir, path) + if os.path.exists(filepath): + return filepath + # File not found + raise ContentError("include", "The file '{0}' was not found in the " + "datadirs.".format(path)) + #pylint: disable=unused-argument def parse(keyword, config, argument, contentlist): """Include an external file content. @@ -26,13 +38,9 @@ def parse(keyword, config, argument, contentlist): - contentlist: a list of file paths to be included. """ new_contentlist = [] - songbook_dir = config.get("_songbook_dir", "") - if not os.path.isdir(songbook_dir): - LOGGER.warning("No songbook directory in configuration. 'include' " - "keyword may fail.") for path in contentlist: - filepath = os.path.join(songbook_dir, path) + filepath = load_from_datadirs(path, config) try: with open(filepath, "r") as content_file: new_content = json.load(content_file) @@ -41,12 +49,9 @@ def parse(keyword, config, argument, contentlist): LOGGER.error("Error while loading file '{}'.".format(filepath)) sys.exit(1) - config["_songbook_dir"] = os.path.abspath( - os.path.dirname(filepath) - ) - + config["datadir"].append(os.path.abspath(os.path.dirname(filepath))) new_contentlist += process_content(new_content, config) - config["_songbook_dir"] = songbook_dir + config["datadir"].pop() return new_contentlist diff --git a/songbook b/songbook index 1919d12a..626385b4 100755 --- a/songbook +++ b/songbook @@ -108,8 +108,6 @@ def main(): LOGGER.error("Error while loading file '{}'.".format(songbook_path)) sys.exit(1) - songbook["_songbook_dir"] = os.path.abspath(os.path.dirname(songbook_path)) - # Gathering datadirs datadirs = [] if options.datadir: @@ -126,9 +124,9 @@ def main(): ) for path in songbook['datadir'] ] - if not datadirs: # Default value - datadirs = [os.path.dirname(os.path.abspath(songbook_path))] + datadirs.append(os.path.dirname(os.path.abspath(songbook_path))) + songbook['datadir'] = datadirs try: