codekingpro/portable-devtools
115k
1"""2 pygments.formatters3 ~~~~~~~~~~~~~~~~~~~4 5 Pygments formatters.6 7 :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.8 :license: BSD, see LICENSE for details.9"""10 11import re12import sys13import types14import fnmatch15from os.path import basename16 17from pygments.formatters._mapping import FORMATTERS18from pygments.plugin import find_plugin_formatters19from pygments.util import ClassNotFound20 21__all__ = ['get_formatter_by_name', 'get_formatter_for_filename',22 'get_all_formatters', 'load_formatter_from_file'] + list(FORMATTERS)23 24_formatter_cache = {} # classes by name25_pattern_cache = {}26 27 28def _fn_matches(fn, glob):29 """Return whether the supplied file name fn matches pattern filename."""30 if glob not in _pattern_cache:31 pattern = _pattern_cache[glob] = re.compile(fnmatch.translate(glob))32 return pattern.match(fn)33 return _pattern_cache[glob].match(fn)34 35 36def _load_formatters(module_name):37 """Load a formatter (and all others in the module too)."""38 mod = __import__(module_name, None, None, ['__all__'])39 for formatter_name in mod.__all__:40 cls = getattr(mod, formatter_name)41 _formatter_cache[cls.name] = cls42 43 44def get_all_formatters():45 """Return a generator for all formatter classes."""46 # NB: this returns formatter classes, not info like get_all_lexers().47 for info in FORMATTERS.values():48 if info[1] not in _formatter_cache:49 _load_formatters(info[0])50 yield _formatter_cache[info[1]]51 for _, formatter in find_plugin_formatters():52 yield formatter53 54 55def find_formatter_class(alias):56 """Lookup a formatter by alias.57 58 Returns None if not found.59 """60 for module_name, name, aliases, _, _ in FORMATTERS.values():61 if alias in aliases:62 if name not in _formatter_cache:63 _load_formatters(module_name)64 return _formatter_cache[name]65 for _, cls in find_plugin_formatters():66 if alias in cls.aliases:67 return cls68 69 70def get_formatter_by_name(_alias, **options):71 """72 Return an instance of a :class:`.Formatter` subclass that has `alias` in its73 aliases list. The formatter is given the `options` at its instantiation.74 75 Will raise :exc:`pygments.util.ClassNotFound` if no formatter with that76 alias is found.77 """78 cls = find_formatter_class(_alias)79 if cls is None:80 raise ClassNotFound(f"no formatter found for name {_alias!r}")81 return cls(**options)82 83 84def load_formatter_from_file(filename, formattername="CustomFormatter", **options):85 """86 Return a `Formatter` subclass instance loaded from the provided file, relative87 to the current directory.88 89 The file is expected to contain a Formatter class named ``formattername``90 (by default, CustomFormatter). Users should be very careful with the input, because91 this method is equivalent to running ``eval()`` on the input file. The formatter is92 given the `options` at its instantiation.93 94 :exc:`pygments.util.ClassNotFound` is raised if there are any errors loading95 the formatter.96 97 .. versionadded:: 2.298 """99 try:100 # This empty dict will contain the namespace for the exec'd file101 custom_namespace = {}102 with open(filename, 'rb') as f:103 exec(f.read(), custom_namespace)104 # Retrieve the class `formattername` from that namespace105 if formattername not in custom_namespace:106 raise ClassNotFound(f'no valid {formattername} class found in {filename}')107 formatter_class = custom_namespace[formattername]108 # And finally instantiate it with the options109 return formatter_class(**options)110 except OSError as err:111 raise ClassNotFound(f'cannot read {filename}: {err}')112 except ClassNotFound:113 raise114 except Exception as err:115 raise ClassNotFound(f'error when loading custom formatter: {err}')116 117 118def get_formatter_for_filename(fn, **options):119 """120 Return a :class:`.Formatter` subclass instance that has a filename pattern121 matching `fn`. The formatter is given the `options` at its instantiation.122 123 Will raise :exc:`pygments.util.ClassNotFound` if no formatter for that filename124 is found.125 """126 fn = basename(fn)127 for modname, name, _, filenames, _ in FORMATTERS.values():128 for filename in filenames:129 if _fn_matches(fn, filename):130 if name not in _formatter_cache:131 _load_formatters(modname)132 return _formatter_cache[name](**options)133 for _name, cls in find_plugin_formatters():134 for filename in cls.filenames:135 if _fn_matches(fn, filename):136 return cls(**options)137 raise ClassNotFound(f"no formatter found for file name {fn!r}")138 139 140class _automodule(types.ModuleType):141 """Automatically import formatters."""142 143 def __getattr__(self, name):144 info = FORMATTERS.get(name)145 if info:146 _load_formatters(info[0])147 cls = _formatter_cache[info[1]]148 setattr(self, name, cls)149 return cls150 raise AttributeError(name)151 152 153oldmod = sys.modules[__name__]154newmod = _automodule(__name__)155newmod.__dict__.update(oldmod.__dict__)156sys.modules[__name__] = newmod157del newmod.newmod, newmod.oldmod, newmod.sys, newmod.types158 