File: bdist_solaris.py

package info (click to toggle)
mysql-connector-python 9.4.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 27,768 kB
  • sloc: python: 83,598; sql: 47,030; ansic: 3,494; cpp: 860; sh: 394; makefile: 208; javascript: 2
file content (378 lines) | stat: -rw-r--r-- 13,988 bytes parent folder | download | duplicates (2)
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
# Copyright (c) 2019, 2024, Oracle and/or its affiliates.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, version 2.0, as
# published by the Free Software Foundation.
#
# This program is designed to work with certain software (including
# but not limited to OpenSSL) that is licensed under separate terms,
# as designated in a particular file or component or in included license
# documentation. The authors of MySQL hereby grant you an
# additional permission to link the program and your derivative works
# with the separately licensed software that they have either included with
# the program or referenced in the documentation.
#
# Without limiting anything contained in the foregoing, this file,
# which is part of MySQL Connector/Python, is also subject to the
# Universal FOSS Exception, version 1.0, a copy of which can be found at
# http://oss.oracle.com/licenses/universal-foss-exception.
#
# 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, version 2.0, for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA

"""Implements the Distutils command for creating Solaris packages."""


import logging
import os
import platform
import shutil
import subprocess
import tarfile
import time

from pathlib import Path

try:
    from setuptools.errors import ExecError
except ImportError:
    ExecError = Exception

try:
    from setuptools.logging import set_threshold
except ImportError:
    set_threshold = None

from . import COMMON_USER_OPTIONS, VERSION_EXTRA, VERSION_TEXT, BaseCommand
from .bdist import DistBinary as bdist
from .utils import write_info_bin, write_info_src

SOLARIS_PKGS = {"pure": os.path.join("cpydist", "data", "solaris")}
PKGINFO = (
    'PKG="{pkg}"\n'
    'NAME="MySQL Connector/Python {ver} {lic}, MySQL driver written in '
    'Python"\n'
    'VERSION="{ver}"\n'
    'ARCH="all"\n'
    'CLASSES="none"\n'
    'CATEGORY="application"\n'
    'VENDOR="ORACLE Corporation"\n'
    'PSTAMP="{tstamp}"\n'
    'EMAIL="MySQL Release Engineering <mysql-build@oss.oracle.com>"\n'
    'BASEDIR="/"\n'
)


