#!/usr/bin/env python3 import os from io import TextIOWrapper import shutil import sys import re NAVBAR_FMT = ''' ''' NAVBAR_LINES = NAVBAR_FMT.split('\n') SELECT_FMT = ' <' def token_to_str(token: str, current_source: str) -> str: if token == 'NAVBAR': fmt_strs = [] href_re = re.compile('href\\="(.+)"') current_href = '' for line in NAVBAR_LINES: m = href_re.search(line) if m is not None: current_href = m.group(1) if '{}' in line: if (f'src{current_href}' == current_source): fmt_strs.append(SELECT_FMT) else: fmt_strs.append('') if current_source.startswith('src/blog'): navbar_fmt = NAVBAR_FMT.replace('BLOG_OPEN', 'open') else: navbar_fmt = NAVBAR_FMT.replace('BLOG_OPEN', '') print(fmt_strs) return navbar_fmt.format(*fmt_strs) elif token.endswith('.html'): return open('includes/' + token).read() else: return '{{' + token + '}}' def replace_line(line: str, current_source: str) -> (str, int): ret = '' count = 0 replacing = False token = '' i = 0 while i < (len(line) - 2): if replacing: if line[i:i+2] == r'}}': replacing = False ret += token_to_str(token, current_source) i += 2 token = '' count += 1 else: token += line[i] i += 1 else: if line[i:i+2] == r'{{': replacing = True i += 2 else: ret += line[i] i += 1 if replacing: ret += '{{' + token ret += line[i:] return (ret, count) def stream_template(in_fd: TextIOWrapper, out_fd: TextIOWrapper, current_source: str) -> int: replacements = 0 while True: line = in_fd.readline() if line == '': break new_line, count = replace_line(line, current_source) out_fd.write(new_line) replacements += count return replacements def source_dir_to_output(source_dir: str, output_dir: str): sources = os.listdir(source_dir) if not os.path.isdir(output_dir): os.mkdir(output_dir) for source in sources: source_full = f'{source_dir}/{source}' output_full = f'{output_dir}/{source}' if os.path.isdir(source_full): source_dir_to_output(source_full, output_full) continue if source_full.endswith('.html'): in_fd = open(source_full, 'r') out_fd = open(output_full, 'w') stream_template(in_fd, out_fd, source_full) else: shutil.copy(source_full, output_full) def main(): print(NAVBAR_FMT) includes = os.listdir('includes') sources = os.listdir('src') print(includes) print(sources) source_dir_to_output('src', 'public') if __name__ == '__main__': main()