env.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801
  1. import os
  2. from os import path
  3. from itertools import chain
  4. from webassets import six
  5. from webassets.six.moves import map
  6. from webassets.six.moves import zip
  7. from webassets.utils import is_url
  8. try:
  9. import glob2 as glob
  10. from glob import has_magic
  11. except ImportError:
  12. import glob
  13. from glob import has_magic
  14. from .cache import get_cache
  15. from .version import get_versioner, get_manifest
  16. from .updater import get_updater
  17. from .utils import urlparse
  18. __all__ = ('Environment', 'RegisterError')
  19. class RegisterError(Exception):
  20. pass
  21. class ConfigStorage(object):
  22. """This is the backend which :class:`Environment` uses to store
  23. its configuration values.
  24. Environment-subclasses like the one used by ``django-assets`` will
  25. often want to use a custom ``ConfigStorage`` as well, building upon
  26. whatever configuration the framework is using.
  27. The goal in designing this class therefore is to make it easy for
  28. subclasses to change the place the data is stored: Only
  29. _meth:`__getitem__`, _meth:`__setitem__`, _meth:`__delitem__` and
  30. _meth:`__contains__` need to be implemented.
  31. One rule: The default storage is case-insensitive, and custom
  32. environments should maintain those semantics.
  33. A related reason is why we don't inherit from ``dict``. It would
  34. require us to re-implement a whole bunch of methods, like pop() etc.
  35. """
  36. def __init__(self, env):
  37. self.env = env
  38. def get(self, key, default=None):
  39. try:
  40. return self.__getitem__(key)
  41. except KeyError:
  42. return default
  43. def update(self, d):
  44. for key in d:
  45. self.__setitem__(key, d[key])
  46. def setdefault(self, key, value):
  47. if not key in self:
  48. self.__setitem__(key, value)
  49. return value
  50. return self.__getitem__(key)
  51. def __contains__(self, key):
  52. raise NotImplementedError()
  53. def __getitem__(self, key):
  54. raise NotImplementedError()
  55. def __setitem__(self, key, value):
  56. raise NotImplementedError()
  57. def __delitem__(self, key):
  58. raise NotImplementedError()
  59. def _get_deprecated(self, key):
  60. """For deprecated keys, fake the values as good as we can.
  61. Subclasses need to call this in __getitem__."""
  62. pass
  63. def _set_deprecated(self, key, value):
  64. """Same for __setitem__."""
  65. pass
  66. def url_prefix_join(prefix, fragment):
  67. """Join url prefix with fragment."""
  68. # Ensures urljoin will not cut the last part.
  69. prefix += prefix[-1:] != '/' and '/' or ''
  70. return urlparse.urljoin(prefix, fragment)
  71. class Resolver(object):
  72. """Responsible for resolving user-specified :class:`Bundle`
  73. contents to actual files, as well as to urls.
  74. In this base version, this is essentially responsible for searching
  75. the load path for the queried file.
  76. A custom implementation of this class is tremendously useful when
  77. integrating with frameworks, which usually have some system to
  78. spread static files across applications or modules.
  79. The class is designed for maximum extensibility.
  80. """
  81. def glob(self, basedir, expr):
  82. """Evaluates a glob expression.
  83. Yields a sorted list of absolute filenames.
  84. """
  85. def glob_generator(basedir, expr):
  86. expr = path.join(basedir, expr)
  87. for filename in glob.iglob(expr):
  88. if path.isdir(filename):
  89. continue
  90. yield path.normpath(filename)
  91. # The order of files returned by the glob implementation is undefined,
  92. # so sort alphabetically to maintain a deterministic ordering
  93. return sorted(glob_generator(basedir, expr))
  94. def consider_single_directory(self, directory, item):
  95. """Searches for ``item`` within ``directory``. Is able to
  96. resolve glob instructions.
  97. Subclasses can call this when they have narrowed done the
  98. location of a bundle item to a single directory.
  99. """
  100. expr = path.join(directory, item)
  101. if has_magic(expr):
  102. # Note: No error if glob returns an empty list
  103. return self.glob(directory, item)
  104. else:
  105. if path.exists(expr):
  106. return expr
  107. raise IOError("'%s' does not exist" % expr)
  108. def search_env_directory(self, ctx, item):
  109. """This is called by :meth:`search_for_source` when no
  110. :attr:`Environment.load_path` is set.
  111. """
  112. return self.consider_single_directory(ctx.directory, item)
  113. def search_load_path(self, ctx, item):
  114. """This is called by :meth:`search_for_source` when a
  115. :attr:`Environment.load_path` is set.
  116. If you want to change how the load path is processed,
  117. overwrite this method.
  118. """
  119. if has_magic(item):
  120. # We glob all paths.
  121. result = []
  122. for path in ctx.load_path:
  123. result.extend(self.glob(path, item))
  124. return result
  125. else:
  126. # Single file, stop when we find the first match, or error
  127. # out otherwise. We still use glob() because then the load_path
  128. # itself can contain globs. Neat!
  129. for path in ctx.load_path:
  130. result = self.glob(path, item)
  131. if result:
  132. return result
  133. raise IOError("'%s' not found in load path: %s" % (
  134. item, ctx.load_path))
  135. def search_for_source(self, ctx, item):
  136. """Called by :meth:`resolve_source` after determining that
  137. ``item`` is a relative filesystem path.
  138. You should always overwrite this method, and let
  139. :meth:`resolve_source` deal with absolute paths, urls and
  140. other types of items that a bundle may contain.
  141. """
  142. if ctx.load_path:
  143. return self.search_load_path(ctx, item)
  144. else:
  145. return self.search_env_directory(ctx, item)
  146. def query_url_mapping(self, ctx, filepath):
  147. """Searches the environment-wide url mapping (based on the
  148. urls assigned to each directory in the load path). Returns
  149. the correct url for ``filepath``.
  150. Subclasses should be sure that they really want to call this
  151. method, instead of simply falling back to ``super()``.
  152. """
  153. # Build a list of dir -> url mappings
  154. mapping = list(ctx.url_mapping.items())
  155. try:
  156. mapping.append((ctx.directory, ctx.url))
  157. except EnvironmentError:
  158. # Rarely, directory/url may not be set. That's ok.
  159. pass
  160. # Make sure paths are absolute, normalized, and sorted by length
  161. mapping = list(map(
  162. lambda p_u: (path.normpath(path.abspath(p_u[0])), p_u[1]),
  163. mapping))
  164. mapping.sort(key=lambda i: len(i[0]), reverse=True)
  165. needle = path.normpath(filepath)
  166. for candidate, url in mapping:
  167. if needle.startswith(candidate):
  168. # Found it!
  169. rel_path = needle[len(candidate)+1:]
  170. # If there are any subdirs in rel_path, ensure
  171. # they use HTML-style path separators, in case
  172. # the local OS (Windows!) has a different scheme
  173. rel_path = rel_path.replace(os.sep, "/")
  174. return url_prefix_join(url, rel_path)
  175. raise ValueError('Cannot determine url for %s' % filepath)
  176. def resolve_source(self, ctx, item):
  177. """Given ``item`` from a Bundle's contents, this has to
  178. return the final value to use, usually an absolute
  179. filesystem path.
  180. .. note::
  181. It is also allowed to return urls and bundle instances
  182. (or generally anything else the calling :class:`Bundle`
  183. instance may be able to handle). Indeed this is the
  184. reason why the name of this method does not imply a
  185. return type.
  186. The incoming item is usually a relative path, but may also be
  187. an absolute path, or a url. These you will commonly want to
  188. return unmodified.
  189. This method is also allowed to resolve ``item`` to multiple
  190. values, in which case a list should be returned. This is
  191. commonly used if ``item`` includes glob instructions
  192. (wildcards).
  193. .. note::
  194. Instead of this, subclasses should consider implementing
  195. :meth:`search_for_source` instead.
  196. """
  197. # Pass through some things unscathed
  198. if not isinstance(item, six.string_types):
  199. # Don't stand in the way of custom values.
  200. return item
  201. if is_url(item) or path.isabs(item):
  202. return item
  203. return self.search_for_source(ctx, item)
  204. def resolve_output_to_path(self, ctx, target, bundle):
  205. """Given ``target``, this has to return the absolute
  206. filesystem path to which the output file of ``bundle``
  207. should be written.
  208. ``target`` may be a relative or absolute path, and is
  209. usually taking from the :attr:`Bundle.output` property.
  210. If a version-placeholder is used (``%(version)s``, it is
  211. still unresolved at this point.
  212. """
  213. return path.join(ctx.directory, target)
  214. def resolve_source_to_url(self, ctx, filepath, item):
  215. """Given the absolute filesystem path in ``filepath``, as
  216. well as the original value from :attr:`Bundle.contents` which
  217. resolved to this path, this must return the absolute url
  218. through which the file is to be referenced.
  219. Depending on the use case, either the ``filepath`` or the
  220. ``item`` argument will be more helpful in generating the url.
  221. This method should raise a ``ValueError`` if the url cannot
  222. be determined.
  223. """
  224. return self.query_url_mapping(ctx, filepath)
  225. def resolve_output_to_url(self, ctx, target):
  226. """Given ``target``, this has to return the url through
  227. which the output file can be referenced.
  228. ``target`` may be a relative or absolute path, and is
  229. usually taking from the :attr:`Bundle.output` property.
  230. This is different from :meth:`resolve_source_to_url` in
  231. that you do not passed along the result of
  232. :meth:`resolve_output_to_path`. This is because in many
  233. use cases, the filesystem is not available at the point
  234. where the output url is needed (the media server may on
  235. a different machine).
  236. """
  237. if not path.isabs(target):
  238. # If relative, output files are written to env.directory,
  239. # thus we can simply base all values off of env.url.
  240. return url_prefix_join(ctx.url, target)
  241. else:
  242. # If an absolute output path was specified, then search
  243. # the url mappings.
  244. return self.query_url_mapping(ctx, target)
  245. class BundleRegistry(object):
  246. def __init__(self):
  247. self._named_bundles = {}
  248. self._anon_bundles = []
  249. def __iter__(self):
  250. return chain(six.itervalues(self._named_bundles), self._anon_bundles)
  251. def __getitem__(self, name):
  252. return self._named_bundles[name]
  253. def __contains__(self, name):
  254. return name in self._named_bundles
  255. def __len__(self):
  256. return len(self._named_bundles) + len(self._anon_bundles)
  257. def __bool__(self):
  258. return True
  259. __nonzero__ = __bool__ # For Python 2
  260. def register(self, name, *args, **kwargs):
  261. """Register a :class:`Bundle` with the given ``name``.
  262. This can be called in multiple ways:
  263. - With a single :class:`Bundle` instance::
  264. env.register('jquery', jquery_bundle)
  265. - With a dictionary, registering multiple bundles at once:
  266. bundles = {'js': js_bundle, 'css': css_bundle}
  267. env.register(bundles)
  268. .. note::
  269. This is a convenient way to use a :doc:`loader <loaders>`:
  270. env.register(YAMLLoader('assets.yaml').load_bundles())
  271. - With many arguments, creating a new bundle on the fly::
  272. env.register('all_js', jquery_bundle, 'common.js',
  273. filters='rjsmin', output='packed.js')
  274. """
  275. from .bundle import Bundle
  276. # Register a dict
  277. if isinstance(name, dict) and not args and not kwargs:
  278. for name, bundle in name.items():
  279. self.register(name, bundle)
  280. return
  281. if len(args) == 0:
  282. raise TypeError('at least two arguments are required')
  283. else:
  284. if len(args) == 1 and not kwargs and isinstance(args[0], Bundle):
  285. bundle = args[0]
  286. else:
  287. bundle = Bundle(*args, **kwargs)
  288. if name in self._named_bundles:
  289. if self._named_bundles[name] == bundle:
  290. pass # ignore
  291. else:
  292. raise RegisterError('Another bundle is already registered '+
  293. 'as "%s": %s' % (name, self._named_bundles[name]))
  294. else:
  295. self._named_bundles[name] = bundle
  296. bundle.env = self # take ownership
  297. return bundle
  298. def add(self, *bundles):
  299. """Register a list of bundles with the environment, without
  300. naming them.
  301. This isn't terribly useful in most cases. It exists primarily
  302. because in some cases, like when loading bundles by searching
  303. in templates for the use of an "assets" tag, no name is available.
  304. """
  305. for bundle in bundles:
  306. self._anon_bundles.append(bundle)
  307. bundle.env = self # take ownership
  308. # Those are config keys used by the environment. Framework-wrappers may
  309. # find this list useful if they desire to prefix those settings. For example,
  310. # in Django, it would be ASSETS_DEBUG. Other config keys are encouraged to use
  311. # their own namespacing, so they don't need to be prefixed. For example, a
  312. # filter setting might be CSSMIN_BIN.
  313. env_options = [
  314. 'directory', 'url', 'debug', 'cache', 'updater', 'auto_build',
  315. 'url_expire', 'versions', 'manifest', 'load_path', 'url_mapping',
  316. 'cache_file_mode' ]
  317. class ConfigurationContext(object):
  318. """Interface to the webassets configuration key-value store.
  319. This wraps the :class:`ConfigStorage`` interface and adds some
  320. helpers. It allows attribute-access to the most important
  321. settings, and transparently instantiates objects, such that
  322. ``env.manifest`` gives you an object, even though the configuration
  323. contains the string "json".
  324. """
  325. def __init__(self, storage):
  326. self._storage = storage
  327. def append_path(self, path, url=None):
  328. """Appends ``path`` to :attr:`load_path`, and adds a
  329. corresponding entry to :attr:`url_mapping`.
  330. """
  331. self.load_path.append(path)
  332. if url:
  333. self.url_mapping[path] = url
  334. def _set_debug(self, debug):
  335. self._storage['debug'] = debug
  336. def _get_debug(self):
  337. return self._storage['debug']
  338. debug = property(_get_debug, _set_debug, doc=
  339. """Enable/disable debug mode. Possible values are:
  340. ``False``
  341. Production mode. Bundles will be merged and filters applied.
  342. ``True``
  343. Enable debug mode. Bundles will output their individual source
  344. files.
  345. *"merge"*
  346. Merge the source files, but do not apply filters.
  347. """)
  348. def _set_cache_file_mode(self, mode):
  349. self._storage['cache_file_mode'] = mode
  350. def _get_cache_file_mode(self):
  351. return self._storage['cache_file_mode']
  352. cache_file_mode = property(_get_cache_file_mode, _set_cache_file_mode, doc=
  353. """Controls the mode of files created in the cache. The default mode
  354. is 0600. Follows standard unix mode.
  355. Possible values are any unix mode, e.g.:
  356. ``0660``
  357. Enable the group read+write bits
  358. ``0666``
  359. Enable world read+write bits
  360. """)
  361. def _set_cache(self, enable):
  362. self._storage['cache'] = enable
  363. def _get_cache(self):
  364. cache = get_cache(self._storage['cache'], self)
  365. if cache != self._storage['cache']:
  366. self._storage['cache'] = cache
  367. return cache
  368. cache = property(_get_cache, _set_cache, doc=
  369. """Controls the behavior of the cache. The cache will speed up rebuilding
  370. of your bundles, by caching individual filter results. This can be
  371. particularly useful while developing, if your bundles would otherwise take
  372. a long time to rebuild.
  373. Possible values are:
  374. ``False``
  375. Do not use the cache.
  376. ``True`` (default)
  377. Cache using default location, a ``.webassets-cache`` folder inside
  378. :attr:`directory`.
  379. *custom path*
  380. Use the given directory as the cache directory.
  381. """)
  382. def _set_auto_build(self, value):
  383. self._storage['auto_build'] = value
  384. def _get_auto_build(self):
  385. return self._storage['auto_build']
  386. auto_build = property(_get_auto_build, _set_auto_build, doc=
  387. """Controls whether bundles should be automatically built, and
  388. rebuilt, when required (if set to ``True``), or whether they
  389. must be built manually be the user, for example via a management
  390. command.
  391. This is a good setting to have enabled during debugging, and can
  392. be very convenient for low-traffic sites in production as well.
  393. However, there is a cost in checking whether the source files
  394. have changed, so if you care about performance, or if your build
  395. process takes very long, then you may want to disable this.
  396. By default automatic building is enabled.
  397. """)
  398. def _set_manifest(self, manifest):
  399. self._storage['manifest'] = manifest
  400. def _get_manifest(self):
  401. manifest = get_manifest(self._storage['manifest'], env=self)
  402. if manifest != self._storage['manifest']:
  403. self._storage['manifest'] = manifest
  404. return manifest
  405. manifest = property(_get_manifest, _set_manifest, doc=
  406. """A manifest persists information about the versions bundles
  407. are at.
  408. The Manifest plays a role only if you insert the bundle version
  409. in your output filenames, or append the version as a querystring
  410. to the url (via the ``url_expire`` option). It serves two
  411. purposes:
  412. - Without a manifest, it may be impossible to determine the
  413. version at runtime. In a deployed app, the media files may
  414. be stored on a different server entirely, and be
  415. inaccessible from the application code. The manifest,
  416. if shipped with your application, is what still allows to
  417. construct the proper URLs.
  418. - Even if it were possible to determine the version at
  419. runtime without a manifest, it may be a costly process,
  420. and using a manifest may give you better performance. If
  421. you use a hash-based version for example, this hash would
  422. need to be recalculated every time a new process is
  423. started.
  424. Valid values are:
  425. ``"cache"`` (default)
  426. The cache is used to remember version information. This
  427. is useful to avoid recalculating the version hash.
  428. ``"file:{path}"``
  429. Stores version information in a file at {path}. If not
  430. path is given, the manifest will be stored as
  431. ``.webassets-manifest`` in ``Environment.directory``.
  432. ``"json:{path}"``
  433. Same as "file:{path}", but uses JSON to store the information.
  434. ``False``, ``None``
  435. No manifest is used.
  436. Any custom manifest implementation.
  437. """)
  438. def _set_versions(self, versions):
  439. self._storage['versions'] = versions
  440. def _get_versions(self):
  441. versions = get_versioner(self._storage['versions'])
  442. if versions != self._storage['versions']:
  443. self._storage['versions'] = versions
  444. return versions
  445. versions = property(_get_versions, _set_versions, doc=
  446. """Defines what should be used as a Bundle ``version``.
  447. A bundle's version is what is appended to URLs when the
  448. ``url_expire`` option is enabled, and the version can be part
  449. of a Bundle's output filename by use of the ``%(version)s``
  450. placeholder.
  451. Valid values are:
  452. ``timestamp``
  453. The version is determined by looking at the mtime of a
  454. bundle's output file.
  455. ``hash`` (default)
  456. The version is a hash over the output file's content.
  457. ``False``, ``None``
  458. Functionality that requires a version is disabled. This
  459. includes the ``url_expire`` option, the ``auto_build``
  460. option, and support for the %(version)s placeholder.
  461. Any custom version implementation.
  462. """)
  463. def set_updater(self, updater):
  464. self._storage['updater'] = updater
  465. def get_updater(self):
  466. updater = get_updater(self._storage['updater'])
  467. if updater != self._storage['updater']:
  468. self._storage['updater'] = updater
  469. return updater
  470. updater = property(get_updater, set_updater, doc=
  471. """Controls how the ``auto_build`` option should determine
  472. whether a bundle needs to be rebuilt.
  473. ``"timestamp"`` (default)
  474. Rebuild bundles if the source file timestamp exceeds the existing
  475. output file's timestamp.
  476. ``"always"``
  477. Always rebuild bundles (avoid in production environments).
  478. Any custom version implementation.
  479. """)
  480. def _set_url_expire(self, url_expire):
  481. self._storage['url_expire'] = url_expire
  482. def _get_url_expire(self):
  483. return self._storage['url_expire']
  484. url_expire = property(_get_url_expire, _set_url_expire, doc=
  485. """If you send your assets to the client using a
  486. *far future expires* header (to minimize the 304 responses
  487. your server has to send), you need to make sure that assets
  488. will be reloaded by the browser when they change.
  489. If this is set to ``True``, then the Bundle URLs generated by
  490. webassets will have their version (see ``Environment.versions``)
  491. appended as a querystring.
  492. An alternative approach would be to use the ``%(version)s``
  493. placeholder in the bundle output file.
  494. The default behavior (indicated by a ``None`` value) is to add
  495. an expiry querystring if the bundle does not use a version
  496. placeholder.
  497. """)
  498. def _set_directory(self, directory):
  499. self._storage['directory'] = directory
  500. def _get_directory(self):
  501. try:
  502. return path.abspath(self._storage['directory'])
  503. except KeyError:
  504. raise EnvironmentError(
  505. 'The environment has no "directory" configured')
  506. directory = property(_get_directory, _set_directory, doc=
  507. """The base directory to which all paths will be relative to,
  508. unless :attr:`load_paths` are given, in which case this will
  509. only serve as the output directory.
  510. In the url space, it is mapped to :attr:`urls`.
  511. """)
  512. def _set_url(self, url):
  513. self._storage['url'] = url
  514. def _get_url(self):
  515. try:
  516. return self._storage['url']
  517. except KeyError:
  518. raise EnvironmentError(
  519. 'The environment has no "url" configured')
  520. url = property(_get_url, _set_url, doc=
  521. """The url prefix used to construct urls for files in
  522. :attr:`directory`.
  523. To define url spaces for other directories, see
  524. :attr:`url_mapping`.
  525. """)
  526. def _set_load_path(self, load_path):
  527. self._storage['load_path'] = load_path
  528. def _get_load_path(self):
  529. return self._storage['load_path']
  530. load_path = property(_get_load_path, _set_load_path, doc=
  531. """An list of directories that will be searched for source files.
  532. If this is set, source files will only be looked for in these
  533. directories, and :attr:`directory` is used as a location for
  534. output files only.
  535. .. note:
  536. You are free to add :attr:`directory` to your load path as
  537. well.
  538. .. note:
  539. Items on the load path are allowed to contain globs.
  540. To modify this list, you should use :meth:`append_path`, since
  541. it makes it easy to add the corresponding url prefix to
  542. :attr:`url_mapping`.
  543. """)
  544. def _set_url_mapping(self, url_mapping):
  545. self._storage['url_mapping'] = url_mapping
  546. def _get_url_mapping(self):
  547. return self._storage['url_mapping']
  548. url_mapping = property(_get_url_mapping, _set_url_mapping, doc=
  549. """A dictionary of directory -> url prefix mappings that will
  550. be considered when generating urls, in addition to the pair of
  551. :attr:`directory` and :attr:`url`, which is always active.
  552. You should use :meth:`append_path` to add directories to the
  553. load path along with their respective url spaces, instead of
  554. modifying this setting directly.
  555. """)
  556. def _set_resolver(self, resolver):
  557. self._storage['resolver'] = resolver
  558. def _get_resolver(self):
  559. return self._storage['resolver']
  560. resolver = property(_get_resolver, _set_resolver)
  561. class BaseEnvironment(BundleRegistry, ConfigurationContext):
  562. """Abstract base class for :class:`Environment` with slightly more
  563. generic assumptions, to ease subclassing.
  564. """
  565. config_storage_class = None
  566. resolver_class = Resolver
  567. def __init__(self, **config):
  568. BundleRegistry.__init__(self)
  569. self._config = self.config_storage_class(self)
  570. ConfigurationContext.__init__(self, self._config)
  571. # directory, url currently do not have default values
  572. #
  573. # some thought went into these defaults:
  574. # - enable url_expire, because we want to encourage the right thing
  575. # - default to hash versions, for the same reason: they're better
  576. # - manifest=cache because hash versions are slow
  577. self.config.setdefault('debug', False)
  578. self.config.setdefault('cache', True)
  579. self.config.setdefault('url_expire', None)
  580. self.config.setdefault('auto_build', True)
  581. self.config.setdefault('manifest', 'cache')
  582. self.config.setdefault('versions', 'hash')
  583. self.config.setdefault('updater', 'timestamp')
  584. self.config.setdefault('load_path', [])
  585. self.config.setdefault('url_mapping', {})
  586. self.config.setdefault('resolver', self.resolver_class())
  587. self.config.setdefault('cache_file_mode', None)
  588. self.config.update(config)
  589. @property
  590. def config(self):
  591. """Key-value configuration. Keys are case-insensitive.
  592. """
  593. # This is a property so that user are not tempted to assign
  594. # a custom dictionary which won't uphold our caseless semantics.
  595. return self._config
  596. class DictConfigStorage(ConfigStorage):
  597. """Using a lower-case dict for configuration values.
  598. """
  599. def __init__(self, *a, **kw):
  600. self._dict = {}
  601. ConfigStorage.__init__(self, *a, **kw)
  602. def __contains__(self, key):
  603. return self._dict.__contains__(key.lower())
  604. def __getitem__(self, key):
  605. key = key.lower()
  606. value = self._get_deprecated(key)
  607. if not value is None:
  608. return value
  609. return self._dict.__getitem__(key)
  610. def __setitem__(self, key, value):
  611. key = key.lower()
  612. if not self._set_deprecated(key, value):
  613. self._dict.__setitem__(key.lower(), value)
  614. def __delitem__(self, key):
  615. self._dict.__delitem__(key.lower())
  616. class Environment(BaseEnvironment):
  617. """Owns a collection of bundles, and a set of configuration values which
  618. will be used when processing these bundles.
  619. """
  620. config_storage_class = DictConfigStorage
  621. def __init__(self, directory=None, url=None, **more_config):
  622. super(Environment, self).__init__(**more_config)
  623. if directory is not None:
  624. self.directory = directory
  625. if url is not None:
  626. self.url = url
  627. def parse_debug_value(value):
  628. """Resolve the given string value to a debug option.
  629. Can be used to deal with os environment variables, for example.
  630. """
  631. if value is None:
  632. return value
  633. value = value.lower()
  634. if value in ('true', '1'):
  635. return True
  636. elif value in ('false', '0'):
  637. return False
  638. elif value in ('merge',):
  639. return 'merge'
  640. else:
  641. raise ValueError()