~brian-murray/ubuntu-archive-tools/pup-raring

« back to all changes in this revision

Viewing changes to edit_acl.py

  • Committer: Colin Watson
  • Author(s): Julian Edwards
  • Date: 2008-10-16 10:30:42 UTC
  • Revision ID: cjwatson@canonical.com-20081016103042-i4xylivhzpq9tp2z
new script to edit uploader ACLs

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/usr/bin/env python2.4
 
2
 
 
3
# Copyright 2008 Canonical Ltd.  All rights reserved.
 
4
 
 
5
"""Edit uploader permissions for the Ubuntu distro in Launchpad."""
 
6
 
 
7
from optparse import OptionParser
 
8
import sys, os
 
9
sys.path.insert(0, os.path.join(
 
10
    os.path.dirname(__file__), 'lib'))
 
11
 
 
12
try:
 
13
    import launchpadlib
 
14
    from launchpadlib.credentials import Credentials
 
15
    from launchpadlib.launchpad import (
 
16
        Launchpad, EDGE_SERVICE_ROOT, STAGING_SERVICE_ROOT)
 
17
except ImportError:
 
18
    print "Can't find launchpadlib, is your PYTHONPATH correct?\n"
 
19
    raise
 
20
 
 
21
 
 
22
API_AUTH = os.path.join(os.getenv("HOME"), ".lp_api_auth")
 
23
CONSUMER_KEY = "edit_acl.py"
 
24
 
 
25
 
 
26
class InvalidCredentials(Exception):
 
27
    pass
 
28
 
 
29
 
 
30
class Retry(Exception):
 
31
    pass
 
32
 
 
33
 
 
34
class LPSystem:
 
35
    cachedir = os.path.join(os.environ['HOME'], '.launchpadlib', 'cache')
 
36
    endpoint = None
 
37
    auth_file = None
 
38
    def __init__(self):
 
39
        if not os.path.exists(self.cachedir):
 
40
            try:
 
41
                os.makedirs(self.cachedir)
 
42
            except error:
 
43
                self.cachedir = None
 
44
        try:
 
45
            # Load credentials from AUTH_FILE if it exists.
 
46
            self.auth_file = os.path.join(
 
47
                os.environ['HOME'], self.auth_file_name)
 
48
            self.credentials = Credentials()
 
49
            self.credentials.load(open(self.auth_file))
 
50
            print "Loading credentials..."
 
51
            try:
 
52
                self.launchpad = Launchpad(
 
53
                    self.credentials, self.endpoint, cache=self.cachedir)
 
54
            except launchpadlib.errors.HTTPError:
 
55
                raise InvalidCredentials, (
 
56
                    "Please remove %s and rerun %s to authenticate." % (
 
57
                    self.auth_file, sys.argv[0]))
 
58
        except IOError:
 
59
            # Prompt for authentication process, then save credentials to
 
60
            # self.auth_file.
 
61
            try:
 
62
                print "Getting credentials..."
 
63
                self.launchpad = Launchpad.get_token_and_login(
 
64
                    CONSUMER_KEY, self.endpoint, cache=self.cachedir)
 
65
                self.launchpad.credentials.save(open(self.auth_file, "w"))
 
66
                print "Credentials saved"
 
67
            except launchpadlib.errors.HTTPError, err:
 
68
                print err.content
 
69
                raise
 
70
 
 
71
 
 
72
class Edge(LPSystem):
 
73
    endpoint = EDGE_SERVICE_ROOT
 
74
    auth_file_name = API_AUTH + '_edge'
 
75
 
 
76
 
 
77
class Staging(LPSystem):
 
78
    endpoint = STAGING_SERVICE_ROOT
 
79
    auth_file_name = API_AUTH + '_staging'
 
80
 
 
81
 
 
82
class Production(LPSystem):
 
83
    endpoint = 'https://api.launchpad.net/beta/'
 
84
    auth_file_name = API_AUTH
 
85
 
 
86
 
 
87
systems=dict(staging=Staging,
 
88
             edge=Edge,
 
89
             beta=Edge,
 
90
             production=Production,
 
91
             prod=Production,
 
92
             )
 
93
 
 
94
 
 
95
def lpfactory(sysname):
 
96
    """Get a launchpad API instance for `sysname`."""
 
97
    try:
 
98
        sysname = sysname.lower()
 
99
        lpinstance = systems[sysname]
 
100
        return lpinstance().launchpad
 
101
    except KeyError:
 
102
        print "System '%s' not supported." % sysname
 
103
        print "Use one of: ", systems.keys()
 
104
        return None
 
105
 
 
106
 
 
107
def print_perms(perms):
 
108
    for perm in perms:
 
109
        print (
 
110
            perm.permission, perm.person.name, perm.component_name,
 
111
            perm.source_package_name)
 
