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.
 
 
 

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