1
#!/usr/bin/env python
2
"""Auto-generate PSEP 0 (PSEP index).
3
4
Generating the PSEP index is a multi-step process.  To begin, you must first
5
parse the PSEP files themselves, which in and of itself takes a couple of steps:
6
7
    1. Parse metadata.
8
    2. Validate metadata.
9
10
With the PSEP information collected, to create the index itself you must:
11
12
    1. Output static text.
13
    2. Format an entry for the PSEP.
14
    3. Output the PSEP (both by category and numerical index).
15
16
"""
17
from __future__ import absolute_import, with_statement
18
19
import sys
20
import os
21
import codecs
22
23
from operator import attrgetter
24
25
from psep0.output import write_psep0
26
from psep0.psep import PSEP, PSEPError
27
28
29
def main(argv):
30
    if not argv[1:]:
31
        path = '.'
32
    else:
33
        path = argv[1]
34
35
    pseps = []
36
    if os.path.isdir(path):
37
        for file_path in os.listdir(path):
38
            abs_file_path = os.path.join(path, file_path)
39
            if not os.path.isfile(abs_file_path):
40
                continue
41
            if file_path.startswith("psep-") and file_path.endswith(".txt"):
42
                with codecs.open(abs_file_path, 'r', encoding='UTF-8') as psep_file:
43
                    try:
44
                        pseps.append(PSEP(psep_file))
45
                    except PSEPError, e:
46
                        errmsg = "Error processing PSEP %s, excluding:" % \
47
                            (e.number,)
48
                        print >>sys.stderr, errmsg, e
49
                        sys.exit(1)
50
        pseps.sort(key=attrgetter('number'))
51
    elif os.path.isfile(path):
52
        with open(path, 'r') as psep_file:
53
            pseps.append(PSEP(psep_file))
54
    else:
55
        raise ValueError("argument must be a directory or file path")
56
57
    with codecs.open('psep-0000.txt', 'w', encoding='UTF-8') as psep0_file:
58
        write_psep0(pseps, psep0_file)
59
60
if __name__ == "__main__":
61
    main(sys.argv)