Mercurial > hgrepos > Python > libs > ConfigMix
diff configmix/__init__.py @ 180:e87fa5bd68e7
Implemented "try_determine_filemode()" to determine a file-mode from an Emacs-compatible declaration
| author | Franz Glasner <fzglas.hg@dom66.de> |
|---|---|
| date | Fri, 03 May 2019 09:31:56 +0200 |
| parents | 62db35db8939 |
| children | 7cfdc972af42 |
line wrap: on
line diff
--- 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,