112
 
 
113
 
 
114
def get_main_archive(launchpad):
 
115
    distros = launchpad.distributions
 
116
    ubuntu = distros['ubuntu']
 
117
    return ubuntu.main_archive
 
118
 
 
119
 
 
120
def do_query(options):
 
121
    """Query existing permissions and show on stdout."""
 
122
    launchpad = lpfactory(options.launchpad_instance)
 
123
    main_archive = get_main_archive(launchpad)
 
124
 
 
125
    if options.person:
 
126
        person = launchpad.people[options.person]
 
127
        perms = main_archive.getPermissionsForPerson(person=person)
 
128
        print "== All rights for %s ==" % options.person
 
129
        print_perms(perms)
 
130
 
 
131
    if options.component:
 
132
        perms = main_archive.getUploadersForComponent(
 
133
            component_name=options.component)
 
134
        print "== All rights for component '%s' ==" % options.component
 
135
        print_perms(perms)
 
136
 
 
137
    if options.source:
 
138
        perms = main_archive.getUploadersForPackage(
 
139
            source_package_name=options.source)
 
140
        print "== All uploaders for package '%s' ==" % options.source
 
141
        print_perms(perms)
 
142
 
 
143
 
 
144
def validate_add_delete_options(options):
 
145
    if not options.person:
 
146
        print "You must specify a person to authorise."
 
147
        return False
 
148
 
 
149
    if options.source and options.component:
 
150
        print "You can only specify one of 'source' or 'component'"
 
151
        return False
 
152
 
 
153
    if not options.source and not options.component:
 
154
        print "You must specify one of 'source package' or 'component'"
 
155
        return False
 
156
 
 
157
    return True
 
158
 
 
159
 
 
160
def do_add(options):
 
161
    """Add a new permission."""
 
162
    if not validate_add_delete_options():
 
163
        return False
 
164
 
 
165
    launchpad = lpfactory(options.launchpad_instance)
 
166
    main_archive = get_main_archive(launchpad)
 
167
    person = launchpad.people[options.person]
 
168
 
 
169
    if options.source:
 
170
        perm = main_archive.newPackageUploader(
 
171
            person=person, source_package_name=options.source)
 
172
        print "Added:"
 
173
        print_perms([perm,])
 
174
        return
 
175
 
 
176
    if options.component:
 
177
        perm = main_archive.newComponentUploader(
 
178
            person=person, component_name=options.component)
 
179
        print "Added:"
 
180
        print_perms([perm,])
 
181
        return
 
182
 
 
183
 
 
184
def do_delete(options):
 
185
    """Delete a permission."""
 
186
    if not validate_add_delete_options():
 
187
        return False
 
188
    
 
189
    launchpad = lpfactory(options.launchpad_instance)
 
190
    main_archive = get_main_archive(launchpad)
 
191
    person = launchpad.people[options.person]
 
192
 
 
193
    if options.source:
 
194
        perm = main_archive.deletePackageUploader(
 
195
            person=person, source_package_name=options.source)
 
196
        print "Deleted %s/%s" % (options.person, options.source)
 
197
        return
 
198
 
 
199
    if options.component:
 
200
        perm = main_archive.deleteComponentUploader(
 
201
            person=person, component_name=options.component)
 
202
        print "Deleted %s/%s" % (options.person, options.component)
 
203
        return
 
204
 
 
205
 
 
206
def main(options, action):
 
207
 
 
208
    if action == "query":
 
209
        do_query(options)
 
210
    elif action == "add":
 
211
        do_add(options)
 
212
    elif action == "delete":
 
213
        do_delete(options)
 
214
    else:
 
215
        raise AssertionError("Invalid action %s" % action)
 
216
 
 
217
    return
 
218
 
 
219
 
 
220
if __name__ == '__main__':
 
221
    parser = OptionParser()
 
222
 
 
223
    parser.add_option(
 
224
        "-l", "--launchpad", dest="launchpad_instance", default="production")
 
225
    parser.add_option("-p", "--person", dest="person")
 
226
    parser.add_option("-c", "--component", dest="component")
 
227
    parser.add_option("-s", "--source", dest="source")
 
228
 
 
229
    options, args = parser.parse_args()
 
230
 
 
231
    possible_actions = ('query', 'add', 'delete')
 
232
 
 
233
    if len(args) != 1:
 
234
        parser.error(
 
235
            "You must specify an action, one of:\n%s"
 
236
                % ", ".join(possible_actions))
 
237
 
 
238
    if not options.person and not options.component and not options.source:
 
239
        parser.error("Provide at least one of person/component/source")
 
240
 
 
241
    try:
 
242
        main(options, args[0])
 
243
    except launchpadlib.errors.HTTPError, err:
 
244
        print "There was an error:"
 
245
        print err.content
 
246
 
 
247