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.
 
 
 

462 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. @property
  31. def name(self):
  32. """
  33. The resource name
  34. """
  35. return self.source.name
  36. def __repr__(self):
  37. return self.path
  38. @property
  39. def path(self):
  40. """
  41. Gets the source path of this node.
  42. """
  43. return self.source.path
  44. class Resource(Processable):
  45. """
  46. Represents any file that is processed by hyde
  47. """
  48. def __init__(self, source_file, node):
  49. super(Resource, self).__init__(source_file)
  50. self.source_file = source_file
  51. if not node:
  52. raise HydeException("Resource cannot exist without a node")
  53. if not source_file:
  54. raise HydeException("Source file is required"
  55. " to instantiate a resource")
  56. self.node = node
  57. self.site = node.site
  58. self._relative_deploy_path = None
  59. @property
  60. def relative_path(self):
  61. """
  62. Gets the path relative to the root folder (Content)
  63. """
  64. return self.source_file.get_relative_path(self.node.root.source_folder)
  65. @property
  66. def slug(self):
  67. #TODO: Add a more sophisticated slugify method
  68. return self.source.name_without_extension
  69. def get_relative_deploy_path(self):
  70. """
  71. Gets the path where the file will be created
  72. after its been processed.
  73. """
  74. return self._relative_deploy_path \
  75. if self._relative_deploy_path \
  76. else self.relative_path
  77. def set_relative_deploy_path(self, path):
  78. """
  79. Sets the path where the file ought to be created
  80. after its been processed.
  81. """
  82. self._relative_deploy_path = path
  83. self.site.content.resource_deploy_path_changed(self)
  84. relative_deploy_path = property(get_relative_deploy_path, set_relative_deploy_path)
  85. url = relative_deploy_path
  86. @property
  87. def full_url(self):
  88. """
  89. Returns the full url for the resource.
  90. """
  91. return self.site.full_url(self.relative_path)
  92. class Node(Processable):
  93. """
  94. Represents any folder that is processed by hyde
  95. """
  96. def __init__(self, source_folder, parent=None):
  97. super(Node, self).__init__(source_folder)
  98. if not source_folder:
  99. raise HydeException("Source folder is required"
  100. " to instantiate a node.")
  101. self.root = self
  102. self.module = None
  103. self.site = None
  104. self.source_folder = Folder(unicode(source_folder))
  105. self.parent = parent
  106. if parent:
  107. self.root = self.parent.root
  108. self.module = self.parent.module if self.parent.module else self
  109. self.site = parent.site
  110. self.child_nodes = []
  111. self.resources = []
  112. def contains_resource(self, resource_name):
  113. """
  114. Returns True if the given resource name exists as a file
  115. in this node's source folder.
  116. """
  117. return File(self.source_folder.child(resource_name)).exists
  118. def get_resource(self, resource_name):
  119. """
  120. Gets the resource if the given resource name exists as a file
  121. in this node's source folder.
  122. """
  123. if self.contains_resource(resource_name):
  124. return self.root.resource_from_path(
  125. self.source_folder.child(resource_name))
  126. return None
  127. def add_child_node(self, folder):
  128. """
  129. Creates a new child node and adds it to the list of child nodes.
  130. """
  131. if folder.parent != self.source_folder:
  132. raise HydeException("The given folder [%s] is not a"
  133. " direct descendant of [%s]" %
  134. (folder, self.source_folder))
  135. node = Node(folder, self)
  136. self.child_nodes.append(node)
  137. return node
  138. def add_child_resource(self, afile):
  139. """
  140. Creates a new resource and adds it to the list of child resources.
  141. """
  142. if afile.parent != self.source_folder:
  143. raise HydeException("The given file [%s] is not"
  144. " a direct descendant of [%s]" %
  145. (afile, self.source_folder))
  146. resource = Resource(afile, self)
  147. self.resources.append(resource)
  148. return resource
  149. def walk(self):
  150. """
  151. Walks the node, first yielding itself then
  152. yielding the child nodes depth-first.
  153. """
  154. yield self
  155. for child in self.child_nodes:
  156. for node in child.walk():
  157. yield node
  158. def walk_resources(self):
  159. """
  160. Walks the resources in this hierarchy.
  161. """
  162. for node in self.walk():
  163. for resource in node.resources:
  164. yield resource
  165. @property
  166. def relative_path(self):
  167. """
  168. Gets the path relative to the root folder (Content, Media, Layout)
  169. """
  170. return self.source_folder.get_relative_path(self.root.source_folder)
  171. @property
  172. def url(self):
  173. return '/' + self.relative_path
  174. @property
  175. def full_url(self):
  176. return self.site.full_url(self.relative_path)
  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 resource_deploy_path_changed(self, resource):
  221. """
  222. Handles the case where the relative deploy path of a
  223. resource has changed.
  224. """
  225. self.resource_deploy_map[unicode(resource.relative_deploy_path)] = resource
  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) for pattern in self.site.config.simple_copy)
  286. logger.debug("Added resource [%s] to [%s]" %
  287. (resource.relative_path, self.source_folder))
  288. return resource
  289. def load(self):
  290. """
  291. Walks the `source_folder` and loads the sitemap.
  292. Creates nodes and resources, reads metadata and injects attributes.
  293. This is the model for hyde.
  294. """
  295. if not self.source_folder.exists:
  296. raise HydeException("The given source folder [%s]"
  297. " does not exist" % self.source_folder)
  298. with self.source_folder.walker as walker:
  299. def dont_ignore(name):
  300. for pattern in self.site.config.ignore:
  301. if fnmatch.fnmatch(name, pattern):
  302. return False
  303. return True
  304. @walker.folder_visitor
  305. def visit_folder(folder):
  306. if dont_ignore(folder.name):
  307. self.add_node(folder)
  308. else:
  309. logger.debug("Ignoring node: %s" % folder.name)
  310. return False
  311. @walker.file_visitor
  312. def visit_file(afile):
  313. if dont_ignore(afile.name):
  314. self.add_resource(afile)
  315. class Site(object):
  316. """
  317. Represents the site to be generated.
  318. """
  319. def __init__(self, sitepath=None, config=None):
  320. super(Site, self).__init__()
  321. self.sitepath = Folder(Folder(sitepath).fully_expanded_path)
  322. # Add sitepath to the list of module search paths so that
  323. # local plugins can be included.
  324. sys.path.insert(0, self.sitepath.fully_expanded_path)
  325. self.config = config if config else Config(self.sitepath)
  326. self.content = RootNode(self.config.content_root_path, self)
  327. self.plugins = []
  328. self.context = {}
  329. def refresh_config(self):
  330. """
  331. Refreshes config data if one or more config files have
  332. changed. Note that this does not refresh the meta data.
  333. """
  334. if self.config.needs_refresh():
  335. logger.debug("Refreshing config data")
  336. self.config = Config(self.sitepath,
  337. self.config.config_file,
  338. self.config.config_dict)
  339. def reload_if_needed(self):
  340. """
  341. Reloads if the site has not been loaded before or if the
  342. configuration has changed since the last load.
  343. """
  344. if not len(self.content.child_nodes):
  345. self.load()
  346. def load(self):
  347. """
  348. Walks the content and media folders to load up the sitemap.
  349. """
  350. self.content.load()
  351. def content_url(self, path, safe=None):
  352. """
  353. Returns the content url by appending the base url from the config
  354. with the given path. The return value is url encoded.
  355. """
  356. fpath = Folder(self.config.base_url) \
  357. .child(path) \
  358. .replace(os.sep, '/').encode("utf-8")
  359. if safe is not None:
  360. return quote(fpath, safe)
  361. else:
  362. return quote(fpath)
  363. def media_url(self, path, safe=None):
  364. """
  365. Returns the media url by appending the media base url from the config
  366. with the given path. The return value is url encoded.
  367. """
  368. fpath = Folder(self.config.media_url) \
  369. .child(path) \
  370. .replace(os.sep, '/').encode("utf-8")
  371. if safe is not None:
  372. return quote(fpath, safe)
  373. else:
  374. return quote(fpath)
  375. def full_url(self, path, safe=None):
  376. """
  377. Determines if the given path is media or content based on the
  378. configuration and returns the appropriate url. The return value
  379. is url encoded.
  380. """
  381. if urlparse.urlparse(path)[:2] != ("",""):
  382. return path
  383. if self.is_media(path):
  384. relative_path = File(path).get_relative_path(
  385. Folder(self.config.media_root))
  386. return self.media_url(relative_path, safe)
  387. else:
  388. return self.content_url(path, safe)
  389. def is_media(self, path):
  390. """
  391. Given the relative path, determines if it is content or media.
  392. """
  393. folder = self.content.source.child_folder(path)
  394. return folder.is_descendant_of(self.config.media_root_path)