# HG changeset patch # User Franz Glasner # Date 1556868716 -7200 # Node ID e87fa5bd68e77a9dc1292f89c4fef7991a6de765 # Parent 62db35db89391053a87163777cb259656c46e8de Implemented "try_determine_filemode()" to determine a file-mode from an Emacs-compatible declaration diff -r 62db35db8939 -r e87fa5bd68e7 configmix/__init__.py --- a/configmix/__init__.py Thu May 02 10:32:36 2019 +0200 +++ b/configmix/__init__.py Fri May 03 09:31:56 2019 +0200 @@ -21,11 +21,14 @@ __all__ = ["load", "safe_load", "set_loader", "get_loader", "get_default_loader", - "Configuration"] + "Configuration", + "try_determine_filemode"] import fnmatch import copy +import io +import re from .compat import u, u2fs from .config import Configuration @@ -116,6 +119,35 @@ return ini.load(filename) +EMACS_MODELINE = re.compile(r"-\*-(.*?)-\*-") +EMACS_MODE = re.compile(r"(?:\A\s*|;\s*)mode[:=]\s*([-_.a-zA-Z0-9]+)") + + +def try_determine_filemode(filename): + """Try to determine an explicitely given filemode from an Emacs-compatible + mode declaration (e.g. ``mode=python``). + + :param str filename: + :return: the found mode string or `None` + :rtype: str or None + + Only the first two lines are searched for. + + """ + with io.open(filename, encoding="ascii", errors="replace") as f: + idx = 0 + for l in f: + idx += 1 + mo = EMACS_MODELINE.search(l) + if mo: + mo = EMACS_MODE.search(mo.group(1)) + if mo: + return mo.group(1) + if idx >= 2: + break + return None + + DEFAULT_MODE_LOADERS = { "python": _load_py, "yaml": _load_yaml,