#!/bin/env python3 from os import walk, mkdir from shutil import rmtree, copyfile # {file path = ([contents by line], {backlink filepaths})} file_backlinks = {} # list of file paths other_files = [] # list of directory paths directories = [] source = 'src' public = 'public' # get data for (dir, subdirs, files) in walk(source): for subdir in subdirs: directories += [dir + '/' + subdir] for file in files: if not (file.endswith('.gmi') or file.endswith('.gemini')): other_files += [dir + '/' + file] continue with open(dir + '/' + file, 'r') as f: lines = f.readlines() file_backlinks[(dir + '/' + file)[len(source)+1:]] = (lines, set()) # create backlinks for file in file_backlinks.keys(): for line in file_backlinks[file][0]: if not line.startswith('=>'): continue path = line[2:].strip().split(' ')[0] if path.startswith('gemini://') or path.startswith('http://') or \ path.startswith('https://') or path.startswith('mailto:'): continue if not (path.endswith('.gmi') or path.endswith('.gemini')): continue if path.startswith('/'): path = path[1:] else: if path.startswith('./'): path = path[2:] before = file.split('/') before.pop() while path.startswith('..'): path = path[2:] before.pop() if path.startswith('/'): path = path[1:] path = '/'.join(before) + '/' + path if path.startswith('/'): path = path[1:] try: file_backlinks[path][1].add(file) except: print(f'warning: {path} doesnt exist but is linked to by {file}') # create new public/ try: rmtree(public) except: pass mkdir(public) for dir in directories: mkdir(public + dir[len(source):]) for file in other_files: copyfile(file, public + file[len(source):]) # copy gemini files for file in file_backlinks.keys(): with open(public + '/' + file, 'w') as f: f.writelines(file_backlinks[file][0]) # generate backlinks if they exist if file_backlinks[file][1]: backs = list(file_backlinks[file][1]) backs.sort() f.write('\n## backlinks\n') for link in backs: if link == 'index.gmi': f.write('=> /') else: f.write(f'=> /{link}') if file_backlinks[link][0][0].startswith('# '): f.write(f' {file_backlinks[link][0][0][2:].strip()}\n') else: f.write('\n') else: if file != 'index.gmi': print(f'warning: {file} might be an orphan') # otherwise just say theres no backlinks f.write('\n## backlinks\nno backlinks\n') f.write(''' ## webring => https://stellophiliac.github.io/roboring/0x5fbe/previous previous => https://stellophiliac.github.io/roboring roboring => https://stellophiliac.github.io/roboring/0x5fbe/next next ▌▖▌▖▘▖▖▌▌ ''') copyfile('preprocessor.py', 'public/preprocessor.py') print('done')