checkManpageAlpha.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #!/usr/bin/python
  2. import difflib
  3. import re
  4. import sys
  5. # Assume we only use the "== Section Name" section title syntax
  6. sectionheader_re = re.compile(r'^==+\s(.*)\s*$')
  7. # Assume we only use the "[[ItemName]]" anchor syntax
  8. anchor_re = re.compile(r'^\[\[([^]]+)\]\]')
  9. class Reader(object):
  10. def __init__(self):
  11. self.d = {}
  12. # Initial state is to gather section headers
  13. self.getline = self._getsec
  14. self.section = None
  15. def _getsec(self, line):
  16. """Read a section header
  17. Prepare to gather anchors from subsequent lines. Don't change
  18. state if the line isn't a section header.
  19. """
  20. m = sectionheader_re.match(line)
  21. if not m:
  22. return
  23. self.anchors = anchors = []
  24. self.d[m.group(1)] = anchors
  25. self.getline = self._getanchor
  26. def _getanchor(self, line):
  27. """Read an anchor for an item definition
  28. Append the anchor names to the list of items in the current
  29. section.
  30. """
  31. m = anchor_re.match(line)
  32. if not m:
  33. return self._getsec(line)
  34. self.anchors.append(m.group(1))
  35. def diffsort(self, key):
  36. """Unified diff of unsorted and sorted item lists
  37. """
  38. # Append newlines because difflib works better with them
  39. a = [s + '\n' for s in self.d[key]]
  40. b = sorted(a, key=str.lower)
  41. return difflib.unified_diff(a, b, fromfile=key+' unsorted',
  42. tofile=key+' sorted')
  43. def main():
  44. """Diff unsorted and sorted lists of option names in a manpage
  45. Use the file named by the first argument, or standard input if
  46. there is none.
  47. """
  48. try:
  49. fname = sys.argv[1]
  50. f = open(fname, 'r')
  51. except IndexError:
  52. f = sys.stdin
  53. reader = Reader()
  54. for line in f:
  55. reader.getline(line)
  56. for key in sorted(reader.d.keys(), key=str.lower):
  57. sys.stdout.writelines(reader.diffsort(key))
  58. if __name__ == '__main__':
  59. main()