def compile_post(path): """ Compile a markdown post. """ with open(path, 'r') as f: raw = f.read() parts = path.split('/') category = parts[-2] slug = parts[-1].replace('.md', '') raw, meta = extract_metadata(raw) html = compile_markdown(raw) data = { 'plain': raw, 'html': html, 'slug': slug, 'category': category, 'url': '/{}/{}'.format(category, slug) } data.update(meta) for k, v in data.items(): if isinstance(v, datetime): data[k] = v.isoformat() # Lead with the published timestamp so the # built files are in the right order data['build_slug'] = '{2}/{0}{1}_{3}'.format('D' if meta['draft'] else '', meta['published_ts'], category, slug) return data
def extract_metadata(raw): """ Extract metadata from raw markdown content. Returns the content with metadata removed and the extracted metadata. """ # Defaults meta = { 'title': '', 'published_at': datetime.now(), 'draft': False } # Try to extract metadata, specified as YAML front matter meta_match = meta_re.search(raw) if meta_match is not None: meta_raw = meta_match.group(1) try: ext_meta = yaml.load(meta_raw) meta.update(ext_meta) # Remove the metadata before we compile raw = meta_re.sub('', raw).strip() except yaml.scanner.ScannerError: pass # Convert to bool if necessary if isinstance(meta['draft'], str): meta['draft'] = strtobool(meta['draft']) # Convert to timestamp if necessary if isinstance(meta['published_at'], str): meta['published_at'] = parse(meta['published_at']) meta['published_ts'] = int(meta['published_at'].timestamp()) # Try to extract title title_match = title_re.search(raw) if title_match is not None: meta['title'] = title_match.group(1) meta['title_html'] = compile_markdown(meta['title']) # Remove the title before we compile raw = title_re.sub('', raw).strip() return raw, meta
def extract_metadata(raw): """ Extract metadata from raw markdown content. Returns the content with metadata removed and the extracted metadata. """ # Defaults meta = {'title': '', 'published_at': datetime.now(), 'draft': False} # Try to extract metadata, specified as YAML front matter meta_match = meta_re.search(raw) if meta_match is not None: meta_raw = meta_match.group(1) try: ext_meta = yaml.load(meta_raw) meta.update(ext_meta) # Remove the metadata before we compile raw = meta_re.sub('', raw).strip() except yaml.scanner.ScannerError: pass # Convert to bool if necessary if isinstance(meta['draft'], str): meta['draft'] = strtobool(meta['draft']) # Convert to timestamp if necessary if isinstance(meta['published_at'], str): meta['published_at'] = parse(meta['published_at']) meta['published_ts'] = int(meta['published_at'].timestamp()) # Try to extract title title_match = title_re.search(raw) if title_match is not None: meta['title'] = title_match.group(1) meta['title_html'] = compile_markdown(meta['title']) # Remove the title before we compile raw = title_re.sub('', raw).strip() return raw, meta