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.
 
 
 

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