pmpkg.py 7.63 KB
Newer Older
1
#  Copyright (c) 2006 by Aurelien Foret <orelien@chez.com>
Allan McRae's avatar
Allan McRae committed
2
#  Copyright (c) 2006-2022 Pacman Development Team <pacman-dev@lists.archlinux.org>
3
#
4
5
6
7
8
9
10
11
12
13
14
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
15
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.
16

Dave Reisner's avatar
Dave Reisner committed
17
from io import BytesIO
18
import os
Chantry Xavier's avatar
Chantry Xavier committed
19
import tarfile
20

Dan McGee's avatar
Dan McGee committed
21
import util
22

23
class pmpkg(object):
24
    """Package object.
25

Dan McGee's avatar
Dan McGee committed
26
    Object holding data from an Arch Linux package.
27
28
29
    """

    def __init__(self, name, version = "1.0-1"):
30
        self.path = "" #the path of the generated package
31
32
33
34
35
36
37
38
39
40
41
42
43
        # desc
        self.name = name
        self.version = version
        self.desc = ""
        self.groups = []
        self.url = ""
        self.license = []
        self.arch = ""
        self.builddate = ""
        self.installdate = ""
        self.packager = ""
        self.size = 0
        self.csize = 0
44
        self.isize = 0
45
46
        self.reason = 0
        self.md5sum = ""      # sync only
47
        self.pgpsig = ""      # sync only
Dan McGee's avatar
Dan McGee committed
48
        self.replaces = []
49
        self.depends = []
50
        self.optdepends = []
51
52
53
54
55
56
57
58
59
60
61
62
        self.conflicts = []
        self.provides = []
        # files
        self.files = []
        self.backup = []
        # install
        self.install = {
            "pre_install": "",
            "post_install": "",
            "pre_remove": "",
            "post_remove": "",
            "pre_upgrade": "",
63
            "post_upgrade": "",
64
        }
Dan McGee's avatar
Dan McGee committed
65
        self.path = None
66
        self.finalized = False
67
68
69
70
71
72
73
74
75
76
77

    def __str__(self):
        s = ["%s" % self.fullname()]
        s.append("description: %s" % self.desc)
        s.append("url: %s" % self.url)
        s.append("files: %s" % " ".join(self.files))
        s.append("reason: %d" % self.reason)
        return "\n".join(s)

    def fullname(self):
        """Long name of a package.
78

79
80
81
82
83
84
        Returns a string formatted as follows: "pkgname-pkgver".
        """
        return "%s-%s" % (self.name, self.version)

    def filename(self):
        """File name of a package, including its extension.
85

86
87
        Returns a string formatted as follows: "pkgname-pkgver.PKG_EXT_PKG".
        """
Dan McGee's avatar
Dan McGee committed
88
        return "%s%s" % (self.fullname(), util.PM_EXT_PKG)
89

90
91
92
93
94
95
96
97
98
99
100
    @staticmethod
    def parse_filename(name):
        filename = name
        if filename[-1] == "*":
            filename = filename.rstrip("*")
        if filename.find(" -> ") != -1:
            filename, extra = filename.split(" -> ")
        elif filename.find("|") != -1:
            filename, extra = filename.split("|")
        return filename

Andrew Gregory's avatar
Andrew Gregory committed
101
102
103
104
105
106
    def makepkg_bytes(self):
        buf = BytesIO();
        self.makepkg(fileobj=buf)
        return buf.getvalue()

    def makepkg(self, path=None, fileobj=None):
Dan McGee's avatar
Dan McGee committed
107
        """Creates an Arch Linux package archive.
108

109
110
111
        A package archive is generated in the location 'path', based on the data
        from the object.
        """
Dan McGee's avatar
Dan McGee committed
112
        archive_files = []
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131

        # .PKGINFO
        data = ["pkgname = %s" % self.name]
        data.append("pkgver = %s" % self.version)
        data.append("pkgdesc = %s" % self.desc)
        data.append("url = %s" % self.url)
        data.append("builddate = %s" % self.builddate)
        data.append("packager = %s" % self.packager)
        data.append("size = %s" % self.size)
        if self.arch:
            data.append("arch = %s" % self.arch)
        for i in self.license:
            data.append("license = %s" % i)
        for i in self.replaces:
            data.append("replaces = %s" % i)
        for i in self.groups:
            data.append("group = %s" % i)
        for i in self.depends:
            data.append("depend = %s" % i)
