File: lp.py

package info (click to toggle)
ppa-dev-tools 0.6.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,096 kB
  • sloc: python: 5,069; makefile: 3
file content (207 lines) | stat: -rw-r--r-- 7,556 bytes parent folder | download
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
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-

# Author:  Bryce Harrington <bryce@canonical.com>
#
# Copyright (C) 2021 Bryce W. Harrington
#
# Released under GNU AGPL or later, read the file 'LICENSE.AGPL' for
# more information.

# Extraction of bileto's lp class, for general use in other places

"""Launchpad Interface."""

from contextlib import suppress
from functools import lru_cache

from launchpadlib.launchpad import Launchpad
from launchpadlib.credentials import Credentials


class Lp:
    """High level wrapper object for Launchpad's API.

    This class wrappers the Launchpadlib service to cache object queries
    and to provide functionalies frequently needed when writing software
    for managing the Ubuntu distribution.

    This can be used as a drop-in replacement in scripts that already
    use Launchpadlib.  Simply replace your Launchpadlib.login_with() call
    with an instantiation of this class.  Any call that Lp does not handle
    itself is passed directly to the Launchpadlib object, so the entire
    API is available in exactly the same way.
    """
    # pylint: disable=invalid-name
    ROOT_URL = 'https://launchpad.net/'
    API_ROOT_URL = 'https://api.launchpad.net/devel/'
    BUGS_ROOT_URL = 'https://bugs.launchpad.net/'
    CODE_ROOT_URL = 'https://code.launchpad.net/'

    _real_instance = None

    def __init__(self, application_name, service=Launchpad, staging=False, credentials=None):
        """Create a Launchpad service object.

        Authentication with Launchpad is done lazily, not at object
        initialization but at the point it first needs to actually use
        Launchpad functionality.  This permits adjustment of the
        object's credentials or other properties as needed.

        If the `$LP_CREDENTIAL` environment variable is defined, its
        contents will be loaded as the credentials to pass to the
        Credentials.from_string() function.  Stored credentials must
        be formatted according to the requirements of launchpadlib's
        Credentials class.  For more information on this class see:
            https://git.launchpad.net/launchpadlib/tree/src/launchpadlib/credentials.py

        :param str application_name: The text name of the software using
            this class.
        :param Launchpad service: The launchpadlib service class or
            object to wrapper.
        :param bool staging: When true, operate against a test instance
            of Launchpad instead of the real one.
        :param str credentials: (Optional) Formatted OAuth information
            to use when authenticating with Launchpad.  If not provided,
            will automatically login to Launchpad as needed.
        """
        self._app_name = application_name
        self._service = service
        self._credentials = credentials
        if staging:
            self._service_root = 'qastaging'
            self.ROOT_URL = 'https://qastaging.launchpad.net/'
            self.API_ROOT_URL = 'https://api.qastaging.launchpad.net/devel/'
            self.BUGS_ROOT_URL = 'https://bugs.qastaging.launchpad.net/'
            self.CODE_ROOT_URL = 'https://code.qastaging.launchpad.net/'
        else:
            self._service_root = 'production'

    def _get_instance_from_creds(self) -> 'Launchpad | None':
        """
        Get an instance of _service using stored credentials if defined,
        else return None.

        For more information on Launchpad credentials-based authentication see
        https://help.launchpad.net/API/launchpadlib#Authenticated_access_for_website_integration

        :rtype: Launchpad | None
        :returns: Logged in Launchpad instance if credentials available,
            else None
        """
        if self._credentials:
            cred = Credentials.from_string(self._credentials)
            return self._service(
                cred, None, None,
                service_root=self._service_root,
                version='devel'
            )
        return None

    def _get_instance_from_login(self) -> 'Launchpad':
        """
        Prompts the user to authorize the login of a new credential
        or use the cached one if it is available and valid

        :rtype: launchpadlib.launchpad.Launchpad
        :returns: Logged in Launchpad instance
        """
        return self._service.login_with(
            application_name=self._app_name,
            service_root=self._service_root,
            allow_access_levels=['WRITE_PRIVATE'],
            version='devel',  # Need devel for copyPackage.
        )

    @property
    def _instance(self):
        """Cache LP object."""
        if not self._real_instance:
            self._real_instance = (
                self._get_instance_from_creds() or
                self._get_instance_from_login()
            )
        return self._real_instance

    @property
    @lru_cache()
    def _api_root(self):
        """Identify the root URL of the launchpad API."""
        return self._instance.resource_type_link.split('#')[0]

    def __getattr__(self, attr):
        """Wrap launchpadlib so tightly you can't tell the difference."""
        assert not attr.startswith('_'), f"Can't getattr for {attr}"
        instance = super(Lp, self).__getattribute__('_instance')
        return getattr(instance, attr)

    @property
    @lru_cache()
    def ubuntu(self):
        """Shorthand for Ubuntu object.

        :rtype: distribution
        :returns: The distribution object for 'ubuntu'.
        """
        return self.distributions['ubuntu']

    @lru_cache()
    def ubuntu_active_series(self):
        """Identify currently supported Ubuntu series.

        This includes the series currently under development, but not
        ones which are experimental or obsolete.

        :rtype: list of distro_series
        :returns: All active Launchpad distro series for the Ubuntu project.
        """
        return [s for s in self.ubuntu.series if s.active]

    @property
    @lru_cache()
    def debian(self):
        """Shorthand for Debian object.

        :rtype: distribution
        :returns: The distribution object for 'debian'.
        """
        return self.distributions['debian']

    @lru_cache()
    def debian_active_series(self):
        """Identify currently supported Debian series.

        :rtype: list of distro_series
        :returns: All active Launchpad distro series for the Debian project.
        """
        return [s for s in self.debian.series if s.active]

    @lru_cache()
    def debian_experimental_series(self):
        """Shorthand for Debian experimental series.

        :rtype: distro_series
        :returns: The Launchpad distro series for the Debian project.
        """
        return next(iter([s for s in self.debian.series if s.name == 'experimental']), None)

    @lru_cache()
    def get_teams(self, user):
        """Retrieve list of teams that user belongs to.

        :param str user: Name of the user to look up.
        :rtype: list(str)
        :returns: List of team names.
        """
        with suppress(KeyError, TypeError):
            return [
                team.self_link.partition('~')[-1].partition('/')[0]
                for team in self.people[user].memberships_details]

    def load(self, url):
        """Return a lp resource from a launchpad url.

        :param str url: The launchpad resource URL.
        :rtype: varies
        :returns: Launchpadlib object corresponding to given url.
        """
        return self._instance.load(url)