~bughelper-dev/bughelper/main

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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
#!/usr/bin/env python

# Written by Henrik Nilsen Omma
# (C) Canonical, Ltd. Licensed under the GPL

import os
import sys
import string
import urllib
import re
import time

try:
    # thekorn:
    # can someone explain this different imports?
    # the imports in the 'except:' block should always work!?
    # but I'm not a packaging hero ;)
    import connector as Connector
    import commandLine
    import config
    import utils
    import output
    import statistic
except:
    from bugHelper.commandLine import commandLine
    from launchpadbugs.lphelper import sort
    import launchpadbugs.connector as Connector
    import bugHelper.utils as utils
    import bugHelper.config as config
    import bugHelper.output as output
    import bugHelper.statistic as statistic
    from launchpadbugs.basebuglistfilter import URLBugListFilter
    from launchpadbugs.lpconstants import BASEURL, BUG, BUGLIST
    from launchpadbugs.exceptions import LaunchpadError
        
        
def no_by_attribute(bug_cls, attribute, op, v):
    def _no_by_attribute(bug):
        try:
            a = getattr(bug, attribute)
        except AttributeError:
            bug = bug_cls(bug)
            a = getattr(bug, attribute)
        x = len(a)
        value = int(v)
        if op == "<":
            return x < value and bug
        if op == ">":
            return x > value and bug
        else:
            return x == value and bug
    return _no_by_attribute
    



