Skip to content

Instantly share code, notes, and snippets.

@wedojava
Created July 26, 2020 10:41
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wedojava/aab3a975858fbbbab4e0b3300ad7e1c8 to your computer and use it in GitHub Desktop.
Save wedojava/aab3a975858fbbbab4e0b3300ad7e1c8 to your computer and use it in GitHub Desktop.
This is written for convert from hexo to hugo, also migrate from hexo to hugo.
import os
import os.path
def walk_over(w_path):
"""Walk in w_path folder and get all filenames back
:w_path: walk folder path
:returns: the filename list
"""
filelist = []
rt = []
for _, _, files in os.walk(w_path):
filelist.append(files)
for name in files:
if os.path.splitext(name)[1] == ".md":
rt.append(name)
return rt
def convert(f_path):
"""convert file to make it fit hugo
:f_path: filepath
:returns: nothing
"""
# read file
with open(f_path, "r+") as f:
lines = f.readlines()
# convert content
i = j = 0
for line in lines:
if line.startswith("title:"):
lines[i] = f'title: "{line[6:].strip()}"\n'
if line.startswith("date:"):
lines[i] = f"date: {line[5:16].strip()}T{line[16:].strip()}+08:00\n"
if line.startswith("tags:"):
t = line[5:].strip()[1:-1].split(',')
s = '", "'.join(t)
lines[i] = f'tags: ["{s}"]\n'
if line.startswith("categories:"):
t = line[11:].strip().split(',')
s = '", "'.join(t)
lines[i] = f'categories: ["{s}"]\n'
if line.startswith("<!-- more -->"):
lines[i] = "<!--more-->"
i+=1
# write file
with open(f_path, "w") as f:
f.writelines(lines)
def main():
# it will modify md files directly, so, make a backup before the treating.
mdfiles = "./YourHexoPostsFolder"
ls = walk_over(mdfiles)
for f in ls:
convert(os.path.join(mdfiles, f))
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment