A fork of hyde, the static site generation. Some patches will be pushed upstream.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

313 lines
11 KiB

  1. # -*- coding: utf-8 -*-
  2. """
  3. The generator class and related utility functions.
  4. """
  5. from hyde.exceptions import HydeException
  6. from hyde.fs import File, Folder
  7. from hyde.model import Context, Dependents
  8. from hyde.plugin import Plugin
  9. from hyde.template import Template
  10. from hyde.site import Node, Resource
  11. from contextlib import contextmanager
  12. from hyde.util import getLoggerWithNullHandler
  13. logger = getLoggerWithNullHandler('hyde.engine')
  14. class Generator(object):
  15. """
  16. Generates output from a node or resource.
  17. """
  18. def __init__(self, site):
  19. super(Generator, self).__init__()
  20. self.site = site
  21. self.generated_once = False
  22. self.deps = Dependents(site.sitepath)
  23. self.__context__ = dict(site=site)
  24. if hasattr(site.config, 'context'):
  25. site.context = Context.load(site.sitepath, site.config.context)
  26. self.__context__.update(site.context)
  27. self.template = None
  28. Plugin.load_all(site)
  29. self.events = Plugin.get_proxy(self.site)
  30. @contextmanager
  31. def context_for_resource(self, resource):
  32. """
  33. Context manager that intializes the context for a given
  34. resource and rolls it back after the resource is processed.
  35. """
  36. # TODO: update metadata and other resource
  37. # specific properties here.
  38. self.__context__.update(resource=resource)
  39. yield self.__context__
  40. self.__context__.update(resource=None)
  41. def context_for_path(self, path):
  42. resource = self.site.resource_from_path(path)
  43. if not resource:
  44. return {}
  45. ctx = self.__context__.copy
  46. ctx.resource = resource
  47. return ctx
  48. def load_template_if_needed(self):
  49. """
  50. Loads and configures the template environement from the site
  51. configuration if its not done already.
  52. """
  53. class GeneratorProxy(object):
  54. """
  55. An interface to templates and plugins for
  56. providing restricted access to the methods.
  57. """
  58. def __init__(self, preprocessor=None, postprocessor=None, context_for_path=None):
  59. self.preprocessor = preprocessor
  60. self.postprocessor = postprocessor
  61. self.context_for_path = context_for_path
  62. if not self.template:
  63. logger.info("Generating site at [%s]" % self.site.sitepath)
  64. self.template = Template.find_template(self.site)
  65. logger.debug("Using [%s] as the template",
  66. self.template.__class__.__name__)
  67. logger.info("Configuring the template environment")
  68. self.template.configure(self.site,
  69. engine=GeneratorProxy(
  70. context_for_path=self.context_for_path,
  71. preprocessor=self.events.begin_text_resource,
  72. postprocessor=self.events.text_resource_complete))
  73. self.events.template_loaded(self.template)
  74. def initialize(self):
  75. """
  76. Start Generation. Perform setup tasks and inform plugins.
  77. """
  78. logger.info("Begin Generation")
  79. self.events.begin_generation()
  80. def load_site_if_needed(self):
  81. """
  82. Checks if the site requries a reload and loads if
  83. necessary.
  84. """
  85. #TODO: Perhaps this is better suited in Site
  86. if not len(self.site.content.child_nodes):
  87. logger.info("Reading site contents")
  88. self.site.load()
  89. def finalize(self):
  90. """
  91. Generation complete. Inform plugins and cleanup.
  92. """
  93. logger.info("Generation Complete")
  94. self.events.generation_complete()
  95. def get_dependencies(self, resource):
  96. """
  97. Gets the dependencies for a given resource.
  98. """
  99. rel_path = resource.relative_path
  100. deps = []
  101. if not rel_path in self.deps:
  102. if hasattr(resource, 'depends'):
  103. user_deps = resource.depends
  104. for dep in user_deps:
  105. deps.append(dep)
  106. deps.extend(self.template.get_dependencies(dep))
  107. deps.extend(self.template.get_dependencies(resource.relative_path))
  108. deps = list(set(deps))
  109. if None in deps:
  110. deps.remove(None)
  111. self.deps[rel_path] = deps
  112. else:
  113. deps = self.deps[rel_path]
  114. return deps
  115. def has_resource_changed(self, resource):
  116. """
  117. Checks if the given resource has changed since the
  118. last generation.
  119. """
  120. logger.debug("Checking for changes in %s" % resource)
  121. self.load_site_if_needed()
  122. self.load_template_if_needed()
  123. target = File(self.site.config.deploy_root_path.child(
  124. resource.relative_deploy_path))
  125. if not target.exists or target.older_than(resource.source_file):
  126. logger.debug("Found changes in %s" % resource)
  127. return True
  128. if resource.source_file.is_binary or not resource.uses_template:
  129. logger.debug("No Changes found in %s" % resource)
  130. return False
  131. deps = self.get_dependencies(resource)
  132. if not deps or None in deps:
  133. logger.debug("No changes found in %s" % resource)
  134. return False
  135. content = self.site.content.source_folder
  136. layout = Folder(self.site.sitepath).child_folder('layout')
  137. logger.debug("Checking for changes in dependents:%s" % deps)
  138. for dep in deps:
  139. if not dep:
  140. return True
  141. source = File(content.child(dep))
  142. if not source.exists:
  143. source = File(layout.child(dep))
  144. if not source.exists:
  145. return True
  146. if target.older_than(source):
  147. return True
  148. logger.debug("No changes found in %s" % resource)
  149. return False
  150. def generate_all(self, incremental=False):
  151. """
  152. Generates the entire website
  153. """
  154. logger.info("Reading site contents")
  155. self.load_template_if_needed()
  156. self.initialize()
  157. self.load_site_if_needed()
  158. self.events.begin_site()
  159. logger.info("Generating site to [%s]" %
  160. self.site.config.deploy_root_path)
  161. self.__generate_node__(self.site.content, incremental)
  162. self.events.site_complete()
  163. self.finalize()
  164. self.generated_once = True
  165. def generate_node_at_path(self, node_path=None, incremental=False):
  166. """
  167. Generates a single node. If node_path is non-existent or empty,
  168. generates the entire site.
  169. """
  170. if not self.generated_once and not incremental:
  171. return self.generate_all()
  172. self.load_template_if_needed()
  173. self.load_site_if_needed()
  174. node = None
  175. if node_path:
  176. node = self.site.content.node_from_path(node_path)
  177. self.generate_node(node, incremental)
  178. @contextmanager
  179. def events_for(self, obj):
  180. if not self.generated_once:
  181. self.events.begin_site()
  182. if isinstance(obj, Resource):
  183. self.events.begin_node(obj.node)
  184. yield
  185. if not self.generated_once:
  186. if isinstance(obj, Resource):
  187. self.events.node_complete(obj.node)
  188. self.events.site_complete()
  189. def generate_node(self, node=None, incremental=False):
  190. """
  191. Generates the given node. If node is invalid, empty or
  192. non-existent, generates the entire website.
  193. """
  194. if not node or not self.generated_once and not incremental:
  195. return self.generate_all()
  196. self.load_template_if_needed()
  197. self.initialize()
  198. self.load_site_if_needed()
  199. try:
  200. with self.events_for(node):
  201. self.__generate_node__(node, incremental)
  202. self.finalize()
  203. except HydeException:
  204. self.generate_all()
  205. def generate_resource_at_path(self,
  206. resource_path=None,
  207. incremental=False):
  208. """
  209. Generates a single resource. If resource_path is non-existent or empty,
  210. generats the entire website.
  211. """
  212. if not self.generated_once and not incremental:
  213. return self.generate_all()
  214. self.load_template_if_needed()
  215. self.load_site_if_needed()
  216. resource = None
  217. if resource_path:
  218. resource = self.site.content.resource_from_path(resource_path)
  219. self.generate_resource(resource, incremental)
  220. def generate_resource(self, resource=None, incremental=False):
  221. """
  222. Generates the given resource. If resource is invalid, empty or
  223. non-existent, generates the entire website.
  224. """
  225. if not resource or not self.generated_once and not incremental:
  226. return self.generate_all()
  227. self.load_template_if_needed()
  228. self.initialize()
  229. self.load_site_if_needed()
  230. try:
  231. with self.events_for(resource):
  232. self.__generate_resource__(resource, incremental)
  233. except HydeException:
  234. self.generate_all()
  235. def __generate_node__(self, node, incremental=False):
  236. for node in node.walk():
  237. logger.debug("Generating Node [%s]", node)
  238. self.events.begin_node(node)
  239. for resource in node.resources:
  240. self.__generate_resource__(resource, incremental)
  241. self.events.node_complete(node)
  242. def __generate_resource__(self, resource, incremental=False):
  243. if not resource.is_processable:
  244. logger.debug("Skipping [%s]", resource)
  245. return
  246. if incremental and not self.has_resource_changed(resource):
  247. logger.debug("No changes found. Skipping resource [%s]", resource)
  248. return
  249. logger.debug("Processing [%s]", resource)
  250. with self.context_for_resource(resource) as context:
  251. if resource.source_file.is_text:
  252. if resource.uses_template:
  253. logger.debug("Rendering [%s]", resource)
  254. try:
  255. text = self.template.render_resource(resource,
  256. context)
  257. except Exception:
  258. logger.error("Error occurred when"
  259. " processing template:[%s]" % resource)
  260. raise
  261. else:
  262. text = resource.source_file.read_all()
  263. text = self.events.begin_text_resource(resource, text) or text
  264. text = self.events.text_resource_complete(
  265. resource, text) or text
  266. target = File(self.site.config.deploy_root_path.child(
  267. resource.relative_deploy_path))
  268. target.parent.make()
  269. target.write(text)
  270. else:
  271. logger.debug("Copying binary file [%s]", resource)
  272. self.events.begin_binary_resource(resource)
  273. target = File(self.site.config.deploy_root_path.child(
  274. resource.relative_deploy_path))
  275. target.parent.make()
  276. resource.source_file.copy_to(target)
  277. self.events.binary_resource_complete(resource)