~yofel/+junk/lp-scripts

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
#!/usr/bin/env python
#
# Script to set the "Expired" status on Launchpad
#
# Copyright (C) 2010-2011 Philip Muskovac
#
# This program 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 3 of the License, or
# (at your option) any later version.
#
# This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

import sys
import re
import os
from optparse import OptionParser
try:
    from launchpadlib.launchpad import Launchpad
    from launchpadlib.errors import HTTPError
except ImportError:
    print >> sys.stderr, "Import Error. python-launchpadlib not installed?"
    sys.exit(1)

def get_bug_task(lp_bug, task_name):
    """ Switch through available bug tasks and return the desired one
    lp_bug: instance of launchpadlib.launchpad.Launchpad.bugs[bugnumber]
    task_name: name of the bug task, example: bash(Ubuntu)"""
    if options.debug:
        print("#DEBUG: set task: %s" % task_name)
    for task in lp_bug.bug_tasks:
        if options.debug:
            print("#DEBUG: %s" % task.bug_target_name) ### DEBUG
        if re.search(task_name.replace("(", "\(").replace(")", "\)"),
                     task.bug_target_name,
                     re.IGNORECASE):
            var = raw_input("Bug Task: %s. Correct? (y/N) " % task.bug_target_display_name)
            if var == "y":
                return task

    # quit if no bug task selected
    print("No bug task selected!")
    sys.exit(0)


def launchpad_login(staging):
    """Launchpad login with credentials file handling
    staging: if true login to staging instead of production"""
    if options.debug:
        print("#DEBUG: Setting up Launchpad")

    if options.staging:
        auth_file="lp-set-expired.staging.txt"
    else:
        auth_file="lp-set-expired.production.txt"

    credentials_dir="~/.cache/lp_credentials"
    cred_dir_path=os.path.expanduser(credentials_dir)
    file_path=os.path.expanduser("%s/%s" % (credentials_dir, auth_file))
    if options.debug:
        print("#DEBUG: auth file: %s" % file_path)
    # create directory if missing
    if not os.path.isdir(cred_dir_path):
        os.makedirs(cred_dir_path)
        os.chmod(cred_dir_path, 0700)
    try:
        if options.staging:
            if options.debug:
                print('#DEBUG: using staging')
            lp = Launchpad.login_with('lp-set-expired', 'staging',
                    credentials_file=file_path)
        else:
            lp = Launchpad.login_with('lp-set-expired', 'production',
                    credentials_file=file_path)
    except HTTPError, error:
        if error.response.status == 401:
            print >> sys.stderr, "E: Not Authorised!"
            sys.exit(2)

        elif error.response.status == 503:
            print >> sys.stderr, "E: Service unavialable, please try again later!"
            sys.exit(2)

        else:
            raise
    except IOError, error:
        if error.errno == 13:
            print >> sys.stderr, "E: Permission denied when opening credentials file (owned by root?):"
            print >> sys.stderr, file_path
            sys.exit(3)
        else:
            raise

    if options.debug:
        print("#DEBUG: Launchpad Setup complete")

    return lp

# MAIN
if __name__ == "__main__":

    # No reply response
    comment = """We are closing this bug report because it lacks the information \
we need to investigate the problem, as described in the previous comments. \
However, if the issue still exists please feel free to reopen with the requested information, and don't hesitate \
to submit bug reports in the future. To reopen the bug report you can click  \
on the current status, under the Status column, and change the Status back to \
"New". Thanks again! """

    # Parse command line options
    if len(sys.argv) <= 1:
        # no options given
        print("At least -h --help or bug number required!")
        sys.exit(0)

    parser = OptionParser('%prog [options] <bug_number> [<bug_number>...]')
    parser.add_option("-n", "--no-reply", action="store_true",
                      dest="no_reply", default=False,
                      help="post \"no-reply\" stock response before expiring bug")
    parser.add_option("-t", dest="taskname", default="ubuntu",
                      help="Name of the Launchpad Task (quoted!). Default: \"ubuntu\"")
    parser.add_option("--staging", dest="staging", default=False,
                      action="store_true",
                      help="use staging.launchpad.net instead of production")
    parser.add_option("--debug", dest="debug", default=False, action="store_true",
                      help="give some information useful for debugging")

    (options, args) = parser.parse_args()

    if len(args) < 1:
        parser.error("Need at least one bug to work with!")


    if options.debug:
        print("#DEBUG: cli options given: %s\n" % sys.argv) ### DEBUG

    # Login to launchpad
    lp = launchpad_login(options.staging)

    # Process every bug given
    for bug_n in args:

        try:
            bug_number = int(bug_n)
        except ValueError:
            parser.error("Invalid bug number!")

        try:
            bug = lp.bugs[bug_number]

            # Check if it's the right bug
            print("Bug %d:" % bug_number)
            print("Title: \"%s\"" % bug.title)

            if options.no_reply:
                print("Posting response")

            var = raw_input("Do you want to continue? (y/N) ")
            if var != "y":
                sys.exit(0)

            # Get bug task from launchpad
            bug_task = get_bug_task(bug, options.taskname)

            if bug_task.status == "Expired":
                print("Bug already Expired!\n")
                continue

            print("Expiring Bug %d" % bug_number)

            if options.no_reply:
                if options.debug:
                    print("#DEBUG: reply message: %s" % bug.newMessage(content = comment))
                else:
                    bug.newMessage(content = comment)

            # Set status to Expired
            bug_task.status = "Expired"
            bug_task.lp_save()

            print("Done!\n")

        except HTTPError, error:
            if error.response.status == 401:
                print >> sys.stderr, "E: Don't have enough permissions to access bug %d" % bug_number
                sys.exit(2)
            elif error.response.status == 404:
                print >> sys.stderr, "E: Bug %d not found" % bug_number
                sys.exit(2)
            elif error.response.status == 503:
                print >> sys.stderr, "E: Service unavailable, please try again later!"
                sys.exit(2)
            else:
                raise