Created
November 1, 2013 14:42
-
-
Save gardiner/7266406 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
#-*- coding: utf-8 -*- | |
import glob | |
import logging | |
import os | |
import shutil | |
import sys | |
TARGET = os.path.join('template', 'fce') | |
class Slice(object): | |
START = '<!-- SLICE:' | |
STOP = '<!-- ENDSLICE' | |
PAUSE = '<!-- SKIP' | |
PROCEED = '<!-- ENDSKIP' | |
TEMPLATE = """<!DOCTYPE html> | |
<html lang="de"> | |
<head> | |
<meta charset="utf-8" /> | |
<title>FCE</title> | |
<!-- %s --> | |
</head> | |
<body> | |
%s | |
</body> | |
</html>""" | |
def __init__(self, filepath, comment=''): | |
logging.debug('Creating new slice %s', filepath) | |
self._filepath = filepath | |
self._lines = [] | |
self._open = True | |
self._comment = comment | |
def append(self, line): | |
if self._open: | |
self._lines.append(line) | |
def close(self): | |
if self._open: | |
logging.debug('Closing slice %s', self._filepath) | |
with open(self._filepath, 'w') as target: | |
target.write(Slice.TEMPLATE % (self._comment, ''.join(self._lines))) | |
self._open = False | |
def pause(self): | |
self._open = False | |
def proceed(self): | |
self._open = True | |
@staticmethod | |
def create_from(line, target_dir, comment=''): | |
filebase = line.replace(Slice.START, '').replace('-->', '').strip() | |
filename = filebase + '.html' | |
return Slice(os.path.join(target_dir, filename), comment) | |
def slice_file(filename, target_dir): | |
logging.debug('Slicing %r to %r', filename, target_dir) | |
with open(filename) as source: | |
s = None | |
for lineno, line in enumerate(source): | |
if Slice.START in line: | |
if s: | |
s.close() | |
comment = 'Source: %s, line %s' % (filename, lineno + 1) | |
s = Slice.create_from(line, target_dir, comment) | |
elif Slice.STOP in line: | |
if s: | |
s.close() | |
elif Slice.PAUSE in line: | |
if s: | |
s.pause() | |
elif Slice.PROCEED in line: | |
if s: | |
s.proceed() | |
elif s: | |
s.append(line) | |
if s: | |
s.close() | |
def slice_all(source_glob, target_dir): | |
for f in glob.glob(source_glob): | |
slice_file(f, target_dir) | |
if __name__ == '__main__': | |
os.chdir(os.path.join(os.path.dirname(__file__), '..')) | |
if os.path.exists(TARGET): | |
shutil.rmtree(TARGET) | |
os.mkdir(TARGET) | |
root = logging.getLogger() | |
for h in root.handlers[:]: | |
root.removeHandler(h) | |
root.addHandler(logging.StreamHandler()) | |
root.setLevel(logging.DEBUG) | |
slice_all('template/*.html', TARGET) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment