86 lines
2.2 KiB
Python
Executable file
86 lines
2.2 KiB
Python
Executable file
#!/usr/bin/env python3
|
|
# Eryn Wells <eryn@erynwells.me>
|
|
|
|
'''
|
|
Convert a Hugo content page from a single page to a bundle and vice versa.
|
|
'''
|
|
|
|
import argparse
|
|
import os.path
|
|
|
|
def parse_args(argv, *a, **kw):
|
|
parser = argparse.ArgumentParser(*a, **kw)
|
|
parser.add_argument('page_path', metavar='PATH', help='Path to page or bundle to convert')
|
|
args = parser.parse_args(argv)
|
|
return args
|
|
|
|
def path_is_page(path):
|
|
if not os.path.isfile(path):
|
|
return False
|
|
|
|
_, extension = os.path.splitext(path)
|
|
if extension not in ['.md']:
|
|
return False
|
|
|
|
return True
|
|
|
|
def path_is_page_bundle(path):
|
|
if not os.path.isdir(path):
|
|
return False
|
|
|
|
contents = os.listdir(path)
|
|
if 'index.md' not in contents:
|
|
return False
|
|
|
|
return True
|
|
|
|
def can_convert_page_bundle_to_page(path):
|
|
contents = os.listdir(path)
|
|
if len(contents) != 1:
|
|
return False
|
|
|
|
if 'index.md' not in contents:
|
|
return False
|
|
|
|
return True
|
|
|
|
def convert_page_to_bundle(path) -> bool:
|
|
dirname = os.path.dirname(path)
|
|
name, extension = os.path.splitext(path)
|
|
|
|
bundle_path = os.path.join(dirname, name)
|
|
index_path = os.path.join(dirname, 'index' + extension)
|
|
|
|
try:
|
|
print(f'Creating {bundle_path} ... ', end='')
|
|
os.mkdir(bundle_path)
|
|
print('OK')
|
|
except FileExistsError as e:
|
|
print(f'\nCannot create {bundle_path}: directory already exists')
|
|
return False
|
|
|
|
try:
|
|
print(f'Moving {path} -> {index_path} ... ', end='')
|
|
os.rename(path, index_path)
|
|
print('OK')
|
|
except:
|
|
print(f'\nCannot move page file to new index path {index_path}')
|
|
|
|
return True
|
|
|
|
def main(argv):
|
|
args = parse_args(argv[1:], prog=argv[0])
|
|
|
|
page_path = args.page_path
|
|
if path_is_page(page_path):
|
|
print(f'{page_path} is a page')
|
|
convert_page_to_bundle(page_path)
|
|
elif path_is_page_bundle(page_path):
|
|
print(f'{page_path} is a page bundle')
|
|
if not can_convert_page_bundle_to_page(page_path):
|
|
print(f'Cannot convert bundle {page_path} to page')
|
|
|
|
if __name__ == '__main__':
|
|
import sys
|
|
result = main(sys.argv)
|
|
sys.exit(0 if not result else result)
|