Skip to content
This repository
Browse code

Added the ability to automatically generate archive pages.

  • Loading branch information...
commit dc4f0704394b693fa8d1359a071ff05530e73207 1 parent f625154
Andrew Fricke authored

Showing 3 changed files with 66 additions and 42 deletions. Show diff stats Hide diff stats

  1. +0 26 mynt/containers.py
  2. +59 16 mynt/core.py
  3. +7 0 mynt/utils.py
26 mynt/containers.py
@@ -2,7 +2,6 @@
2 2
3 3 from __future__ import unicode_literals
4 4
5   -from collections import OrderedDict
6 5 from datetime import datetime
7 6 import re
8 7
@@ -18,26 +17,6 @@
18 17 logger = get_logger('mynt')
19 18
20 19
21   -class Archives(object):
22   - posts = OrderedDict()
23   -
24   -
25   - def __init__(self, posts):
26   - for post in posts:
27   - year, month = datetime.utcfromtimestamp(post['timestamp']).strftime('%Y %B').decode('utf-8').split()
28   -
29   - if year not in self.posts:
30   - self.posts[year] = OrderedDict({month: [post]})
31   - elif month not in self.posts[year]:
32   - self.posts[year][month] = [post]
33   - else:
34   - self.posts[year][month].append(post)
35   -
36   -
37   - def __iter__(self):
38   - for year, months in self.posts.iteritems():
39   - yield (year, months.items())
40   -
41 20 class Config(dict):
42 21 def __init__(self, string):
43 22 super(Config, self).__init__()
@@ -93,8 +72,3 @@ def _get_date(self, mtime, date):
93 72 d[4] = '{0:02d}'.format(d[4])
94 73
95 74 return datetime.strptime('-'.join(d), '%Y-%m-%d-%H-%M')
96   -
97   -class Tags(OrderedDict):
98   - def __iter__(self):
99   - for name in super(Tags, self).__iter__():
100   - yield (name, self[name])
75 mynt/core.py
@@ -4,6 +4,7 @@
4 4
5 5 from argparse import ArgumentParser
6 6 from calendar import timegm
  7 +from datetime import datetime
7 8 import logging
8 9 import re
9 10 from time import time
@@ -14,10 +15,10 @@
14 15 from pygments.lexers import get_lexer_by_name
15 16 from pygments.util import ClassNotFound
16 17
17   -from mynt.containers import Archives, Config, Page, Post, Tags
  18 +from mynt.containers import Config, Page, Post
18 19 from mynt.exceptions import ConfigException, OptionException, RendererException
19 20 from mynt.fs import Directory, File
20   -from mynt.utils import get_logger, normpath
  21 +from mynt.utils import get_logger, normpath, OrderedDict
