summaryrefslogtreecommitdiff
path: root/apkkit/base/package.py
blob: 109cf04dfef410935b27467f190f1a8010496d94 (plain) (blame)
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
"""Contains the Package class and related helper classes and functions."""

from jinja2 import Template
import logging
import os
import time


PACKAGE_LOGGER = logging.getLogger(__name__)


PKGINFO_TEMPLATE = Template("""
# Generated by APK Kit for Adélie Linux
# {{ builduser }}@{{ buildhost }} {{ self.builddate }}
pkgname = {{ package.name }}
pkgver = {{ package.version }}
pkgdesc = {{ package.description }}
arch = {{ package.arch }}
size = {{ package.size }}
{%- if package.license %}
license = {{ package.license }}
{%- endif %}
{%- if package.url %}
url = {{ package.url }}
{%- endif %}
{%- if package.origin %}
origin = {{ package.origin }}
{%- endif %}
{%- if package.provides %}{%- for provided in package.provides %}
provides = {{ provided }}
{%- endfor %}{%- endif %}
{%- if package.depends %}{%- for depend in package.depends %}
depend = {{ depend }}
{%- endfor %}{%- endif %}
{%- if package.replaces %}{%- for replace in package.replaces %}
replaces = {{ replace }}
{%- endfor %}{%- endif %}
{%- if package.install_if %}{%- for iif in package.install_if %}
install_if = {{ iif }}
{%- endfor %}{%- endif %}
builddate = {{ builddate }}
{%- if package.commit %}
commit = {{ package.commit }}
{%- endif %}
{%- if package.data_hash %}
datahash = {{ package.data_hash }}
{%- endif %}
{%- if package.maintainer %}
maintainer = {{ package.maintainer }}
{%- endif %}

""")
"""The template used for generating .PKGINFO"""


