File: popcon.py

package info (click to toggle)
python-popcon 3.0.3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 112 kB
  • sloc: python: 225; makefile: 35
file content (342 lines) | stat: -rw-r--r-- 8,784 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
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
#!/usr/bin/env python


"""Get Debian popcon values for given packages.

The usage of this module is easy:

    >>> import popcon
    >>> popcon.package('reportbug-ng')
    {'reportbug-ng': 323}
    >>> popcon.package('reportbug-ng', 'reportbug')
    {'reportbug-ng': 323, 'reportbug': 75065}

The raw data (vote, old, recent, no-file) is also available, the sum of
the raw numbers is the number of installations as reported by
`popcon.package`.

    >>> popcon.package_raw('reportbug-ng', 'reportbug')
    {'reportbug-ng': Package(vote=50, old=187, recent=86, no_files=0),
            'reportbug': Package(vote=5279, old=59652, recent=10118,
            no_files=16)}

Behind the scene popcon will try to use cached information saved in a
file in the ~/.cache/popcon directory. If the relevant file is not
available, or older than `EXPIRY` seconds (default is 7 days) it will
download fresh data and save that.

The cached data will be kept in memory unless `KEEP_DATA` is set to
False.

"""


import warnings
import time
from urllib.request import Request, urlopen
import gzip
import io
import tempfile
import pickle
import os
import collections
import logging


logger = logging.getLogger(__name__)


XDG_CACHE_HOME = os.environ.get('XDG_CACHE_HOME',
                                os.path.expandvars('$HOME/.cache'))

__author__ = 'Bastian Venthur <venthur@debian.org>'

Package = collections.namedtuple(
    "Package", ["vote", "old", "recent", "no_files"])


# week in seconds
EXPIRY = 60 * 60 * 24 * 7
KEEP_DATA = True
cached_data = {}
cached_timestamp = {}


def _fetch(url):
    """Fetch all popcon results and return unparsed data.

    Parameters
    ----------
    url : str
        the url of the gzipped popcon results

    Returns
    -------
    txt : str
        the uncompressed data

    """
    request = Request(url)
    response = urlopen(request)
    txt = response.read()
    response.close()
    txt = _decompress(txt)
    return txt


def _parse(results):
    """Parse all-popcon-results file.

    Parameters
    ----------
    results : str
        the results file

    Returns
    -------
    ans : dict
        package name -> `Package` namedtuple mapping, containing the
        package information

    """
    ans = dict()
    results = results.splitlines()
    for line in results:
        elems = line.split()
        if elems[0] != b"Package:":
            continue
        ans[elems[1]] = Package(*(int(i) for i in elems[2:]))
    return ans


def _parse_stats(results):
    """Parse "statistics" files.

    Parameters
    ----------
    results : str
        the results file

    Returns
    -------
    ans : dict
        package name -> `Package` namedtuple mapping, containing the
        package information

    """
    ans = dict()
    results = results.splitlines()
    for line in results:
        elems = line.split()
        try:
            int(elems[0])
            int(elems[2])  # e.g. skip pass the "not in sid" pseudo-package
            if elems[1] == b"Total":
                continue
        except Exception:
            continue
        ans[elems[1]] = Package(*(int(i) for i in elems[3:]))
    return ans


def _decompress(compressed):
    """Decompress a gzipped string.

    Parameters
    ----------
    compressed : str
        the compressed string

    Returns
    -------
    data : str
        the uncompressed string

    """
    gzippedstream = io.BytesIO(compressed)
    gzipper = gzip.GzipFile(fileobj=gzippedstream)
    data = gzipper.read()
    return data


def packages(package_list):
    """Return the number of installations.

    The return value is a dict where the keys are the packages and the
    values the number of installations. If a package was not found it is
    not in the dict.

    Parameters
    ----------
    package_list : list of strings
        the package names

    Returns
    -------
    ans : dict
        packagename -> number of installations mapping

    """
    raw = packages_raw(package_list)
    ans = dict()
    for pkg, values in list(raw.items()):
        ans[pkg] = sum(values)
    return ans


