all repos — nasg @ 82db3907868f2f74b04ea1842e469cd3ef4d3209

nasg.py (view raw)

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
import argparse
import logging
import os
import re
import arrow
import atexit
from concurrent.futures import ProcessPoolExecutor
from multiprocessing import cpu_count
from slugify import slugify

import nasg.config as config
import nasg.singular as singular
import nasg.searchindex as searchindex
import nasg.taxonomy as taxonomy

from pprint import pprint

parser = argparse.ArgumentParser(description='Parameters for NASG')
parser.add_argument(
    '--regenerate', '-f',
    dest='regenerate',
    action='store_true',
    default=False,
    help='force regeneration of all HTML outputs'
)
parser.add_argument(
    '--downsize', '-c',
    action='store_true',
    dest='downsize',
    default=False,
    help='force re-downsizing of all suitable images'
)
parser.add_argument(
    '--debug', '-d',
    action='store_true',
    dest='debug',
    default=False,
    help='turn on debug log'
)

class Engine(object):
    def __init__(self):
        self._initdirs()
        self._lock()
        atexit.register(self._lock, action='clear')
        self.files = []
        self.categories = {}
        self.tags = {}
        self.allposts = taxonomy.TaxonomyHandler('')
        self.frontposts = taxonomy.TaxonomyHandler('')
        self.allowedpattern = re.compile(config.accept_sourcefiles)
        self.counter = {}

    def _parse_results(self, futures):
        for future in futures:
            try:
                future.result()
            except Exception as e:
                logging.error("processing failed: %s", e)


    def collect(self):
        self._setup_categories()
        self._setup_singulars()


    def render(self):
        self._render_singulars()
        #self._render_taxonomy()


    def _render_singulars(self):
        logging.warning("rendering singulars")
        pprint(self.allposts)
        #futures = []
        #with ProcessPoolExecutor(max_workers=cpu_count()) as executor:
        for p in self.allposts:
            #futures.append(executor.submit(p.write))
            p.write()
        #for future in futures:
            #try:
                #future.result()
            #except Exception as e:
                #logging.error("processing failed: %s", e)


    def _render_taxonomy(self):
        futures = []
        with ProcessPoolExecutor(max_workers=cpu_count()) as executor:
            for tslug, t in self.tags.items():
                #t.write()
                futures.append(executor.submit(t.write))
            for cslug, c in self.categories.items():
                #c.write()
                futures.append(executor.submit(c.write))
            #self.frontposts.write()
            futures.append(executor.submit(self.frontposts.write))
        self._parse_results(futures)


    def _setup_categories(self):
        for cat, meta in config.categories.items():
            cpath = os.path.join(config.CONTENT, cat)
            if not os.path.isdir(cpath):
                logging.error("category %s not found at: %s", cat, cpath)
                continue

            self.categories[cat] = taxonomy.TaxonomyHandler(
                meta.get('name', cat),
                taxonomy=meta.get('type', 'category'),
                slug=cat,
                render=meta.get('render', True)
            )


    def _setup_singulars(self):
        futures = []
        with ProcessPoolExecutor(max_workers=cpu_count()) as executor:
            for slug, tax in self.categories.items():
                cpath = os.path.join(config.CONTENT, slug)
                for f in os.listdir(cpath):
                    fpath = os.path.join(cpath,f)
                    if not self.allowedpattern.fullmatch(f):
                        logging.warning("unexpected file at: %s" % fpath)
                        continue
                    #self._posttype(fpath, slug)
                    futures.append(executor.submit(self._posttype, fpath, slug))
        self._parse_results(futures)

    def _posttype(self, fpath, cat):
        c = self.categories[cat]

        if re.match('.*\.jpg', fpath):
            p = singular.PhotoHandler(fpath)
        elif 'page' == c.taxonomy:
            p = singular.PageHandler(fpath)
        else:
            p = singular.ArticleHandler(fpath)

        c.append(p)
        self.allposts.append(p)

        front = config.categories[cat].get('front', True)
        if front:
            self.frontposts.append(p)

        ptags = p.vars.get('tags', [])
        for tag in ptags:
            tslug = slugify(tag, only_ascii=True, lower=True)
            if tslug not in self.tags:
                self.tags[tslug] = taxonomy.TaxonomyHandler(
                    tag,
                    taxonomy='tag',
                    slug=tslug
                )
            self.tags[tslug].append(p)


    def _initdirs(self):
        for d in [
            config.TARGET,
            config.TTHEME,
            config.TFILES,
            config.VAR,
            config.SEARCHDB,
            config.TSDB,
            config.LOGDIR
        ]:
            if not os.path.exists(d):
                os.mkdir(d)


    def _lock(self, action='set'):
        if 'set' == action:
            if os.path.exists(config.LOCKFILE):
                raise ValueError("lockfile %s present" % config.LOCKFILE)
            with open(config.LOCKFILE, "wt") as l:
                l.write("%s" % arrow.utcnow())
                l.close()
        elif 'clear' == action:
            if os.path.exists(config.LOCKFILE):
                os.unlink(config.LOCKFILE)
        else:
            return os.path.exists(config.LOCKFILE)


if __name__ == '__main__':
    config.options.update(vars(parser.parse_args()))
    loglevel = 30
    if config.options['debug']:
        loglevel = 10

    while len(logging.root.handlers) > 0:
        logging.root.removeHandler(logging.root.handlers[-1])

    logging.basicConfig(
        level=loglevel,
        format='%(asctime)s - %(levelname)s - %(message)s'
    )

    engine = Engine()
    engine.collect()
    engine.render()