aboutsummaryrefslogtreecommitdiff
blob: 2b201c63c0e2eba7eb89e2d9d7af31cebe3fc9d4 (plain)
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
    pypi_db.py
    ~~~~~~~~~~
    
    PyPI package database
    
    :copyright: (c) 2013 by Jauhien Piatlicki
    :license: GPL-2, see LICENSE for more details.
"""

import datetime
import re
import time

import bs4

from g_sorcery.exceptions import DownloadingError
from g_sorcery.g_collections import Package, serializable_elist
from g_sorcery.package_db import DBGenerator

class PypiDBGenerator(DBGenerator):
    """
    Implementation of database generator for PYPI backend.
    """
    def get_download_uries(self, common_config, config):
        """
        Get URI of packages index.
        """
        self.repo_uri = config["repo_uri"]
        return [{"uri": self.repo_uri + "pypi?%3Aaction=index", "output": "packages"}]

    def parse_data(self, data_f):
        """
        Download and parse packages index. Then download and parse pages for all packages.
        """
        soup = bs4.BeautifulSoup(data_f.read())
        packages = soup.table
        data = {}
        data["index"] = {}

        pkg_uries = []
        
        for entry in packages.find_all("tr")[1:-1]:
            package, description = entry.find_all("td")
            
            if description.contents:
                description = description.contents[0]
            else:
                description = ""
            package, version = package.a["href"].split("/")[2:]            
            data["index"][(package, version)] = description
            pkg_uries.append({"uri": self.repo_uri + "pypi/" + package + "/" + version,
                              "parser": self.parse_package_page,
                              "output": package + "-" + version})
            entry.decompose()

        packages.decompose()
        soup.decompose()

        pkg_uries = self.decode_download_uries(pkg_uries)
        for uri in pkg_uries:
            attempts = 0
            while True:
                try:
                    attempts += 1
                    self.process_uri(uri, data)
                except DownloadingError as error:
                    print(str(error))
                    time.sleep(5)
                    if attempts < 100:
                        continue
                break

        return data

    def parse_package_page(self, data_f):
        """
        Parse package page.
        """
        soup = bs4.BeautifulSoup(data_f.read())
        data = {}
        data["files"] = []
        data["info"] = {}
        try:
            for table in soup("table", class_ = "list")[-1:]:
                if not "File" in table("th")[0].string:
                    continue

                for entry in table("tr")[1:-1]:
                    fields = entry("td")

                    FILE = 0
                    URL = 0
                    MD5 = 1

                    TYPE = 1
                    PYVERSION = 2
                    UPLOADED = 3
                    SIZE = 4

                    file_inf = fields[FILE]("a")[0]["href"].split("#")
                    file_url = file_inf[URL]
                    file_md5 = file_inf[MD5][4:]

                    file_type = fields[TYPE].string
                    file_pyversion = fields[PYVERSION].string
                    file_uploaded = fields[UPLOADED].string
                    file_size = fields[SIZE].string

                    data["files"].append({"url": file_url,
                                          "md5": file_md5,
                                          "type": file_type,
                                          "pyversion": file_pyversion,
                                          "uploaded": file_uploaded,
                                          "size": file_size})
                    entry.decompose()
                table.decompose()

            uls = soup("ul", class_ = "nodot")
            if uls:
                if "Downloads (All Versions):" in uls[0]("strong")[0].string:
                    ul = uls[1]
                else:
                    ul = uls[0]

                for entry in ul.contents:
                    if not hasattr(entry, "name") or entry.name != "li":
                        continue
                    entry_name = entry("strong")[0].string
                    if not entry_name:
                        continue

                    if entry_name == "Categories":
                        data["info"][entry_name] = {}
                        for cat_entry in entry("a"):
                            cat_data = cat_entry.string.split(" :: ")
                            if not cat_data[0] in data["info"][entry_name]:
                                data["info"][entry_name][cat_data[0]] = cat_data[1:]
                            else:
                                data["info"][entry_name][cat_data[0]].extend(cat_data[1:])
                        continue

                    if entry("span"):
                        data["info"][entry_name] = entry("span")[0].string
                        continue

                    if entry("a"):
                        data["info"][entry_name] = entry("a")[0]["href"]
                        continue
                    entry.decompose()
                ul.decompose()

        except Exception as error:
            print("There was an error during parsing: " + str(error))
            print("Ignoring this package.")
            data = {}
            data["files"] = []
            data["info"] = {}

        soup.decompose()
        return data

    def process_data(self, pkg_db, data, common_config, config):
        """
        Process parsed package data.
        """
        category = "dev-python"
        pkg_db.add_category(category)

        #todo: write filter functions
        allowed_ords_pkg = set(range(ord('a'), ord('z') + 1)) | set(range(ord('A'), ord('Z') + 1)) | \
            set(range(ord('0'), ord('9') + 1)) | set(list(map(ord,
                ['+', '_', '-'])))

        allowed_ords_desc = set(range(ord('a'), ord('z') + 1)) | set(range(ord('A'), ord('Z') + 1)) | \
              set(range(ord('0'), ord('9') + 1)) | set(list(map(ord,
                    ['+', '_', '-', ' ', '.', '(', ')', '[', ']', '{', '}', ','])))

        now = datetime.datetime.now()
        pseudoversion = "%04d%02d%02d" % (now.year, now.month, now.day)

        for (package, version), description in data["packages"]["index"].items():

            pkg = package + "-" + version
            if not pkg in data["packages"]:
                continue

            pkg_data = data["packages"][pkg]
            
            if not pkg_data["files"] and not pkg_data["info"]:
                continue

            files_src_uri = ""
            md5 = ""
            if pkg_data["files"]:
                for file_entry in pkg_data["files"]:
                    if file_entry["type"] == "\n    Source\n  ":
                        files_src_uri = file_entry["url"]
                        md5 = file_entry["md5"]
                        break

            download_url = ""
            info = pkg_data["info"]
            if info:
                if "Download URL:" in info:
                    download_url = pkg_data["info"]["Download URL:"]

            if download_url:
                source_uri = download_url #todo: find how to define src_uri
            else:
                source_uri = files_src_uri

            if not source_uri:
                continue

            homepage = ""
            pkg_license = ""
            py_versions = []
            if info:
                if "Home Page:" in info:
                    homepage = info["Home Page:"]
                categories = {}
                if "Categories" in info:
                    categories = info["Categories"]

                    if 'Programming Language' in  categories:
                        for entry in categories['Programming Language']:
                            if entry == '2':
                                py_versions.extend(['2_6', '2_7'])
                            elif entry == '3':
                                py_versions.extend(['3_2', '3_3'])
                            elif entry == '2.6':
                                py_versions.extend(['2_6'])
                            elif entry == '2.7':
                                py_versions.extend(['2_7'])
                            elif entry == '3.2':
                                py_versions.extend(['3_2'])
                            elif entry == '3.3':
                                py_versions.extend(['3_3'])

                    if "License" in categories:
                        pkg_license = categories["License"][-1]
            pkg_license = self.convert([common_config, config], "licenses", pkg_license)

            if not py_versions:
                py_versions = ['2_6', '2_7', '3_2', '3_3']
            if len(py_versions) == 1:
                python_compat = 'python' + py_versions[0]
            else:
                python_compat = '( python{' + py_versions[0]
                for ver in py_versions[1:]:
                    python_compat += ',' + ver
                python_compat += '} )'

            filtered_package = "".join([x for x in package if ord(x) in allowed_ords_pkg])
            description = "".join([x for x in description if ord(x) in allowed_ords_desc])
            filtered_version = version
            match_object = re.match("(^[0-9]+[a-z]?$)|(^[0-9][0-9\.]+[0-9][a-z]?$)",
                                    filtered_version)
            if not match_object:
                filtered_version = pseudoversion

            dependencies = serializable_elist(separator="\n\t")
            eclasses = ['g-sorcery', 'gs-pypi']
            maintainer = [{'email' : 'piatlicki@gmail.com',
                           'name' : 'Jauhien Piatlicki'}]

            ebuild_data = {}
            ebuild_data["realname"] = package
            ebuild_data["realversion"] = version

            ebuild_data["description"] = description
            ebuild_data["longdescription"] = description
            ebuild_data["dependencies"] = dependencies
            ebuild_data["eclasses"] = eclasses
            ebuild_data["maintainer"] = maintainer

            ebuild_data["homepage"] = homepage
            ebuild_data["license"] = pkg_license
            ebuild_data["source_uri"] = source_uri
            ebuild_data["md5"] = md5
            ebuild_data["python_compat"] = python_compat

            ebuild_data["info"] = info

            pkg_db.add_package(Package(category, filtered_package, filtered_version), ebuild_data)