summaryrefslogtreecommitdiffstats
path: root/fedora-easy-karma.py
blob: b44990d26846719405a6d7f343a7ff88cb717d36 (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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
#!/usr/bin/python
# vim: fileencoding=utf8 foldmethod=marker
# {{{ License header: GPLv2+
#    This file is part of fedora-easy-karma.
#
#    Fedora-easy-karma is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 2 of the License, or
#    (at your option) any later version.
#
#    Fedora-easy-karma is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with fedora-easy-karma.  If not, see <http://www.gnu.org/licenses/>.
# }}}

# default python modules
import datetime
import getpass
import itertools
import os
import readline

from optparse import OptionParser
from textwrap import wrap

# extra python modules
import fedora
import fedora_cert
import yum

from fedora.client.bodhi import BodhiClient


def wrap_paragraphs(paragraphs, width=67, subsequent_indent=(" "*11 + ": "), second_column_indent=0):
    return ("\n%s" % subsequent_indent).join(map(lambda p: "\n".join(wrap(p, width=width, subsequent_indent=(subsequent_indent + " " * second_column_indent))), paragraphs))


def wrap_paragraphs_prefix(paragraphs, first_prefix, width=80, extra_newline=False):
    if isinstance(paragraphs, basestring):
        paragraphs = paragraphs.split("\n")

    if first_prefix:
        subsequent_indent = " " * (len(first_prefix) - 2) + ": "
    else:
        subsequent_indent = ""

    output = []
    first = True
    wrapped = []

    # remove trailing empty paragraphs
    while paragraphs[-1] == "":
        paragraphs.pop()

    for p in paragraphs:
        if extra_newline and len(wrapped) > 1:
            output.append("")
        if first:
            p = first_prefix + p
            first = False

        wrapped = wrap(p, width=width, subsequent_indent=subsequent_indent)
        output.append("\n".join(wrapped))

    return ("\n%s" % subsequent_indent).join(output)



def bodhi_update_str(update, bodhi_base_url="https://admin.fedoraproject.org/updates/", bugzilla_bug_url="https://bugzilla.redhat.com/", wrap_bugs=True, width=80):

        # copy update to avoid side effects
        values = dict(update)
        format_string = (
            "%(header_line)s\n"
            "%(title)s\n"
            "%(header_line)s\n"
            "%(updateid)s"
            "    Release: %(release)s\n"
            "     Status: %(status)s\n"
            "       Type: %(type)s\n"
            "      Karma: %(karma)d\n"
            "%(request)s"
            "%(bugs)s"
            "%(notes)s"
            "  Submitter: %(submitter)s\n"
            "  Submitted: %(date_submitted)s\n"
            "%(comments)s"
            "\n%(update_url)s"
                        )

        values["header_line"] = "=" * width
        values["title"] = "\n".join(wrap(update["title"].replace(",", ", "), width=width, initial_indent=" "*5, subsequent_indent=" "*5))

        if update["updateid"]:
            values["updateid"] = "  Update ID: %s\n" % update["updateid"]
        else:
            values["updateid"] = ""

        values["release"] = update["release"]["long_name"]

        if update["request"]:
            values["request"] = "    Request: %s\n" % update["request"]
        else:
            values["request"] = ""

        if len(update["bugs"]):
            bugs = []
            for bug in update["bugs"]:
                bz_id = bug["bz_id"]
                if bugzilla_bug_url:
                    bz_id = "%s%d" % ( bugzilla_bug_url, bz_id)
                bz_title = bug["title"]
                bugs.append("%s - %s" % (bz_id, bz_title))

            if wrap_bugs:
                values["bugs"] = "%s\n" % wrap_paragraphs_prefix(bugs, first_prefix="       Bugs: ", width=width, extra_newline=True)
            else:
                values["bugs"] = "       Bugs: %s\n" % ("\n" + " " * 11 + ": ").join(bugs)
        else:
            values["bugs"] = ""

        if update["notes"]:
            values["notes"] = "%s\n" % wrap_paragraphs_prefix(update["notes"].split("\r\n"), first_prefix="      Notes: ", width=width)
        else:
            values["notes"] = ""


        if len(update["comments"]):
            val = "   Comments: "
            comments = []
            for comment in update["comments"]:

                # copy comment to avoid side effects
                comment = dict(comment)

                author = comment["author"]
                indent = " " * 13
                comment["indent"] = indent

                if comment["anonymous"]:
                    comment["author"] += " (unauthenticated)"

                comments.append("%(indent)s%(author)s - %(timestamp)s (karma %(karma)s)" % comment)

                if comment["text"]:
                    wrapped = wrap(comment["text"], initial_indent=indent, subsequent_indent=indent, width=width)
                    comments.append("\n".join(wrapped))
            val += "\n".join(comments).lstrip() + "\n"
            values["comments"] = val
        else:
            values["comments"] = ""


        if update["updateid"]:
            url_path = "%s/%s" % (update["release"]["name"], update["updateid"])
        else:
            url_path = update["title"]

        values["update_url"] = "  %s%s\n" % (bodhi_base_url, url_path)

        return format_string % values



def already_commented(update, user):
    for comment in update["comments"]:
        if not comment["anonymous"] and comment["author"] == user:
            return True
    return False


def send_comment(bc, update, comment, karma, options):
    try:
        bc.comment(update["title"], comment, karma=karma)
        return True
    except fedora.client.AuthError:
        bc.password = getpass.getpass('FAS Password for %s: ' % options.fas_username)
    return False

if __name__ == "__main__":
    usage = (
            "usage: %prog [options]\n\n"
            "You will be asked for every package installed from updates-testing to provide feedback using karma points. "
            "After you have selected the karma points, you will be asked for a comment. An empty comments skips the package\n\n"
            "Possible karma points are:\n"
            "-1 : Update breaks something or does not fix a bug it is supposed to\n"
            " 0 : The update has not been tested much or at all\n"
            " 1 : The update seems not to break anything new\n"
            "All other inputs will skip the update\n\n"
            "The source can be found at\n"
            "http://fedorapeople.org/gitweb?p=till/public_git/fedora-easy-karma.git;a=summary\n"
            "Please send bug reports and feature requests to\n"
            "'Till Maas <opensource@till.name>'\n"
            "For patches please use 'git send-mail'."
            )

    usage = wrap_paragraphs_prefix(usage, first_prefix="", width=80, extra_newline=False)

    parser = OptionParser(usage=usage)
    parser.add_option("", "--fas-username", dest="fas_username", help="FAS username", default=None)
    parser.add_option("", "--include-commented", dest="include_commented", help="Also ask for more comments on updates that already got a comment from you", action="store_true", default=False)
    parser.add_option("", "--installed-max-days", dest="installed_max_days", help="Only check packages installed within the last XX days, default: %default", metavar="DAYS", default=28, type="int")
    parser.add_option("", "--installed-min-days", dest="installed_min_days", help="Only check packages installed for at least XX days, default: %default", metavar="DAYS", default=0, type="int")
    parser.add_option("", "--product", dest="product", help="product to query Bodhi for, 'F' for Fedora, 'EL-' for EPEL, default: %default", default="F")
    parser.add_option("", "--releasever", dest="releasever", help="releasever to query Bodhi for, default: releasever from yum", default=None)
    parser.add_option("", "--wrap-bugs", dest="wrap_bugs", help="Apply line-wrapping to bugs", action="store_true", default=False)
    parser.add_option("", "--wrap-rpms", dest="wrap_rpms", help="Apply line-wrapping to list of installed rpms", action="store_true", default=False)
    parser.add_option("", "--wrap-width", dest="wrap_width", help="Width to use for line wrapping of updates, default: %default", default=80, type="int")

    (options, args) = parser.parse_args()

    if not options.fas_username:
        try:
            fas_username = fedora_cert.read_user_cert()
        except fedora_cert.fedora_cert_error:
            fas_username = os.getlogin()
        options.fas_username = fas_username

    bc = BodhiClient(username=options.fas_username)
    my = yum.YumBase()
    my.preconf.debuglevel=0

    if not options.releasever:
        options.releasever = my.conf.yumvar["releasever"]
    release = "%s%s" % (options.product, options.releasever)


    installed_testing_builds = {}
    now = datetime.datetime.now()
    installed_max_days = datetime.timedelta(options.installed_max_days)
    installed_min_days = datetime.timedelta(options.installed_min_days)

    # make pkg objects subscriptable, i.e. pkg["name"] work
    yum.rpmsack.RPMInstalledPackage.__getitem__ = lambda self, key: getattr(self, key)
    for pkg in my.rpmdb.returnPackages():
        installed = datetime.datetime.fromtimestamp(pkg.installtime)
        installed_timedelta = now - installed
        if  installed_timedelta < installed_max_days and installed_timedelta > installed_min_days:
            if pkg.yumdb_info.get('from_repo') == 'updates-testing':
                build = pkg.sourcerpm[:-8]
                rpm = "%(name)s-%(version)s-%(release)s.%(arch)s" % pkg
                if build in installed_testing_builds:
                    installed_testing_builds[build].append(rpm)
                else:
                    installed_testing_builds[build] = [rpm]

    # probably raises some exceptions
    testing_updates = bc.query(release=release, status="testing", limit=1000)["updates"]

    # create a mapping build -> update
    testing_builds = {}
    for update in testing_updates:
        if options.include_commented or not already_commented(update, options.fas_username):
            for build in update["builds"]:
                testing_builds[build["nvr"]] = update

    # multiple build can be grouped together in one update, only ask once per update
    processed_updates = []
    for build in testing_builds:
        update = testing_builds[build]
        if update not in processed_updates and build in installed_testing_builds:
                print bodhi_update_str(update, bodhi_base_url=bc.base_url, width=options.wrap_width, wrap_bugs=options.wrap_bugs)

                affected_builds = [b["nvr"] for b in update["builds"]]
                installed_rpms = list(itertools.chain(*[installed_testing_builds[b] for b in affected_builds]))
                installed_rpms.sort()

                if options.wrap_rpms:
                    print wrap_paragraphs_prefix(installed_rpms, first_prefix=" inst. RPMS: ", width=options.wrap_width)
                else:
                    print " inst. RPMS: %s\n" % ("\n" + " " * 11 + ": ").join(installed_rpms)

                karma = raw_input("Comment? -1/0/1 ->karma, other -> skip> ")
                if karma in ["-1", "0", "1"]:
                    comment = raw_input("Comment> ")
                    if comment:
                        while not send_comment(bc, update, comment, karma, options):
                            pass
                    else:
                        print "skipped because of empty comment"

        processed_updates.append(update)