view piecrust/sources/prose.py @ 1188:a7c43131d871

bake: Fix file write flushing problem with Python 3.8+ Writing the cache files fails in Python 3.8 because it looks like flushing behaviour has changed. We need to explicitly flush. And even then, in very rare occurrences, it looks like it can still run into racing conditions, so we do a very hacky and ugly "retry" loop when fetching cached data :(
author Ludovic Chabant <ludovic@chabant.com>
date Tue, 15 Jun 2021 22:36:23 -0700
parents a4d7ff2cdc5c
children
line wrap: on
line source

import copy
import logging
from piecrust.sources.default import DefaultContentSource


logger = logging.getLogger(__name__)


class ProseSource(DefaultContentSource):
    SOURCE_NAME = 'prose'

    def __init__(self, app, name, config):
        super().__init__(app, name, config)
        self.config_recipe = config.get('config', {})

    def _createItemMetadata(self, path):
        metadata = super()._createItemMetadata(path)
        config = metadata.setdefault('config', {})
        config.update(self._makeConfig(path))
        return metadata

    def _makeConfig(self, path):
        c = copy.deepcopy(self.config_recipe)
        if c.get('title') == '%first_line%':
            c['title'] = get_first_line(path)
        return c


def get_first_line(path):
    with open(path, 'r') as f:
        while True:
            line = f.readline()
            if not line:
                break
            line = line.strip()
            if not line:
                continue
            return line
    return None