Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code

Unified Diff: cms/utils.py

Issue 29516687: Issue 4488 - Add support for JSON page front matter (Closed) Base URL: https://hg.adblockplus.org/cms
Patch Set: Preserve lines in metadata, fix sort in sitemap.tmpl Created March 26, 2018, 2:28 a.m.
Use n/p to move between diff chunks; N/P to move between comments.
Jump to:
View side-by-side diff with in-line comments
Download patch
Index: cms/utils.py
===================================================================
--- a/cms/utils.py
+++ b/cms/utils.py
@@ -14,6 +14,7 @@
# along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>.
import re
+import json
__all__ = [
'get_page_params',
@@ -65,21 +66,31 @@
Metadata of the page, remaining source text without metadata.
"""
- metadata = {}
- lines = source.splitlines(True)
- for i, line in enumerate(lines):
- if line.strip() in {'<!--', '-->'}:
- lines[i] = ''
- continue
- if not re.search(r'^\s*[\w\-]+\s*=', line):
- break
- name, value = line.split('=', 1)
- value = value.strip()
- if value.startswith('[') and value.endswith(']'):
- value = [element.strip() for element in value[1:-1].split(',')]
- lines[i] = '\n'
- metadata[name.strip()] = value
- return metadata, ''.join(lines)
+ m = re.search(r'^\s*<!--\s*(.*?)-->', source, re.S)
+ text = m.group(1) if m else source
+
+ decoder = json.JSONDecoder()
+ try:
+ metadata, length = decoder.raw_decode(text)
+ except ValueError:
+ metadata = None
+
+ if not isinstance(metadata, dict):
+ metadata = {}
+ length = 0
+ for line in text.splitlines(True):
+ if not re.search(r'^\s*[\w\-]+\s*=', line):
+ break
+ name, value = line.split('=', 1)
+ value = value.strip()
+ if value.startswith('[') and value.endswith(']'):
+ value = [element.strip() for element in value[1:-1].split(',')]
+ metadata[name.strip()] = value
+ length += len(line)
+
+ # Need to preserve line numbers for jinja2 tracebacks
+ cutoff = m.end() if m else length
+ return metadata, '\n' * source.count('\n', 0, cutoff) + source[cutoff:]
Sebastian Noack 2018/03/26 02:57:48 I just noticed one more edge case, if there is an
Vasily Kuznetsov 2018/03/26 09:24:28 Good catch, Sebastian! It probably makes sense to
Jon Sonesen 2018/03/28 03:01:36 Perhaps a test case should be added as well to cov
rosie 2018/03/31 21:09:28 I've implemented Sebastian's suggestion and it wor
Sebastian Noack 2018/03/31 22:07:35 So default.tmpl is empty, and empty.tmpl is not. T
Vasily Kuznetsov 2018/04/03 14:29:19 I suppose we can say that it ended up being so for
rosie 2018/04/18 02:35:32 Acknowledged.
def get_page_params(source, locale, page, format=None, site_url_override=None,

Powered by Google App Engine
This is Rietveld