def main():
    conf = config.Config("~/.bughelper/config")
    cl = commandLine()
    
    if cl.options.parsemode not in ("text","html"):
        cl.parser.print_usage()
        sys.exit(1)
    if cl.options.format == 'csv' and not cl.options.stats:
        print '''csv format is only useful for stats'''
        sys.exit(1)
    if cl.options.format == 'csv' and not cl.options.closed_bugs:
        print '''csv format isn't really useful if you don't include closed bugs'''
        sys.exit(1)
        
    Bug = Connector.ConnectBug(method=cl.options.parsemode)
    BugList = Connector.ConnectBugList(method=cl.options.parsemode)
    
    cookie = cl.options.cookie
    if cookie:
        cookie = os.path.expanduser(cookie)
    else:
        try:
            cookie = os.path.expanduser(conf.cookie)
        except:
            if cl.options.debug:
                print >> sys.stderr, "No cookie-file found"
    if cookie:
        BugList.authentication=cookie
        Bug.authentication=cookie
        
    try:
        out = output.Output("bugnumbers",cl.options.format,cl.options.file)
    except output.StyleNotFound, e:
        print >> sys.stderr, e
        sys.exit(1)
    out.print_header()
    start = time.time()

    bug_filter = URLBugListFilter()
    
    #HACK!!
    # the text-interface of LP does not provide infos like status, importance etc.
    # in a bug-list. [..]
    # move this to the end of the functions-list?
    if cl.options.parsemode == "text" and not cl.options.date_created:
        if cl.options.format != "numbers" or (cl.options.sort or cl.options.stats):
            from launchpadbugs.basebuglistfilter import get_current_task
            bug_filter.functions.append(lambda x: get_current_task(x, bug_filter.baseurl, Bug))    

    if not cl.options.url:
        if not cl.options.sourcepackage and not cl.options.product and not cl.options.distro:
            cl.parser.print_usage()
            sys.exit(1)
            
        if cl.options.sourcepackage and not cl.options.distro:
            cl.options.distro = BUGLIST.DEFAULT_DISTRO
        
        if cl.options.product:
            if cl.options.sourcepackage:
                print "defining product AND sourcepackage goes not make sense, \
as only distros can have sourcepackages"
                cl.parser.print_usage()
                sys.exit(1)
            cl.options.url = bug_filter("%s/%s/+bugs" %(BASEURL.BUG, cl.options.product))
        elif cl.options.distro and not cl.options.sourcepackage:
            cl.options.url = \
                    bug_filter("%s/%s/+bugs" %(BASEURL.BUG, cl.options.distro))
        elif cl.options.distro and cl.options.sourcepackage:
            cl.options.url = \
                    bug_filter("%s/%s/+source/%s/+bugs" %(BASEURL.BUG,
                                cl.options.distro, cl.options.sourcepackage))
        else:
            cl.parser.print_usage()
            sys.exit(1)
    else:
        try:
            cl.options.url = bug_filter(cl.options.url)
        except ValueError, e:
            print >> sys.stderr, e
            sys.exit(1)
            
    if cl.options.ignore_conflicts:
        bug_filter._conflicts_error = bug_filter.ADD
         
    if cl.options.minbug:
        from launchpadbugs.basebuglistfilter import minbug
        bug_filter.functions.append(lambda x: minbug(x, int(cl.options.minbug)))
        
    if cl.options.filterbug:
        from launchpadbugs.basebuglistfilter import filterbug
        bug_filter.functions.append(lambda x: filterbug(x, map(int, cl.options.filterbug.split(","))))

    if cl.options.date_created:
        from launchpadbugs.basebuglistfilter import datereported
        from launchpadbugs.lptime import LPTime
        Bug = Connector.ConnectBug("text")
        BugList = Connector.ConnectBugList(method="html")
        
        def _parse_date_reported(a):
            if a.startswith("=") or a[0].isdigit():
                return ("=", LPTime(a.lstrip("=")))
            elif a.startswith("<"):
                return ("<", LPTime(a.lstrip("<")))
            elif a.startswith(">"):
                return (">", LPTime(a.lstrip(">")))
            else:
                raise ValueError

        opt_d = _parse_date_reported(cl.options.date_created)
        if opt_d[0] == ">":
            x = "-"
        else:
            x = ""
        bug_filter.add_option("orderby", "%sdatecreated" % x)
        bug_filter.functions.append(datereported(opt_d, Bug))
    
    if cl.options.date_updated:
        from launchpadbugs.basebuglistfilter import dateupdated
        from launchpadbugs.lptime import LPTime
        Bug = Connector.ConnectBug("text")
        BugList = Connector.ConnectBugList(method="html")
        
        def _parse_date_updated(a):
            if a.startswith("=") or a[0].isdigit():
                return ("=", LPTime(a.lstrip("=")))
            elif a.startswith("<"):
                return ("<", LPTime(a.lstrip("<")))
            elif a.startswith(">"):
                return (">", LPTime(a.lstrip(">")))
            else:
                raise ValueError

        opt_d = _parse_date_updated(cl.options.date_updated)
        if opt_d[0] == ">":
            x = "-"
        else:
            x = ""
        bug_filter.add_option("orderby", "%sdate_last_updated" % x)
        bug_filter.functions.append(dateupdated(opt_d, Bug))
        
    if cl.options.branch:
        if not cl.options.parsemode == "html":
            print "branch information is only accessible via --parsemode=html"
            sys.exit(1)
        else:
            from launchpadbugs.basebuglistfilter import hasbranch
            bug_filter.functions.append(lambda x: hasbranch(x, Bug))
        
    if cl.options.lastcomment:
        from launchpadbugs.basebuglistfilter import lastcomment
        from launchpadbugs.lptime import LPTime
        def _parse_lastcomment(a):
            ret_dict = {}    
            x = [i.strip() for i in re.split(r"([ |&]?)([du:]{2})", a) if i]
            ret_dict["operation"] = "|"
            if "&" in x:
                ret_dict["operation"] = "&"
                x.remove("&")
            x = [i for i in map(lambda a: not(a=="|" or a=="&") and a, x) if i]
            if len(x) == 1:
                x.insert(0, "u:")
            assert not(len(x) %2), "wrong number of arguments"
            for i in range(0,len(x),2):
                if x[i] == "u:":
                    ret_dict["user"] = x[i+1]
                elif x[i] == "d:":
                    try:
                        if x[i+1].startswith("="):
                            ret_dict["at"] = LPTime(x[i+1].lstrip("="))
                        elif x[i+1].startswith("<"):
                            ret_dict["before"] = LPTime(x[i+1].lstrip("<"))
                        else:
                            ret_dict["after"] = LPTime(x[i+1].lstrip(">"))
                    except ValueError, e:
                        print  >> sys.stderr, "%s, ignoring given date" %e
                else:
                    cl.parser.print_usage()
                    sys.exit(1)
            return ret_dict
        opt_d = _parse_lastcomment(cl.options.lastcomment)
        #print opt_d#DEBUG
        if "at" in opt_d.keys():
            if "before" in opt_d.keys() or "after" in opt_d.keys():
                raise TypeError, "'at' and 'after' or 'before' is not allowed"
        bug_filter.functions.append(lambda x: lastcomment(x, Bug, **opt_d))
        

    re_opt = re.compile('^(<|>){0,1}([0-9]+$)')
    opt_dict = {"no_duplicates": "duplicates", "no_subscribers": "subscribers",
                "no_comments": "comments", "no_attachments": "attachments"}
    for i,k in opt_dict.iteritems():
        x = getattr(cl.options, i)
        if x:
            m = re_opt.search(x)
            if not m:
                cl.parser.print_usage()
                sys.exit(1)
            bug_filter.functions.append(no_by_attribute(Bug, k, m.group(1), m.group(2)))
          
    if cl.options.status:
        x = set(cl.options.status.split(","))
        if not x <= set(BUG.STATUS.values()).union(set(BUG.STATUS_INCOMPLETE_ADD.values())):
            raise ValueError, "unknown status: %s" %x
        if "Incomplete" in x:
            x.remove("Incomplete")
            x = x.union(set(BUG.STATUS_INCOMPLETE_ADD.keys()))
        for k,i in BUG.STATUS_INCOMPLETE_ADD.iteritems():
            if i in x:
                x.remove(i)
                x.add(k)
        bug_filter.add_option("status", x)
        
    if cl.options.importance:
        x = cl.options.importance.split(",")
        if not set(x) <= set(BUG.IMPORTANCE.values()):
            raise ValueError, "unknown status: %s" %x
        bug_filter.add_option("importance", x)
        
    if cl.options.component:
        x = cl.options.component.split(",")
        if not set(x) <= set(BUGLIST.COMPONENT_DICT.keys()):
            raise ValueError, "unknown component: %s" %x
        bug_filter.add_option("component", x)
        
    if cl.options.closed_bugs:
        bug_filter.add_option("status", BUG.STATUS.values())
        
    if cl.options.tag:
        bug_filter.add_option("tag", cl.options.tag.split(","))
        
    if cl.options.duplicates:
        bug_filter.add_option("duplicates", ("off",))

    if cl.options.patch:
        bug_filter.add_option("has-patch", ("on",))
    
    if cl.options.needs_forwarding:
        bug_filter.add_option("upstream-status", ("pending_bugwatch",))

    if cl.options.fixed_upstream:
        bug_filter.add_option("upstream-status", ("resolved_upstream",))
        
    if cl.options.reporter:
        bug_filter.add_option("reporter", (cl.options.reporter,))

    if cl.options.subscriber:
        bug_filter.add_option("subscriber", (cl.options.subscriber,))

    if cl.options.commenter:
        bug_filter.add_option("commenter", (cl.options.commenter,))

    if cl.options.supervisor:
        bug_filter.add_option("supervisor", (cl.options.supervisor,))

        
    #print "USING THIS URL, ", bug_filter.baseurl
    #sys.exit(1)

    try:
        bl = BugList(cl.options.url)
    except LaunchpadError, e:
        if cl.options.sourcepackage:
            print >> sys.stderr, "Maybe package '%s' does not exist in Ubuntu." % cl.options.sourcepackage
        else:
            print >> sys.stderr, "Error while parsing '%s': %s.%s" %(cl.options.url, e, x)
        for i in ("+assignedbugs","+commentedbugs","+reportedbugs","+subscribedbugs"):
            if i in cl.options.url.baseurl:
                print >> sys.stderr, "Error while parsing '%s': %s.%s" %(cl.options.url.baseurl, e, x)
                print >> sys.stderr, "Please try using \"--parsemode=html\"" 
                break
        else:
            print >> sys.stderr, "Error while parsing '%s': %s.%s" %(cl.options.url.baseurl, e, x)
        sys.exit(1)
        
    if cl.options.upstream and cl.options.sourcepackage:
            l = None
            try:
                l = BugList(bug_filter("%s/%s/+bugs" %(BASEURL.BUG, cl.options.sourcepackage)))
            except LaunchpadError, e:
                print >> sys.stderr, "There is no product <%s> in launchpad.net" %cl.options.sourcepackage
            if l:
                bl += l
            
    if cl.options.sourcepackage:
        path = os.path.expanduser(os.path.join(conf.attachments_cache, 
                                               cl.options.sourcepackage))
        utils.remove_obsolete_attachments(path, bl)      
    
    if not bl:
        if not bug_filter.urlopt:
            out.info("There are currently no open bugs.")
        else:
            out.info("No results for search.")
        sys.exit(1)
    elif cl.options.count:
        for x in bl:
            try:
                comments = x.comments
            except AttributeError:
                b = Bug(x)
                comments = b.comments
            out.print_item({"bug" : x, "count" : len(comments)},"comments")
    elif cl.options.stats:
        out.print_item(statistic.summary(bl),"statistic")
    else:
        if cl.options.sort:
            x = bl.sort(cl.options.sort)
            for bi in x:
                out.print_item({"bug" :bi})
        else:
            for bi in bl:
                out.print_item({"bug" :bi})

    footer_opt = {}
    if cl.options.footer:
        o = list(cl.options.footer)
        if "s" in o:
            footer_opt["statistic"] = statistic.summary(bl)
        if "t" in o:
            footer_opt["time"] = {
                "time": time.strftime("%a, %d %b %Y %H:%M:%S %Z"),
                "duration" : "%i" %(time.time() - start)}
    out.print_footer(footer_opt)
        

if __name__ == "__main__":
    main()