summaryrefslogtreecommitdiffstats
path: root/src/pyfedpkg/man_page.py
blob: dbd4b03f8528525c5ff93a7b9413b1a3a04d24ff (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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
# Print a man page from the help texts.


import argparse
import sys
import datetime


__all__ = ['get_parser']


# We could substitute the "" in .TH with the fedpkg version if we knew it
man_header = """\
.\" man page for fedpkg
.TH fedpkg 1 "%(today)s" "" "fedora\-packager"
.SH "NAME"
fedpkg \- Fedora Packaging utility
.SH "SYNOPSIS"
.B "fedpkg"
[
.I global_options
]
.I "command"
[
.I command_options
]
[
.I command_arguments
]
.br
.B "fedpkg"
.B "help"
.br
.B "fedpkg"
.I "command"
.B "\-\-help"
.SH "DESCRIPTION"
.B "fedpkg"
is a script to interact with the Fedora Packaging system.
"""

man_footer = """\
.SH "SEE ALSO"
.UR "https://fedorahosted.org/fedora\-packager/"
.BR "https://fedorahosted.org/fedora\-packager/"
"""

class ManFormatter(object):

    def __init__(self, man):
        self.man = man

    def write(self, data):
        #print "MF:", repr(data)
        for line in data.split('\n'):
            #print 'MFL:', line
            self.man.write('  %s\n' % line)


def usage_clean(s):
    if s.startswith('usage: '):
        return s.replace('usage: ', '', 1)
    else:
        return s


def man_constants():
    """Global constants for man file templates"""
    today = datetime.date.today()
    today_manstr = today.strftime('%Y\-%m\-%d')
    return {'today': today_manstr}


def fedpkg_command(args):
    man_file = args.outfile

    # Not nice, but redirects any print statement output to stderr
    sys.stdout = sys.stderr

    mf = ManFormatter(man_file)

    subparsers = args.subparsers

    #print dir(subparsers)
    # subparsers.print_help()

    choices = subparsers.choices
    k = choices.keys()
    k.sort()

    man_file.write(man_header % man_constants())

    man_file.write('.SH "COMMAND OVERVIEW"\n')

    help_texts = {}
    for pa in subparsers._choices_actions:
        help_texts[pa.dest] = getattr(pa, 'help', None)

    for command in k:
        parser = choices[command]
        if not parser.add_help:
            continue
        usage = parser.format_usage()
        usage = usage_clean(usage)
        usage = ''.join(usage.split('\n'))
        usage = ' '.join(usage.split())
        if help_texts[command]:
            man_file.write('.TP\n.B "%s"\n%s\n' % (usage, help_texts[command]))
        else:
            man_file.write('.TP\n.B "%s"\n' % (usage))

    man_file.write('.SH "COMMAND REFERENCE"\n')
    for command in k:
        parser = choices[command]
        if not parser.add_help:
            continue

        #print
        #print "####", command, "####"
        man_file.write('.SS "%s"\n' % parser.prog)

        help = help_texts[command]
        if help and not parser.description:
            if not help.endswith('.'): help = "%s." % help
            parser.description = help
        #print parser
        formatter = parser.formatter_class(parser.prog)
        h = parser.format_help()
        mf.write(h)

    man_file.write(man_footer)


def add_parser(subparsers):

    descr = """\
Generate a basic fedpkg(1) man page from the command line argument
help text and descriptions.
"""

    sp = subparsers.add_parser('man-page',
                               help = 'Generate a fedpkg(1) man page',
                               add_help = False,
                               description = descr)
    sp.add_argument('-o', '--output',
                    dest='outfile', nargs='?',
                    type=argparse.FileType('w'), default=sys.stdout,
                    help="File to write the man page to. Default is stdout.")
    sp.set_defaults(command = fedpkg_command)
    return sp