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.
 
 
 

440 lines
14 KiB

  1. # -*- coding: utf-8 -*-
  2. """
  3. Parses & holds information about the site to be generated.
  4. """
  5. import os
  6. import fnmatch
  7. import sys
  8. import urlparse
  9. from functools import wraps
  10. from hyde.exceptions import HydeException
  11. from hyde.fs import FS, File, Folder
  12. from hyde.model import Config
  13. from hyde.util import getLoggerWithNullHandler
  14. def path_normalized(f):
  15. @wraps(f)
  16. def wrapper(self, path):
  17. return f(self, str(path).replace('/', os.sep))
  18. return wrapper
  19. logger = getLoggerWithNullHandler('hyde.engine')
  20. class Processable(object):
  21. """
  22. A node or resource.
  23. """
  24. def __init__(self, source):
  25. super(Processable, self).__init__()
  26. self.source = FS.file_or_folder(source)
  27. self.is_processable = True
  28. self.uses_template = True
  29. @property
  30. def name(self):
  31. """
  32. The resource name
  33. """
  34. return self.source.name
  35. def __repr__(self):
  36. return self.path
  37. @property
  38. def path(self):
  39. """
  40. Gets the source path of this node.
  41. """
  42. return self.source.path
  43. class Resource(Processable):
  44. """
  45. Represents any file that is processed by hyde
  46. """
  47. def __init__(self, source_file, node):
  48. super(Resource, self).__init__(source_file)
  49. self.source_file = source_file
  50. if not node:
  51. raise HydeException("Resource cannot exist without a node")
  52. if not source_file:
  53. raise HydeException("Source file is required"
  54. " to instantiate a resource")
  55. self.node = node
  56. self.site = node.site
  57. self._relative_deploy_path = None
  58. @property
  59. def relative_path(self):
  60. """
  61. Gets the path relative to the root folder (Content)
  62. """
  63. return self.source_file.get_relative_path(self.node.root.source_folder)
  64. @property
  65. def slug(self):
  66. #TODO: Add a more sophisticated slugify method
  67. return self.source.name_without_extension
  68. def get_relative_deploy_path(self):
  69. """
  70. Gets the path where the file will be created
  71. after its been processed.
  72. """
  73. return self._relative_deploy_path \
  74. if self._relative_deploy_path \
  75. else self.relative_path
  76. def set_relative_deploy_path(self, path):
  77. """
  78. Sets the path where the file ought to be created
  79. after its been processed.
  80. """
  81. self._relative_deploy_path = path
  82. self.site.content.resource_deploy_path_changed(self)
  83. relative_deploy_path = property(get_relative_deploy_path, set_relative_deploy_path)
  84. url = relative_deploy_path
  85. @property
  86. def full_url(self):
  87. """
  88. Returns the full url for the resource.
  89. """
  90. return self.site.full_url(self.relative_path)
  91. class Node(Processable):
  92. """
  93. Represents any folder that is processed by hyde
  94. """
  95. def __init__(self, source_folder, parent=None):
  96. super(Node, self).__init__(source_folder)
  97. if not source_folder:
  98. raise HydeException("Source folder is required"
  99. " to instantiate a node.")
  100. self.root = self
  101. self.module = None
  102. self.site = None
  103. self.source_folder = Folder(str(source_folder))
  104. self.parent = parent
  105. if parent:
  106. self.root = self.parent.root
  107. self.module = self.parent.module if self.parent.module else self
  108. self.site = parent.site
  109. self.child_nodes = []
  110. self.resources = []
  111. def contains_resource(self, resource_name):
  112. """
  113. Returns True if the given resource name exists as a file
  114. in this node's source folder.
  115. """
  116. return File(self.source_folder.child(resource_name)).exists
  117. def get_resource(self, resource_name):
  118. """
  119. Gets the resource if the given resource name exists as a file
  120. in this node's source folder.
  121. """
  122. if self.contains_resource(resource_name):
  123. return self.root.resource_from_path(
  124. self.source_folder.child(resource_name))
  125. return None
  126. def add_child_node(self, folder):
  127. """
  128. Creates a new child node and adds it to the list of child nodes.
  129. """
  130. if folder.parent != self.source_folder:
  131. raise HydeException("The given folder [%s] is not a"
  132. " direct descendant of [%s]" %
  133. (folder, self.source_folder))
  134. node = Node(folder, self)
  135. self.child_nodes.append(node)
  136. return node
  137. def add_child_resource(self, afile):
  138. """
  139. Creates a new resource and adds it to the list of child resources.
  140. """
  141. if afile.parent != self.source_folder:
  142. raise HydeException("The given file [%s] is not"
  143. " a direct descendant of [%s]" %
  144. (afile, self.source_folder))
  145. resource = Resource(afile, self)
  146. self.resources.append(resource)
  147. return resource
  148. def walk(self):
  149. """
  150. Walks the node, first yielding itself then
  151. yielding the child nodes depth-first.
  152. """
  153. yield self
  154. for child in self.child_nodes:
  155. for node in child.walk():
  156. yield node
  157. def walk_resources(self):
  158. """
  159. Walks the resources in this hierarchy.
  160. """
  161. for node in self.walk():
  162. for resource in node.resources:
  163. yield resource
  164. @property
  165. def relative_path(self):
  166. """
  167. Gets the path relative to the root folder (Content, Media, Layout)
  168. """
  169. return self.source_folder.get_relative_path(self.root.source_folder)
  170. @property
  171. def url(self):
  172. return '/' + self.relative_path
  173. @property
  174. def full_url(self):
  175. return self.site.full_url(self.relative_path)
  176. class RootNode(Node):
  177. """
  178. Represents one of the roots of site: Content, Media or Layout
  179. """
  180. def __init__(self, source_folder, site):
  181. super(RootNode, self).__init__(source_folder)
  182. self.site = site
  183. self.node_map = {}
  184. self.node_deploy_map = {}
  185. self.resource_map = {}
  186. self.resource_deploy_map = {}
  187. @path_normalized
  188. def node_from_path(self, path):
  189. """
  190. Gets the node that maps to the given path.
  191. If no match is found it returns None.
  192. """
  193. if Folder(path) == self.source_folder:
  194. return self
  195. return self.node_map.get(str(Folder(path)), None)
  196. @path_normalized
  197. def node_from_relative_path(self, relative_path):
  198. """
  199. Gets the content node that maps to the given relative path.
  200. If no match is found it returns None.
  201. """
  202. return self.node_from_path(
  203. self.source_folder.child(str(relative_path)))
  204. @path_normalized
  205. def resource_from_path(self, path):
  206. """
  207. Gets the resource that maps to the given path.
  208. If no match is found it returns None.
  209. """
  210. return self.resource_map.get(str(File(path)), None)
  211. @path_normalized
  212. def resource_from_relative_path(self, relative_path):
  213. """
  214. Gets the content resource that maps to the given relative path.
  215. If no match is found it returns None.
  216. """
  217. return self.resource_from_path(
  218. self.source_folder.child(str(relative_path)))
  219. def resource_deploy_path_changed(self, resource):
  220. """
  221. Handles the case where the relative deploy path of a
  222. resource has changed.
  223. """
  224. self.resource_deploy_map[str(resource.relative_deploy_path)] = resource
  225. @path_normalized
  226. def resource_from_relative_deploy_path(self, relative_deploy_path):
  227. """
  228. Gets the content resource whose deploy path maps to
  229. the given relative path. If no match is found it returns None.
  230. """
  231. if relative_deploy_path in self.resource_deploy_map:
  232. return self.resource_deploy_map[relative_deploy_path]
  233. return self.resource_from_relative_path(relative_deploy_path)
  234. def add_node(self, a_folder):
  235. """
  236. Adds a new node to this folder's hierarchy.
  237. Also adds to to the hashtable of path to node associations
  238. for quick lookup.
  239. """
  240. folder = Folder(a_folder)
  241. node = self.node_from_path(folder)
  242. if node:
  243. logger.debug("Node exists at [%s]" % node.relative_path)
  244. return node
  245. if not folder.is_descendant_of(self.source_folder):
  246. raise HydeException("The given folder [%s] does not"
  247. " belong to this hierarchy [%s]" %
  248. (folder, self.source_folder))
  249. p_folder = folder
  250. parent = None
  251. hierarchy = []
  252. while not parent:
  253. hierarchy.append(p_folder)
  254. p_folder = p_folder.parent
  255. parent = self.node_from_path(p_folder)
  256. hierarchy.reverse()
  257. node = parent if parent else self
  258. for h_folder in hierarchy:
  259. node = node.add_child_node(h_folder)
  260. self.node_map[str(h_folder)] = node
  261. logger.debug("Added node [%s] to [%s]" % (
  262. node.relative_path, self.source_folder))
  263. return node
  264. def add_resource(self, a_file):
  265. """
  266. Adds a file to the parent node. Also adds to to the
  267. hashtable of path to resource associations for quick lookup.
  268. """
  269. afile = File(a_file)
  270. resource = self.resource_from_path(afile)
  271. if resource:
  272. logger.debug("Resource exists at [%s]" % resource.relative_path)
  273. return resource
  274. if not afile.is_descendant_of(self.source_folder):
  275. raise HydeException("The given file [%s] does not reside"
  276. " in this hierarchy [%s]" %
  277. (afile, self.source_folder))
  278. node = self.node_from_path(afile.parent)
  279. if not node:
  280. node = self.add_node(afile.parent)
  281. resource = node.add_child_resource(afile)
  282. self.resource_map[str(afile)] = resource
  283. logger.debug("Added resource [%s] to [%s]" %
  284. (resource.relative_path, self.source_folder))
  285. return resource
  286. def load(self):
  287. """
  288. Walks the `source_folder` and loads the sitemap.
  289. Creates nodes and resources, reads metadata and injects attributes.
  290. This is the model for hyde.
  291. """
  292. if not self.source_folder.exists:
  293. raise HydeException("The given source folder [%s]"
  294. " does not exist" % self.source_folder)
  295. with self.source_folder.walker as walker:
  296. @walker.folder_visitor
  297. def visit_folder(folder):
  298. self.add_node(folder)
  299. @walker.file_visitor
  300. def visit_file(afile):
  301. for pattern in self.site.config.ignore:
  302. if fnmatch.fnmatch(afile.name, pattern):
  303. return
  304. self.add_resource(afile)
  305. class Site(object):
  306. """
  307. Represents the site to be generated.
  308. """
  309. def __init__(self, sitepath=None, config=None):
  310. super(Site, self).__init__()
  311. self.sitepath = Folder(Folder(sitepath).fully_expanded_path)
  312. # Add sitepath to the list of module search paths so that
  313. # local plugins can be included.
  314. sys.path.insert(0, self.sitepath.fully_expanded_path)
  315. self.config = config if config else Config(self.sitepath)
  316. self.content = RootNode(self.config.content_root_path, self)
  317. self.plugins = []
  318. self.context = {}
  319. def refresh_config(self):
  320. """
  321. Refreshes config data if one or more config files have
  322. changed. Note that this does not refresh the meta data.
  323. """
  324. if self.config.needs_refresh():
  325. logger.debug("Refreshing config data")
  326. self.config = Config(self.sitepath,
  327. self.config.config_file,
  328. self.config.config_dict)
  329. def reload_if_needed(self):
  330. """
  331. Reloads if the site has not been loaded before or if the
  332. configuration has changed since the last load.
  333. """
  334. if not len(self.content.child_nodes):
  335. self.load()
  336. def load(self):
  337. """
  338. Walks the content and media folders to load up the sitemap.
  339. """
  340. self.content.load()
  341. def content_url(self, path):
  342. """
  343. Returns the content url by appending the base url from the config
  344. with the given path.
  345. """
  346. return Folder(self.config.base_url).child(path).replace(os.sep, '/')
  347. def media_url(self, path):
  348. """
  349. Returns the media url by appending the media base url from the config
  350. with the given path.
  351. """
  352. return Folder(self.config.media_url).child(path).replace(os.sep, '/')
  353. def full_url(self, path):
  354. """
  355. Determines if the given path is media or content based on the
  356. configuration and returns the appropriate url.
  357. """
  358. if urlparse.urlparse(path)[:2] != ("",""):
  359. return path
  360. if self.is_media(path):
  361. relative_path = File(path).get_relative_path(
  362. Folder(self.config.media_root))
  363. return self.media_url(relative_path)
  364. else:
  365. return self.content_url(path)
  366. def is_media(self, path):
  367. """
  368. Given the relative path, determines if it is content or media.
  369. """
  370. folder = self.content.source.child_folder(path)
  371. return folder.is_descendant_of(self.config.media_root_path)