class DistSolaris(bdist, BaseCommand):
    """Create a Solaris distribution."""

    platf_n = "-solaris"
    platf_v = platform.version().split(".")[0]
    platf_a = "sparc" if platform.processor() == "sparc" else "x86"
    description = "create a Solaris distribution"
    user_options = COMMON_USER_OPTIONS + [
        ("dist-dir=", "d", "directory to put final built distributions in"),
        (
            "platform=",
            "p",
            f"name of the platform in resulting file (default '{platf_n}')",
        ),
        (
            "platform-version=",
            "v",
            f"version of the platform in resulting file (default '{platf_v}')",
        ),
        (
            "platform-version=",
            "a",
            "architecture, i.e. 'sparc' or 'x86' in the resulting file "
            f"(default '{platf_a}')",
        ),
        (
            "trans",
            "t",
            "transform the package into data stream (default 'False')",
        ),
    ]

    def initialize_options(self):
        """Initialize the options."""
        bdist.initialize_options(self)
        BaseCommand.initialize_options(self)
        self.name = self.distribution.get_name()
        self.version = self.distribution.get_version()
        self.version_extra = f"-{VERSION_EXTRA}" if VERSION_EXTRA else ""
        self.keep_temp = None
        self.create_dmg = False
        self.dist_dir = None
        self.started_dir = os.getcwd()
        self.platform = self.platf_n
        self.platform_version = self.platf_v
        self.architecture = self.platf_a
        self.debug = False
        self.sun_pkg_name = f"{self.name}-{self.version}{self.version_extra}.pkg"
        self.dstroot = "dstroot"
        self.sign = False
        self.identity = "MySQL Connector/Python"
        self.trans = False

    def finalize_options(self):
        """Finalize the options."""
        bdist.finalize_options(self)
        BaseCommand.finalize_options(self)
        self.set_undefined_options("bdist", ("dist_dir", "dist_dir"))
        if self.debug:
            self.log.setLevel(logging.DEBUG)
            if set_threshold:
                # Set setuptools logging level to DEBUG
                set_threshold(1)

    def _prepare_pkg_base(self, template_name, data_dir, root=""):
        """Create and populate the src base directory."""
        self.log.info("-> _prepare_pkg_base()")
        self.log.info("  template_name: %s", template_name)
        self.log.info("  data_dir: %s", data_dir)
        self.log.info("  root: %s", root)

        # copy and create necessary files
        sun_dist_name = template_name.format(self.name, self.version)
        self.sun_pkg_name = f"{sun_dist_name}.pkg"
        self.log.info("  sun_pkg_name: %s", self.sun_pkg_name)

        sun_path = os.path.join(root, self.dstroot)
        self.log.info("  sun_path: %s", sun_path)
        cwd = os.path.join(os.getcwd())
        self.log.info("Current directory: %s", cwd)

        copy_file_src_dst = []

        # No special folder for GPL or commercial. Files inside the directory
        # will determine what it is.
        data_path = os.path.join(
            sun_path,
            "usr",
            "share",
            template_name.format(self.name, self.version),
        )
        self.mkpath(data_path)

        lic = "(GPL)"
        sun_pkg_info = os.path.join(sun_path, "pkginfo")
        self.log.info("sun_pkg_info path: %s", sun_pkg_info)
        with open(sun_pkg_info, "w") as f_pkg_info:
            f_pkg_info.write(
                PKGINFO.format(
                    ver=self.version,
                    lic=lic,
                    pkg=self.name,
                    tstamp=time.ctime(),
                )
            )
            f_pkg_info.close()

        data_path = os.path.join(
            sun_path,
            "usr",
            "share",
            template_name.format(self.name, self.version),
        )
        copy_file_src_dst += [
            (
                os.path.join(cwd, "README.txt"),
                os.path.join(data_path, "README.txt"),
            ),
            (
                os.path.join(cwd, "LICENSE.txt"),
                os.path.join(data_path, "LICENSE.txt"),
            ),
            (
                os.path.join(cwd, "CHANGES.txt"),
                os.path.join(data_path, "CHANGES.txt"),
            ),
            (
                os.path.join(cwd, "docs", "INFO_SRC"),
                os.path.join(data_path, "INFO_SRC"),
            ),
            (
                os.path.join(cwd, "docs", "INFO_BIN"),
                os.path.join(data_path, "INFO_BIN"),
            ),
            (
                os.path.join(cwd, "README.rst"),
                os.path.join(data_path, "README.rst"),
            ),
            (
                os.path.join(cwd, "CONTRIBUTING.md"),
                os.path.join(data_path, "CONTRIBUTING.md"),
            ),
            (
                os.path.join(cwd, "SECURITY.md"),
                os.path.join(data_path, "SECURITY.md"),
            ),
        ]

        for src, dst in copy_file_src_dst:
            shutil.copyfile(src, dst)

    def _create_pkg(self, template_name, dmg=False, sign=False, root="", identity=""):
        """Create the Solaris package using the OS dependent commands."""
        self.log.info("-> _create_pkg()")
        self.log.info("template_name: %s", template_name)
        self.log.info("identity: %s", identity)

        sun_dist_name = template_name.format(self.name, self.version)
        self.sun_pkg_name = f"{sun_dist_name}.pkg"
        sun_pkg_contents = os.path.join(self.sun_pkg_name, "Contents")

        self.log.info("sun_dist_name: %s", sun_dist_name)
        self.log.info("sun_pkg_name: %s", self.sun_pkg_name)
        self.log.info("sun_pkg_contents: %s", sun_pkg_contents)

        sun_path = os.path.join(root, self.dstroot)
        os.chdir(sun_path)
        self.log.info("Root directory for Prototype: %s", os.getcwd())

        # Creating a Prototype file, this contains a table of contents of the
        # Package, that is suitable to be used for the package creation tool.
        self.log.info(
            f"Creating Prototype file on {self.dstroot} to describe files to install"
        )

        prototype_path = "Prototype"
        proto_tmp = "Prototype_temp"

        with open(proto_tmp, "w") as f_out:
            cmd = ["pkgproto", "."]
            pkgp_p = subprocess.Popen(cmd, shell=False, stdout=f_out, stderr=f_out)
            res = pkgp_p.wait()
            if res != 0:
                self.log.error(f"pkgproto command failed with: {res}")
                raise ExecError(f"pkgproto command failed with: {res}")
            f_out.flush()

        # log Prototype contents
        self.log.info("/n>> Prototype_temp contents >>/n")
        with open(proto_tmp, "r") as f_in:
            self.log.info(f_in.readlines())
        self.log.info("/n<< Prototype_temp contents end <</n")

        # Fix Prototype file, insert pkginfo and remove Prototype
        self.log.info("Fixing folder permissions on Prototype contents")
        with open(prototype_path, "w") as f_out:
            with open(proto_tmp, "r") as f_in:
                # Add pkginfo entry at beginning of the Prototype file
                f_out.write("i pkginfo\n")
                f_out.flush()
                for line in f_in:
                    if line.startswith("f none Prototype"):
                        continue
                    elif line.startswith("f none pkginfo"):
                        continue
                    elif line.startswith("d"):
                        tokeep = line.split(" ")[:-3]
                        tokeep.extend(["?", "?", "?", "\n"])
                        f_out.write(" ".join(tokeep))
                    elif line.startswith("f"):
                        tokeep = line.split(" ")[:-2]
                        tokeep.extend(["root", "bin", "\n"])
                        f_out.write(" ".join(tokeep))
                    else:
                        f_out.write(line)
                f_out.flush()

        # log Prototype contents
        self.log.info("/n>> Prototype contents >>/n")
        with open(prototype_path, "r") as f_in:
            self.log.info(f_in.readlines())
        self.log.info("/n<< Prototype contents end <</n")

        # Create Solaris package running the package creation command pkgmk
        self.log.info("Creating package with pkgmk")

        self.log.info("Root directory for pkgmk: %s", os.getcwd())
        self.spawn(["pkgmk", "-o", "-r", ".", "-d", "../", "-f", prototype_path])
        os.chdir("../")
        if self.debug:
            self.log.info("current directory: %s", os.getcwd())

        # gzip the package folder
        self.log.info("creating tarball")

        archive_name = f"{self.sun_pkg_name}.tar.gz"
        self.log.info("Creating tar archive '%s'", archive_name)
        with tarfile.open(archive_name, "w|gz") as tar:
            tar.add(self.name)

        if self.trans:
            self.log.info("Transforming package into data stream with pkgtrans")
            self.log.info("Current directory: %s", os.getcwd())
            self.spawn(
                [
                    "pkgtrans",
                    "-s",
                    os.getcwd(),
                    os.path.join(os.getcwd(), self.sun_pkg_name),
                    self.name,
                ]
            )

        for base, _, files in os.walk(os.getcwd()):
            for filename in files:
                if filename.endswith(".gz") or filename.endswith(".pkg"):
                    new_name = filename.replace(
                        f"{self.version}",
                        f"{self.version}{self.version_extra}{self.platform}"
                        f"{self.platform_version}-{self.architecture}",
                    )
                    file_path = os.path.join(base, filename)
                    file_dest = os.path.join(self.started_dir, self.dist_dir, new_name)
                    shutil.copyfile(file_path, file_dest)
            break

    def run(self):
        """Run the command."""
        self.mkpath(self.dist_dir)
        self.debug = self.verbose

        self.log.info("Generating INFO_SRC and INFO_BIN files")
        write_info_src(VERSION_TEXT)
        write_info_bin()

        cmd_build = self.get_finalized_command("build")
        build_base = os.path.abspath(cmd_build.build_base)
        metadata_name = self.distribution.metadata.name

        data_dir = SOLARIS_PKGS["pure"]
        sun_root = os.path.join(build_base, "sun_pure")
        cmd_install = self.reinitialize_command("install", reinit_subcommands=1)
        cmd_install.byte_code_only = self.byte_code_only
        cmd_install.compile = self.byte_code_only
        cmd_install.distribution.metadata.name = metadata_name
        cmd_install.with_mysql_capi = None
        cmd_install.root = os.path.join(sun_root, self.dstroot)
        cmd_install.ensure_finalized()
        cmd_install.run()

        template_name = ["{}"]
        if self.label:
            template_name.append(f"-{self.label}")
        template_name.append("-{}")

        self._prepare_pkg_base("".join(template_name), data_dir, root=sun_root)
        self._create_pkg(
            "".join(template_name),
            dmg=self.create_dmg,
            root=sun_root,
            sign=self.sign,
            identity=self.identity,
        )

        os.chdir(self.started_dir)

        self.remove_temp()