def source_packages(package_list):
    """Return the number of installations, for source packages.

    See `package` for the format of the returned data.

    At present, this is only an approximation that instead gives the
    maximum value, out of the number of installations of any binary
    package belonging to each source package.

    Parameters
    ----------
    package_list : list of strings
        the package names

    Returns
    -------
    ans : dict
        packagename -> number of installations mapping

    """
    raw = source_packages_raw(package_list)
    ans = dict()
    for pkg, values in list(raw.items()):
        ans[pkg] = sum(values)
    return ans


def packages_raw(package_list):
    """Return the raw popcon values for the given packages.

    The return value is a dict where the keys are the packages and the
    values a named tuple of integers: (vote, old, recent, no-files)

    * vote: number of people who use this package regulary
    * old: is the number of people who installed, but don't use this
      package regularly
    * recent: is the number of people who upgraded this package recently
    * no-files: is the number of people whose entry didn't contain
      enough information (atime and ctime were 0)

    Parameters
    ----------
    package_list : list of strings
        the package names

    Returns
    -------
    ans : dict

    """
    return _packages_raw_generic(
        "https://popcon.debian.org/all-popcon-results.txt.gz",
        _parse, "debian", package_list)


def source_packages_raw(package_list):
    """Return the raw popcon values for the given source packages.

    See `package_raw` for the format of the returned data.

    At present, this is only an approximation that instead gives the
    maximum value, out of the number of installations of any binary
    package belonging to each source package.

    Parameters
    ----------
    package_list : list of strings

    Returns
    -------
    ans : dict

    """
    return _packages_raw_generic(
        "https://popcon.debian.org/sourcemax/by_inst.gz",
        _parse_stats, "debian-sourcemax", package_list)


def _packages_raw_generic(url, parse, key, package_list):
    """The work mule

    Parameters
    ----------
    url : str
        the url to use
    parse : function
        the parser function
    key : str
        "debian-sourcemax" or "debian"
    package_list : list of strings
        the debian package names

    Returns
    -------
    ans : dict

    """
    global cached_data, cached_timestamp
    # implements BASEDIRSPEC
    # https://standards.freedesktop.org/basedir-spec/basedir-spec-0.6.html
    dumpfile = os.path.join(
        XDG_CACHE_HOME,
        'popcon',
        "%s.%s" % (key, pickle.format_version))

    earliest_possible_mtime = max(
        time.time() - EXPIRY,
        os.stat(__file__).st_mtime)

    if (key in cached_data
            and cached_timestamp.get(key, 0) <= earliest_possible_mtime):
        del cached_data[key]

    data = cached_data.get(key, None)
    if (data is None
            and os.path.exists(dumpfile)
            and os.stat(dumpfile).st_mtime > earliest_possible_mtime):
        try:
            with open(dumpfile, 'rb') as fh:
                data = pickle.load(fh)
            cached_timestamp[key] = os.stat(dumpfile).st_mtime
        except Exception:
            import traceback
            warnings.warn("Problems loading cache file: %s" % dumpfile)
            traceback.print_exc()

    if data is None:
        data = _fetch(url)
        data = parse(data)
        # i still think that makedirs should behave like mkdir -p
        if not os.path.isdir(os.path.dirname(dumpfile)):
            os.makedirs(
                os.path.dirname(dumpfile),
                mode=0o700)  # mode according to BASEDIRSPEC
        # as soon as python2.6 is in stable, we can use delete=False
        # here and replace the flush/rename/try:close sequence with the
        # cleaner close/rename.
        temp = tempfile.NamedTemporaryFile(dir=os.path.dirname(dumpfile))
        pickle.dump(data, temp)
        temp.flush()
        os.rename(temp.name, dumpfile)
        try:
            temp.close()
        except OSError:
            pass
        cached_timestamp[key] = time.time()
    ans = dict()
    for pkg in package_list:
        # Lookup using bytestrings, but always index results by the
        # original so that callsites can look it up.
        lookup = pkg if isinstance(pkg, bytes) else pkg.encode('utf-8')
        if lookup in data:
            ans[pkg] = data[lookup]
    if KEEP_DATA:
        cached_data[key] = data
    return ans