git.lain.church game of nomic
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

94 lines
2.6KB

  1. #!/usr/bin/env python
  2. """Find and concatenate all the rule files into one readable output.
  3. """
  4. # n.b.: This shows any file, not just ones committed in git, which would
  5. # require parsing output from git ls-files or something.
  6. # This doesn't show files in subdirectories.
  7. # This won't show anything that doesn't have a .md extension.
  8. # This is supposed to generate valid markdown, but that depends on the
  9. # rule files.
  10. import os
  11. import re
  12. _FILENAME_RE = re.compile(r'(\d+)_(.*)\.md')
  13. def file_paths_under(root):
  14. """Yield paths of files under the given root.
  15. """
  16. for filename in sorted(os.listdir(root)):
  17. full_path = os.path.join(root, filename)
  18. # n.b.: lots of checks against filesystem.
  19. if os.path.isfile(full_path):
  20. yield full_path
  21. def files(file_paths):
  22. """Yield file objects for the given file paths.
  23. """
  24. # n.b.: no error handling if files don't exist or can't be opened.
  25. for file_path in file_paths:
  26. with open(file_path, "r") as file_obj:
  27. yield file_obj
  28. def parse_path(filename):
  29. """Extract rule number and title from given path to rule file.
  30. """
  31. basename = os.path.basename(filename)
  32. match = _FILENAME_RE.match(basename)
  33. if not match:
  34. return None
  35. number = match.group(1)
  36. words = [word.capitalize() for word in match.group(2).split("-")]
  37. title = " ".join(words)
  38. return number, title
  39. def render_dir(root):
  40. """Yield lines presenting rule files in the given directory.
  41. """
  42. for file_obj in files(file_paths_under(root)):
  43. parsed = parse_path(file_obj.name)
  44. # n.b.: parsed may be None and fail to unpack here.
  45. number, title = parsed
  46. content = file_obj.read().rstrip()
  47. title_line = "{0}. {1}".format(number, title)
  48. yield ""
  49. yield title_line
  50. yield "-" * len(title_line)
  51. yield ""
  52. yield content
  53. def render_section(root, title):
  54. """Add a title to the output of render_dir.
  55. """
  56. yield title
  57. yield "=" * len(title)
  58. for line in render_dir(root):
  59. yield line
  60. def main():
  61. """What happens when the script is run
  62. """
  63. this_file = os.path.abspath(__file__)
  64. here = os.path.dirname(this_file)
  65. parent = os.path.dirname(here)
  66. immutable_rule_dir = os.path.join(parent, 'immutable_rules')
  67. mutable_rule_dir = os.path.join(parent, 'mutable_rules')
  68. for line in render_section(immutable_rule_dir, "Immutable Rules"):
  69. print(line)
  70. print("")
  71. for line in render_section(mutable_rule_dir, "Mutable Rules"):
  72. print(line)
  73. # This is a script file, so __name__ stuff is not useful.
  74. main()