Mercurial > hgrepos > Python > libs > ConfigMix
comparison 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 |
comparison
equal
deleted
inserted
replaced
| 179:62db35db8939 | 180:e87fa5bd68e7 |
|---|---|
| 19 __date__ = "|VCSJustDate|" | 19 __date__ = "|VCSJustDate|" |
| 20 | 20 |
| 21 __all__ = ["load", "safe_load", | 21 __all__ = ["load", "safe_load", |
| 22 "set_loader", "get_loader", | 22 "set_loader", "get_loader", |
| 23 "get_default_loader", | 23 "get_default_loader", |
| 24 "Configuration"] | 24 "Configuration", |
| 25 "try_determine_filemode"] | |
| 25 | 26 |
| 26 | 27 |
| 27 import fnmatch | 28 import fnmatch |
| 28 import copy | 29 import copy |
| 30 import io | |
| 31 import re | |
| 29 | 32 |
| 30 from .compat import u, u2fs | 33 from .compat import u, u2fs |
| 31 from .config import Configuration | 34 from .config import Configuration |
| 32 | 35 |
| 33 | 36 |
| 112 | 115 |
| 113 | 116 |
| 114 def _load_ini(filename): | 117 def _load_ini(filename): |
| 115 from . import ini | 118 from . import ini |
| 116 return ini.load(filename) | 119 return ini.load(filename) |
| 120 | |
| 121 | |
| 122 EMACS_MODELINE = re.compile(r"-\*-(.*?)-\*-") | |
| 123 EMACS_MODE = re.compile(r"(?:\A\s*|;\s*)mode[:=]\s*([-_.a-zA-Z0-9]+)") | |
| 124 | |
| 125 | |
| 126 def try_determine_filemode(filename): | |
| 127 """Try to determine an explicitely given filemode from an Emacs-compatible | |
| 128 mode declaration (e.g. ``mode=python``). | |
| 129 | |
| 130 :param str filename: | |
| 131 :return: the found mode string or `None` | |
| 132 :rtype: str or None | |
| 133 | |
| 134 Only the first two lines are searched for. | |
| 135 | |
| 136 """ | |
| 137 with io.open(filename, encoding="ascii", errors="replace") as f: | |
| 138 idx = 0 | |
| 139 for l in f: | |
| 140 idx += 1 | |
| 141 mo = EMACS_MODELINE.search(l) | |
| 142 if mo: | |
| 143 mo = EMACS_MODE.search(mo.group(1)) | |
| 144 if mo: | |
| 145 return mo.group(1) | |
| 146 if idx >= 2: | |
| 147 break | |
| 148 return None | |
| 117 | 149 |
| 118 | 150 |
| 119 DEFAULT_MODE_LOADERS = { | 151 DEFAULT_MODE_LOADERS = { |
| 120 "python": _load_py, | 152 "python": _load_py, |
| 121 "yaml": _load_yaml, | 153 "yaml": _load_yaml, |
