1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
|
import enum import sys from pathlib import Path import os import re
posts = "source/_posts"
valid_pic_suffix = ["png", "jpg", "jpeg", "gif", "svg"]
def check_is_pic(pic_file_name): suffix = Path(pic_file_name).suffix.lower() if suffix is None or suffix == "": return False return suffix[1:] in valid_pic_suffix
class OperateType(enum.Enum): ADD_ASSET = 1 REM_ASSET = 2 REPLACE_BY_ASSERT = 3
def fix_one_post(file, operate_type): new_lines = [] with open(file, encoding="utf-8") as f: old_lines = f.readlines() for i in range(len(old_lines)): l = old_lines[i] if l.startswith("["): new_lines.append(l) continue if l.strip().startswith("{%"): continue if operate_type == OperateType.REM_ASSET: new_lines.append(l) else: re_obj = re.search(r"(.*)!\[(.*)](.*)\((.*)\)(.*)", l) if re_obj is not None: groups = re_obj.groups() assert len(groups) == 5 pic_file_path = groups[3] assert check_is_pic(pic_file_path) pic_file_name = str(Path(pic_file_path).name) if operate_type == OperateType.ADD_ASSET: new_lines.append(l) asset_line = f"{{% asset_img {pic_file_name}%}}\n" new_lines.append(asset_line) else: asset_line = f"{groups[0]}{{% asset_img {pic_file_name}%}}{groups[4]}\n" new_lines.append(asset_line) else: new_lines.append(l) with open(file, "w", encoding="utf-8") as f: f.writelines(new_lines)
def main(): argv = sys.argv operate_type = OperateType.ADD_ASSET if argv[1] == "add": operate_type = OperateType.ADD_ASSET elif argv[1] == "rem": operate_type = OperateType.REM_ASSET elif argv[1] == "replace": operate_type = OperateType.REPLACE_BY_ASSERT else: raise RuntimeError(f"wrong arguments {argv}") for path, dir_list, file_list in os.walk(posts): for file_name in file_list: if file_name.lower().endswith(".md"): real_name = os.path.join(path, file_name) fix_one_post(real_name, operate_type) pass
if __name__ == '__main__': main()
|