aboutsummaryrefslogtreecommitdiff
blob: d9aded473a0cf3a4e4df9712df667cf2d1b504da (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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
#!/usr/bin/python

"""

NAME     - metagen
SYNOPSIS - Adds metadata.xml to current directory
AUTHOR   - Rob Cakebread <cakebread@gmail.com>
AUTHOR   - Jesus Rivero <neurogeek@gentoo.org>
USE      - metagen --help
EXAMPLES - man metagen

"""

import re
import os
import sys
from optparse import OptionParser
from commands import getstatusoutput

from portage import config
from portage.output import red, blue

try:
    # portage <2.2.22
    # https://bugs.gentoo.org/show_bug.cgi?id=561908
    from repoman import herdbase
except ImportError:
    # portage >=2.2.22
    from repoman.checks.herds import herdbase

from metagen.version import __version__
from metagen import metagenerator

PORTDIR = config(local_config=False)["PORTDIR"]
HB = herdbase.make_herd_base(os.path.sep.join([PORTDIR, 'metadata', 'herds.xml']))

def parse_echangelog_variable(name, email):
    """Extract developer name and email from ECHANGELOG_USER variable"""
    try:
        e = os.environ["ECHANGELOG_USER"]
    except KeyError:
        print red("!!! Environmental variable ECHANGELOG_USER not set.")
        print red("!!! Set ECHANGELOG_USER or use -e and -n")
        sys.exit(1) 
    try:
        my_email = e[e.find("<") +1:e.find(">")]
    except:
        print red("!!! ECHANGELOG_USER not set properly")
        sys.exit(1) 
    try:
        my_name = e[0:e.find("<")-1]
    except:
        print red("!!! ECHANGELOG_USER not set properly")
        sys.exit(1) 
    if email:
        email = "%s,%s" % (my_email, email)
    else:
        email = my_email
    if name:
        name = "%s,%s" % (my_name, name)
    else:
        name = my_name
    return name, email

def generate_xml(options):
    """Returns metadata.xml text"""

    herds=[]
    metadata = metagenerator.MyMetadata()

    if options.herd:
        herds = options.herd.split(",")

    for herd in herds:
        if not HB.known_herd(herd):
            print red("!!! Error. Herd %s does not exist." % herd)
            sys.exit(1) 
            
    metadata.set_herd(herds)

    if options.echangelog:
        (options.name, options.email) = \
            parse_echangelog_variable(options.name, options.email)

    if options.email:
        names, descs = [], []
        if options.name:
            names = options.name.split(",")
        if options.desc:
            descs = options.desc.split(",")
        metadata.set_maintainer(options.email.split(","),
                                names,
                                descs
                                )

    if options.long:
        metadata.set_longdescription(options.long)

    return "%s" % metadata

def validate_xml(my_xml):
    """Test for valid XML"""
    #TODO validate against DTD
    #This just makes sure its valid XML of some sort.
    #Probably not necessary since repoman validates against DTD?
    re_escape_quotes = re.compile('"')
    s = re_escape_quotes.sub('\\"', my_xml)
    cmd = "echo \"%s\" | xmllint --valid - 2>&1 > /dev/null" % s
    return getstatusoutput(cmd)[0]


if __name__ == '__main__':
    optParser = OptionParser(version=__version__)
    optParser.add_option("-H", action="store", dest="herd", type="string",
                         help="Name of herd. If not specified, It will be empty. " +
                         "This requires either the -e or -m option.")

    optParser.add_option("-e", action="store", dest="email", type="string",
                         help="Maintainer's email address")

    optParser.add_option("-n", action="store", dest="name", type="string",
                         help="Maintainer's name")

    optParser.add_option("-m", action="store_true", dest="echangelog", 
                         default=False,
                         help="Use name and email address from ECHANGELOG_USER "+
                         "environmental variable. "+
                         "This is a shortcut for -e <email> -n <name>")

    optParser.add_option("-d", action="store", dest="desc", type="string",
                         help="Description of maintainership")

    optParser.add_option("-l", action="store", dest="long", type="string",
                         help="Long description of package.")

    optParser.add_option("-o", action="store", dest="output", type="string",
                         help="Specify location of output file.")

    optParser.add_option("-f", action="store_true", dest="force", default=False,
                         help="Force overwrite of existing metadata.")

    optParser.add_option("-v", action="store_true", dest="verbose", default=True,
                         help="Verbose. Output of file to stdout. (default)")

    optParser.add_option("-q", action="store_false", dest="verbose",
                         help="Squelch output of file to stdout.")

    optParser.add_option("-Q", action="store_true", dest="no_write",
                         default=False,
                         help="Do not write file to disk.")

    (options, remainingArgs) = optParser.parse_args()

    if len(sys.argv) == 1:
        optParser.print_help()
        sys.exit(1)

    if options.desc or options.name:
        if not options.email and not options.echangelog:
            print red("!!! No maintainer's email address specified.")
            print red("!!! Options -d and -n are only valid with -e or -m")
            sys.exit(1)
 
    if not options.herd and not options.email and not options.echangelog:
        print red("!!! You must specify at least a herd (-H) " +
                  "or maintainer's email address (-e)\n")
        sys.exit(1)

    txt = generate_xml(options)

    error_status = validate_xml(txt)
    if error_status < 0:
        print red("!!! Error - Invalid XML")
        print red("!!! Please report this bug with the options you used and the output:")
        print error_status
        print txt
        sys.exit(1)

    if options.verbose:
        print "\n%s" % txt

    out_file = "./metadata.xml"
    if options.output:
        out_file = options.output
    if not options.no_write and os.path.exists(out_file):
        if not options.force:
            print red("!!! File %s exists." % out_file)
            print red("!!! Use -f to force overwrite.")
            sys.exit(1)
    if not options.no_write:
        open("%s" % out_file, "w").writelines(txt)
        print blue("%s written") % out_file