markdown-filed-converter.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. #
  2. # This script is a conveter helper for Obsiditan linter
  3. # to converter the orginal date field name
  4. # from "date created" to "date-created"
  5. # from "date modified" to "date-modified"
  6. # because the dataview plugin cannot identify the white space
  7. #
  8. # Created on: 2022-07-10
  9. # Author: Xing@deyisi.com
  10. import os
  11. import argparse
  12. def go_through_docs(work_dir):
  13. count = 0
  14. for root, dirs, files in os.walk(work_dir):
  15. for filename in files:
  16. if filename.endswith(".md"):
  17. if convert(os.path.join(root, filename)):
  18. count += 1
  19. print(f"{count:3d}: \"{filename}\" is converted")
  20. def change(line):
  21. if line.startswith("date created:"):
  22. return line.replace(
  23. "date created",
  24. "date-created"
  25. )
  26. converted = True
  27. if line.startswith("date modified:"):
  28. return line.replace(
  29. "date modified",
  30. "date-modified"
  31. )
  32. if line.startswith("date updated:"):
  33. return line.replace(
  34. "date updated",
  35. "date-updated"
  36. )
  37. def convert(filename):
  38. contents = []
  39. converted = False
  40. with open(filename, encoding="utf-8") as reader:
  41. yaml_entry = False
  42. line_no = 0
  43. for line in reader.readlines():
  44. if line_no == 0:
  45. if line == "---\n":
  46. yaml_entry = True
  47. if yaml_entry:
  48. if line == "---\n" and line_no > 0:
  49. yaml_entry = False
  50. else:
  51. updated = change(line)
  52. if updated is not None:
  53. line = updated
  54. converted = True
  55. contents.append(line)
  56. line_no += 1
  57. with open(filename, "w", encoding="utf-8") as writer:
  58. writer.write("".join(contents))
  59. return converted
  60. if __name__ == "__main__":
  61. parser = argparse.ArgumentParser(
  62. description="Converter existing Markdown documents with"
  63. " new linter format.\n"
  64. "The linter format `date created` will change to "
  65. "`date-created` format.",
  66. )
  67. parser.add_argument(
  68. '--dir',
  69. help='The location of the source ',
  70. default=os.getcwd(),
  71. )
  72. args = parser.parse_args()
  73. work_dir = args.dir
  74. print(f"Converting `{work_dir}` to new format...")
  75. if work_dir is None:
  76. work_dir = os.getcwd()
  77. if os.path.isdir(work_dir):
  78. go_through_docs(work_dir)
  79. else:
  80. print(f"Error: no such directory {work_dir} found.")