Last active
October 4, 2020 15:30
-
-
Save rishabhc32/38cf5b0d2777708c8f200d8c431279a1 to your computer and use it in GitHub Desktop.
Convert cover hugo front matter "cover_image" key to "image" key
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
""" | |
Include a safety pig in your code as a warning to other developers that hard-to-read code and crazy hacks follow. | |
You have been warned! | |
_._ _..._ .-', _.._(`)) | |
'-. ` ' /-._.-' ',/ | |
) \ '. | |
/ _ _ | \ | |
| a a / | | |
\ .-. ; | |
'-('' ).-' ,' ; | |
'-; | .' | |
\ \ / | |
| 7 .__ _.-\ \ | |
| | | ``/ /` / | |
/,_| | /,_/ / | |
/,_/ '`-' | |
""" | |
import os | |
def main(file_path): | |
index = list() | |
f = open(file_path, 'r+') | |
position = 0 | |
for line in f: | |
position += len(line) | |
if '---' in line: | |
break | |
for line in f: | |
position += len(line) | |
if '---' in line: | |
break | |
index.append({'pos': position, 'line': line}) | |
cover_image = normal_image = None | |
for idx in index: | |
line = idx['line'] | |
line = line.replace(' ', '') | |
lines = [x.strip() for x in line.split(':')] | |
if 'cover_image' in lines: | |
cover_image = idx | |
if 'image' in lines: | |
normal_image = idx | |
if cover_image is not None and normal_image is None: | |
line = cover_image['line'] | |
pos = cover_image['pos'] | |
text = line.split(':')[1].strip() | |
text_to_insert = "image: {}\n".format(text) | |
with open(file_path, 'r') as temp_file: | |
temp_file.seek(pos) | |
rest_of_lines = temp_file.read() | |
f.seek(pos) | |
f.write(text_to_insert) | |
f.write(rest_of_lines) | |
f.close() | |
def get_file_list(folder_name): | |
all_files = [f'{folder_name}/{x}' for x in os.listdir(folder_name) if x.endswith('.md')] | |
return all_files | |
if __name__ == "__main__": | |
files = get_file_list('./blog') | |
for f in files: | |
main(f) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In my hugo website, zapcircle.net, I was using
material
theme which was usingcover_image
key in post's front matter for specifying cover images.I wanted to try other theme named
bigspring
, but it usedimage
key in front matter to specify cover image. So this is the script I wrote to findcover_image
key from front matter and add anotherimage
key with same value ascover_image
key.