husk/husk_helpers.py

177 lines
5.2 KiB
Python
Raw Normal View History

2023-05-26 10:53:34 +02:00
import glob
2022-09-18 21:00:35 +02:00
import os
2023-05-26 10:53:34 +02:00
# from collections import deque
# import toml
2022-09-18 21:00:35 +02:00
2023-05-26 10:53:34 +02:00
# base_url = toml.load('settings.toml')["general"]["base_url"]
2022-09-06 23:45:26 +02:00
2023-05-24 22:22:53 +02:00
# def sort_branch( lst ):
# '''
# put directories in front of files and
# sorts both alphabetically
2023-05-26 10:53:34 +02:00
# '''
2023-05-24 22:22:53 +02:00
# files = []
# dirs = []
# for path in lst:
# if path.endswith(".md"):
# files.append(path)
# else:
# dirs.append(path)
# files.sort()
# dirs.sort()
2023-05-26 10:53:34 +02:00
# return [*dirs, *files]
2023-05-24 22:22:53 +02:00
def sort_branch(lst):
"""
Puts directories in front of files and sorts both alphabetically.
"""
files = [path for path in lst if path.endswith(".md")]
dirs = [path for path in lst if not path.endswith(".md")]
files.sort()
dirs.sort()
2023-05-24 22:22:53 +02:00
return dirs + files
# def make_tree(path="templates/content"):
# '''
# creates a dictionary of the directories and files of the doc repository
2023-05-26 10:53:34 +02:00
# '''
2023-05-24 22:22:53 +02:00
# if '/' in path:
# tree = dict(name=path, children=[], type="directory")
# else:
# pass
# try: lst = os.listdir(path)
# except OSError:
# pass #ignore errors
# else:
# lst = sort_branch(lst)
# for name in lst:
# fn = os.path.join(path, name)
# if os.path.isdir(fn) and not fn.endswith(".git"):
# if os.listdir(fn): # this line is experimental and needs to be tested
# tree['children'].append(make_tree(fn))
# else:
# if fn.endswith('.md'):
# tree['children'].append(dict(name=fn))
# return tree
2022-09-06 23:45:26 +02:00
def make_tree(path="templates/content"):
2023-05-24 22:22:53 +02:00
"""
Creates a dictionary of the directories and files of the doc repository.
"""
tree = {'name': path, 'children': [], 'type': 'directory'}
try:
lst = os.listdir(path)
lst = sort_branch(lst)
2022-09-06 23:45:26 +02:00
for name in lst:
fn = os.path.join(path, name)
2023-05-24 22:22:53 +02:00
if os.path.isdir(fn) and not fn.endswith(".git") and os.listdir(fn):
tree['children'].append(make_tree(fn))
elif fn.endswith('.md'):
tree['children'].append({'name': fn})
except OSError:
pass # Ignore errors
2022-09-06 23:45:26 +02:00
return tree
2023-05-24 22:22:53 +02:00
2022-10-29 00:15:24 +02:00
def rem_readme(path, tree):
'''
This functions puts out the path of the README.md and
which will be index.html
path can be dynamically configured and may have a / at the end nor not
'''
2023-05-26 10:53:34 +02:00
index = f"{path.rstrip('/')}/README.md"
for item in tree['children']:
if isinstance(item, dict):
for k, v in item.items():
if k == "name":
if v == index:
del tree['children'][-1][k]
2022-10-29 00:15:24 +02:00
return tree
2022-10-20 23:39:10 +02:00
2023-05-26 10:53:34 +02:00
2022-09-06 23:45:26 +02:00
def cut_path_tree(tree, subdir, file_ending):
'''
pruning of the tree structure from make_tree()
'''
2022-09-09 15:41:05 +02:00
if subdir.endswith('/'):
subdir = subdir[:-1]
2022-09-06 23:45:26 +02:00
for key, val in tree.items():
if isinstance(val, list):
for item in val:
item["name"] = item["name"][len(subdir):]
if item["name"].endswith(file_ending):
item["name"] = item["name"][:-len(file_ending)]
if isinstance(item, dict):
cut_path_tree(item, subdir, file_ending)
return tree
2023-05-26 10:53:34 +02:00
2022-09-06 23:45:26 +02:00
def cut_filetype_tree(tree, filetype):
'''
removes file type of the links stored in make_tree()
'''
2022-09-06 23:45:26 +02:00
for key, val in tree.items():
if isinstance(val, list):
for item in val:
if item["name"].endswith(filetype):
item["name"] = item["name"][:-len(filetype)]
if isinstance(item, dict):
cut_filetype_tree(item, filetype)
return tree
2023-05-26 10:53:34 +02:00
# def list_files(path):
# '''
# creates a simple, one dimensional list of the doc repository
# filters markdown files only
2023-05-24 22:22:53 +02:00
# '''
2023-05-26 10:53:34 +02:00
# doc_files = []
# for root, dirs, files in os.walk(path):
# for file in files:
# if file.endswith(".md") and not ".git" in root:
# doc_files.append(os.path.join(root, file))
# return doc_files
def list_files(path):
"""
Creates a simple, one-dimensional list of the doc repository.
Filters markdown files only.
"""
return [
file for file in glob.glob(
os.path.join(path, '**/*.md'), recursive=True
)
if '.git' not in file
]
2023-05-24 22:22:53 +02:00
2022-09-06 23:45:26 +02:00
def build_index(path, file_ending):
2023-05-24 22:22:53 +02:00
"""
Builds the searchable JSON object containing
all markdown files with metadata.
"""
searchable = {'index': []}
file_list = list_files(path)
2022-09-06 23:45:26 +02:00
for item in file_list:
if item.endswith(file_ending):
2023-05-24 22:22:53 +02:00
with open(item, 'r') as file:
data = file.readlines()
title = data[0].strip('# \n')
uri = '/' + item[len(path):-len(file_ending)] + '.html'
content = ''.join(data)
searchable['index'].append({
'uri': uri,
'title': title,
'tags': [],
'content': content,
'description': ''
})
elif isinstance(item, dict):
build_index(item, file_ending)
2022-09-06 23:45:26 +02:00
return searchable