aboutsummaryrefslogtreecommitdiff
path: root/scripts/maint/checkManpageAlpha.py
blob: 70421c2fd112b0a8dbe91da6240ce6a795f081c0 (plain)
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
#!/usr/bin/python

import difflib
import re
import sys

# Assume we only use the "== Section Name" section title syntax
sectionheader_re = re.compile(r'^==+\s(.*)\s*$')

# Assume we only use the "[[ItemName]]" anchor syntax
anchor_re = re.compile(r'^\[\[([^]]+)\]\]')

class Reader(object):
    def __init__(self):
        self.d = {}
        # Initial state is to gather section headers
        self.getline = self._getsec
        self.section = None

    def _getsec(self, line):
        """Read a section header

        Prepare to gather anchors from subsequent lines.  Don't change
        state if the line isn't a section header.
        """
        m = sectionheader_re.match(line)
        if not m:
            return
        self.anchors = anchors = []
        self.d[m.group(1)] = anchors
        self.getline = self._getanchor

    def _getanchor(self, line):
        """Read an anchor for an item definition

        Append the anchor names to the list of items in the current
        section.
        """
        m = anchor_re.match(line)
        if not m:
            return self._getsec(line)
        self.anchors.append(m.group(1))

    def diffsort(self, key):
        """Unified diff of unsorted and sorted item lists
        """
        # Append newlines because difflib works better with them
        a = [s + '\n' for s in self.d[key]]
        b = sorted(a, key=str.lower)
        return difflib.unified_diff(a, b, fromfile=key+' unsorted',
                                    tofile=key+' sorted')

def main():
    """Diff unsorted and sorted lists of option names in a manpage

    Use the file named by the first argument, or standard input if
    there is none.
    """
    try:
        fname = sys.argv[1]
        f = open(fname, 'r')
    except IndexError:
        f = sys.stdin

    reader = Reader()
    for line in f:
        reader.getline(line)
    for key in sorted(reader.d.keys(), key=str.lower):
        sys.stdout.writelines(reader.diffsort(key))

if __name__ == '__main__':
    main()