21 22
22 23
23 24 logger = get_logger('mynt')
@@ -25,6 +26,8 @@
25 26
26 27 class Mynt(object):
27 28 config = {
  29 + 'archive_layout': None,
  30 + 'archives_url': '/',
28 31 'assets_url': '/assets',
29 32 'base_url': '/',
30 33 'date_format': '%A, %B %d, %Y',
@@ -40,10 +43,10 @@ class Mynt(object):
40 43 _parser = None
41 44 _renderer = None
42 45
43   - archives = []
  46 + archives = OrderedDict()
44 47 pages = []
45 48 posts = []
46   - tags = Tags()
  49 + tags = OrderedDict()
47 50
48 51
49 52 def __init__(self, args = None):
@@ -85,6 +88,11 @@ def __init__(self, args = None):
85 88 self.renderer.register({'site': self.config})
86 89
87 90
  91 + def _get_archives_url(self, year):
  92 + format = self._get_url_format(self.config['tags_url'].endswith('/'))
  93 +
  94 + return format.format(self.config['archives_url'], year)
  95 +
88 96 def _get_opts(self, args):
89 97 opts = {}
90 98
@@ -145,17 +153,20 @@ def _get_post_url(self, date, slug):
145 153
146 154 return date.strftime(link).decode('utf-8')
147 155
148   - def _get_tag_url(self, name):
149   - end = '/' if self.config['tags_url'].endswith('/') else '.html'
150   -
151   - return '{0}/{1}{2}'.format(self.config['tags_url'], self._slugify(name), end)
152   -
153 156 def _get_renderer(self):
154 157 try:
155 158 return load_entry_point('mynt', 'mynt.renderers', self.config['renderer'])
156 159 except ImportError:
157 160 return __import__('mynt.renderers.{0}'.format(self.config['renderer']), globals(), locals(), ['Renderer'], -1).Renderer
158 161
  162 + def _get_tag_url(self, name):
  163 + format = self._get_url_format(self.config['tags_url'].endswith('/'))
  164 +
  165 + return format.format(self.config['tags_url'], self._slugify(name))
  166 +
  167 + def _get_url_format(self, clean):
  168 + return '{0}{1}/' if clean else '{0}/{1}.html'
  169 +
159 170 def _highlight(self, match):
160 171 language, code = match.groups()
161 172 formatter = HtmlFormatter(linenos = 'table')
@@ -214,36 +225,59 @@ def _parse(self):
214 225 self.tags[tag] = []
215 226
216 227 self.tags[tag].append(data)
  228 +
  229 + def _process(self):
  230 + self._parse()
  231 +
  232 + logger.info('>> Processing')
217 233
218 234 if self.posts:
  235 + logger.debug('.. ordering posts')
  236 +
219 237 self.posts.sort(key = lambda post: post['timestamp'], reverse = True)
220 238
221   - self.archives = Archives(self.posts)
  239 + logger.debug('.. generating archives')
  240 +
  241 + for post in self.posts:
  242 + year, month = datetime.utcfromtimestamp(post['timestamp']).strftime('%Y %B').decode('utf-8').split()
  243 +
  244 + if year not in self.archives:
  245 + self.archives[year] = {
  246 + 'months': OrderedDict({month: [post]}),
  247 + 'url': self._get_archives_url(year),
  248 + 'year': year
  249 + }
  250 + elif month not in self.archives[year]['months']:
  251 + self.archives[year]['months'][month] = [post]
  252 + else:
  253 + self.archives[year]['months'][month].append(post)
  254 +
  255 + logger.debug('.. sorting tags')
222 256
223   - sorting = []
  257 + tags = []
224 258
225 259 for name, posts in self.tags:
226 260 posts.sort(key = lambda post: post['timestamp'], reverse = True)
227 261
228   - sorting.append({
  262 + tags.append({
229 263 'count': len(posts),
230 264 'name': name,
231 265 'posts': posts,
232 266 'url': self._get_tag_url(name)
233 267 })
234 268
235   - sorting.sort(key = lambda tag: tag['name'].lower())
236   - sorting.sort(key = lambda tag: tag['count'], reverse = True)
  269 + tags.sort(key = lambda tag: tag['name'].lower())
  270 + tags.sort(key = lambda tag: tag['count'], reverse = True)
237 271
238 272 self.tags.clear()
239 273
240   - for tag in sorting:
  274 + for tag in tags:
241 275 self.tags[tag['name']] = tag
242 276 else:
243 277 logger.debug('.. no posts found')
244 278
245 279 def _render(self):
246   - self._parse()
  280 + self._process()
247 281
248 282 logger.info('>> Rendering')
249 283
@@ -285,6 +319,15 @@ def _render(self):
285 319 self._get_path(data['url']),
286 320 self._pygmentize(self.renderer.render(self.config['tag_layout'], {'tag': data}))
287 321 ))
  322 +
  323 + if self.config['archive_layout'] and self.archives:
  324 + logger.debug('.. archives')
  325 +
  326 + for year, data in self.archives:
  327 + self.pages.append(Page(
  328 + self._get_path(data['url']),
  329 + self._pygmentize(self.renderer.render(self.config['archive_layout'], {'year': data}))
  330 + ))
288 331
289 332
290 333 def generate(self):
7 mynt/utils.py
@@ -2,6 +2,7 @@
2 2
3 3 from __future__ import unicode_literals
4 4
  5 +from collections import OrderedDict as _OrderedDict
5 6 import logging
6 7 from os import path as op
7 8 from re import match, sub
@@ -47,3 +48,9 @@ def normpath(*args):
47 48 *_cleanpath(*args)
48 49 )
49 50 )
  51 +
  52 +
  53 +class OrderedDict(_OrderedDict):
  54 + def __iter__(self):
  55 + for key in super(OrderedDict, self).__iter__():
  56 + yield (key, self[key])

0 comments on commit dc4f070

Please sign in to comment.
Something went wrong with that request. Please try again.