class Package:
    """The base package class."""

    def __init__(self, name, version, arch, description=None, url=None, size=0,
                 provides=None, depends=None, license=None, origin=None,
                 replaces=None, commit=None, maintainer=None, builddate=0,
                 install_if=None, **kwargs):
        """Initialise a package object.

        :param str name:
            The name of the package.

        :param str version:
            The version of the package.

        :param str arch:
            The architecture of the package.

        :param str description:
            (Recommended) The description of the package.  Defaults to the name
            if not set.

        :param int size:
            (Recommended) The installed size of the package.  You almost always
            want to set this to something other than 0 if you don't want
            unhappy users. :)

        :param str url:
            (Optional) The URL of the homepage for the package.

        :param list provides:
            (Optional) One or more virtuals that this package provides.

        :param list depends:
            (Optional) One or more packages that are required to be installed
            to use this package.

        :param str license:
            (Recommended) The license this package is under.

        :param str origin:
            (Optional) The origin package, if this package is a subpackage.
            Defaults to `name`.

        :param list replaces:
            (Optional) One or more packages that this package replaces.

        :param str commit:
            (Recommended) The hash of the git commit the repository was on when
            this package was built.

        :param str maintainer:
            (Recommended) The maintainer of the package.

        :param int builddate:
            (Optional) The date the package was built, in UNIX timestamp.
            Defaults to right now.

        :param list install_if:
            (Optional) Read the APKBUILD.5 manpage.
        """

        self._pkgname = name
        self._pkgver = str(version)
        self._pkgdesc = description or name
        self._url = url
        self._size = int(size)
        self._arch = arch
        self._provides = provides or list()
        self._depends = depends or list()
        self._replaces = replaces or list()
        self._iif = install_if or list()
        self._license = license
        self._origin = origin or name
        self._commit = commit
        self._maintainer = maintainer
        self._builddate = builddate or time.time()

        if '_datahash' in kwargs:
            self._datahash = kwargs.pop('_datahash')

        if len(kwargs) > 0:
            PACKAGE_LOGGER.warning("unknown kwargs in Package: %r", kwargs)

    @property
    def name(self):
        """The name of the package."""
        return self._pkgname

    @property
    def version(self):
        """The version of the package."""
        return self._pkgver

    @property
    def description(self):
        """The description of the package."""
        return self._pkgdesc

    @property
    def url(self):
        """The URL of the homepage of the package."""
        return self._url

    @property
    def size(self):
        """The installed size of the package in bytes."""
        return self._size

    @size.setter
    def size(self, new_size):
        """Change the installed size of the package in bytes.

        .. warning: Internal use only!

        :param int new_size:
            The new installed size of the package.
        """
        self._size = new_size

    @property
    def arch(self):
        """The architecture of the package."""
        return self._arch

    @property
    def provides(self):
        """The libraries and/or virtuals provided by this package."""
        return self._provides

    @property
    def depends(self):
        """The dependencies of the package."""
        return self._depends

    @property
    def replaces(self):
        """The packages this package replaces."""
        return self._replaces

    @property
    def install_if(self):
        """The packages that pull in this package."""
        return self._iif

    @property
    def license(self):
        """The license of the package."""
        return self._license

    @property
    def origin(self):
        """The origin package of this package."""
        return self._origin

    @property
    def commit(self):
        """The hash of the git commit the build repository was on."""
        return self._commit

    @property
    def maintainer(self):
        """The maintainer of the package."""
        return self._maintainer

    @property
    def data_hash(self):
        """The hash of the package's data, or None if not available."""
        return getattr(self, '_datahash', None)

    @data_hash.setter
    def data_hash(self, hash_):
        """Set the hash of the package's data."""
        self._datahash = hash_

    def __repr__(self):
        return 'Package(name="{name}", version="{ver}", arch="{arch}", '\
               'description="{desc}", url="{url}", size={size}, '\
               'provides={prov}, depends={dep}, license={lic}, '\
               'origin="{origin}", replaces={rep}, commit="{git}", '\
               'maintainer="{m}", builddate={ts}, install_if={iif})'.format(
                   name=self._pkgname, ver=self._pkgver, arch=self._arch,
                   desc=self._pkgdesc, prov=self._provides, dep=self._depends,
                   url=self._url, size=self._size, lic=self._license,
                   origin=self._origin, rep=self._replaces, git=self._commit,
                   m=self._maintainer, ts=self._builddate, iif=self._iif)

    def to_pkginfo(self):
        """Serialises the package's information into the PKGINFO format.

        :returns str: The PKGINFO for this package.  Unicode str, ready to be
                      written to a file.

        .. note:: To write a file, see the :py:meth:`.write_pkginfo` helper
                  method.
        """
        return PKGINFO_TEMPLATE.render(builduser=os.getenv('USER', '?'),
                                       buildhost=os.uname().nodename,
                                       package=self)

    @classmethod
    def from_pkginfo(cls, buf):
        """Create a new :py:class:`Package` object from an existing PKGINFO.

        :param buf:
            The buffer to read from (whether file, StringIO, etc).

        :returns:
            A :py:class:`Package` object with the details from the PKGINFO.

        :throws ValueError:
            If a required field is missing from the PKGINFO.
        """

        params = {}
        param_map = {'pkgname': 'name', 'pkgver': 'version', 'arch': 'arch',
                     'pkgdesc': 'description', 'provides': 'provides',
                     'depend': 'depends', 'url': 'url', 'size': 'size',
                     'replaces': 'replaces', 'builddate': 'builddate',
                     'license': 'license', 'datahash': '_datahash',
                     'maintainer': 'maintainer', 'commit': 'commit',
                     'install_if': 'install_if'}
        list_keys = {'provides', 'depend', 'replaces', 'install_if'}

        params['provides'] = list()
        params['depends'] = list()
        params['replaces'] = list()

        for line in buf.readlines():
            if not isinstance(line, str):
                line = line.decode('utf-8')

            # Skip comments.
            if len(line) == 0 or line[0] == '#':
                continue

            if line.find('=') == -1:
                PACKAGE_LOGGER.warning('!!! malformed line? "%s" !!!', line)
                continue

            (key, value) = line.split('=', 1)
            key = key.strip()
            value = value.strip()

            if key in param_map:
                if key in list_keys:
                    params[param_map[key]].append(value)
                else:
                    params[param_map[key]] = value
            else:
                PACKAGE_LOGGER.info('!!! unrecognised PKGINFO key %s !!!', key)

        return cls(**params)