132
133
        for i in self.optdepends:
            data.append("optdepend = %s" % i)
134
135
136
137
138
139
        for i in self.conflicts:
            data.append("conflict = %s" % i)
        for i in self.provides:
            data.append("provides = %s" % i)
        for i in self.backup:
            data.append("backup = %s" % i)
Dan McGee's avatar
Dan McGee committed
140
        archive_files.append((".PKGINFO", "\n".join(data)))
141
142

        # .INSTALL
143
        if any(self.install.values()):
Dan McGee's avatar
Dan McGee committed
144
            archive_files.append((".INSTALL", self.installfile()))
145

Andrew Gregory's avatar
Andrew Gregory committed
146
147
148
        if path:
            self.path = os.path.join(path, self.filename())
            util.mkdir(os.path.dirname(self.path))
149

Dan McGee's avatar
Dan McGee committed
150
        # Generate package metadata
Andrew Gregory's avatar
Andrew Gregory committed
151
        tar = tarfile.open(name=self.path, fileobj=fileobj, mode="w:gz", format=tarfile.GNU_FORMAT)
Dan McGee's avatar
Dan McGee committed
152
153
154
        for name, data in archive_files:
            info = tarfile.TarInfo(name)
            info.size = len(data)
Dave Reisner's avatar
Dave Reisner committed
155
            tar.addfile(info, BytesIO(data.encode('utf8')))
Dan McGee's avatar
Dan McGee committed
156
157
158
159
160
161
162

        # Generate package file system
        for name in self.files:
            fileinfo = util.getfileinfo(name)
            info = tarfile.TarInfo(fileinfo["filename"])
            if fileinfo["hasperms"]:
                info.mode = fileinfo["perms"]
163
            elif fileinfo["isdir"]:
164
                info.mode = 0o755
Dan McGee's avatar
Dan McGee committed
165
166
167
168
169
170
171
172
173
174
175
            if fileinfo["isdir"]:
                info.type = tarfile.DIRTYPE
                tar.addfile(info)
            elif fileinfo["islink"]:
                info.type = tarfile.SYMTYPE
                info.linkname = fileinfo["link"]
                tar.addfile(info)
            else:
                # TODO wow what a hack, adding a newline to match mkfile?
                filedata = name + "\n"
                info.size = len(filedata)
Dave Reisner's avatar
Dave Reisner committed
176
                tar.addfile(info, BytesIO(filedata.encode('utf8')))
Dan McGee's avatar
Dan McGee committed
177

Chantry Xavier's avatar
Chantry Xavier committed
178
        tar.close()
179

Dan McGee's avatar
Dan McGee committed
180
181
182
    def install_package(self, root):
        """Install the package in the given root."""
        for f in self.files:
183
            path = util.mkfile(root, f, f)
Dan McGee's avatar
Dan McGee committed
184
185
            if os.path.isfile(path):
                os.utime(path, (355, 355))
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
    def filelist(self):
        """Generate a list of package files."""
        return sorted([self.parse_filename(f) for f in self.files])

    def finalize(self):
        """Perform any necessary operations to ready the package for use."""
        if self.finalized:
            return

        # add missing parent dirs to file list
        # use bare file names so trailing ' -> ', '*', etc don't throw off the
        # checks for existing files
        file_names = self.filelist()
        for name in list(file_names):
            if os.path.isabs(name):
                raise ValueError("Absolute path in filelist '%s'." % name)

            name = os.path.dirname(name.rstrip("/"))
            while name:
                if name in file_names:
                    # path exists as both a file and a directory
                    raise ValueError("Duplicate path in filelist '%s'." % name)
                elif name + "/" in file_names:
                    # path was either manually included or already processed
                    break
                else:
                    file_names.append(name + "/")
                    self.files.append(name + "/")
                name = os.path.dirname(name)
        self.files.sort()

        self.finalized = True
219
220
221
222

    def local_backup_entries(self):
        return ["%s\t%s" % (self.parse_filename(i), util.mkmd5sum(i)) for i in self.backup]

223
224
    def installfile(self):
        data = []
225
        for key, value in self.install.items():
226
            if value:
227
                data.append("%s() {\n%s\n}\n" % (key, value))
228
229

        return "\n".join(data)