ยปCore Development>Code coverage>Lib/packaging/command/bdist_wininst.py

Python code coverage for Lib/packaging/command/bdist_wininst.py

#countcontent
1n/a"""Create an executable installer for Windows."""
2n/a
3n/aimport sys
4n/aimport os
5n/a
6n/afrom shutil import rmtree
7n/afrom sysconfig import get_python_version
8n/afrom packaging.command.cmd import Command
9n/afrom packaging.errors import PackagingOptionError, PackagingPlatformError
10n/afrom packaging import logger
11n/afrom packaging.util import get_platform
12n/a
13n/a
14n/aclass bdist_wininst(Command):
15n/a
16n/a description = "create an executable installer for Windows"
17n/a
18n/a user_options = [('bdist-dir=', None,
19n/a "temporary directory for creating the distribution"),
20n/a ('plat-name=', 'p',
21n/a "platform name to embed in generated filenames "
22n/a "(default: %s)" % get_platform()),
23n/a ('keep-temp', 'k',
24n/a "keep the pseudo-installation tree around after " +
25n/a "creating the distribution archive"),
26n/a ('target-version=', None,
27n/a "require a specific python version" +
28n/a " on the target system"),
29n/a ('no-target-compile', 'c',
30n/a "do not compile .py to .pyc on the target system"),
31n/a ('no-target-optimize', 'o',
32n/a "do not compile .py to .pyo (optimized)"
33n/a "on the target system"),
34n/a ('dist-dir=', 'd',
35n/a "directory to put final built distributions in"),
36n/a ('bitmap=', 'b',
37n/a "bitmap to use for the installer instead of python-powered logo"),
38n/a ('title=', 't',
39n/a "title to display on the installer background instead of default"),
40n/a ('skip-build', None,
41n/a "skip rebuilding everything (for testing/debugging)"),
42n/a ('install-script=', None,
43n/a "basename of installation script to be run after"
44n/a "installation or before deinstallation"),
45n/a ('pre-install-script=', None,
46n/a "Fully qualified filename of a script to be run before "
47n/a "any files are installed. This script need not be in the "
48n/a "distribution"),
49n/a ('user-access-control=', None,
50n/a "specify Vista's UAC handling - 'none'/default=no "
51n/a "handling, 'auto'=use UAC if target Python installed for "
52n/a "all users, 'force'=always use UAC"),
53n/a ]
54n/a
55n/a boolean_options = ['keep-temp', 'no-target-compile', 'no-target-optimize',
56n/a 'skip-build']
57n/a
58n/a def initialize_options(self):
59n/a self.bdist_dir = None
60n/a self.plat_name = None
61n/a self.keep_temp = False
62n/a self.no_target_compile = False
63n/a self.no_target_optimize = False
64n/a self.target_version = None
65n/a self.dist_dir = None
66n/a self.bitmap = None
67n/a self.title = None
68n/a self.skip_build = None
69n/a self.install_script = None
70n/a self.pre_install_script = None
71n/a self.user_access_control = None
72n/a
73n/a
74n/a def finalize_options(self):
75n/a self.set_undefined_options('bdist', 'skip_build')
76n/a
77n/a if self.bdist_dir is None:
78n/a if self.skip_build and self.plat_name:
79n/a # If build is skipped and plat_name is overridden, bdist will
80n/a # not see the correct 'plat_name' - so set that up manually.
81n/a bdist = self.distribution.get_command_obj('bdist')
82n/a bdist.plat_name = self.plat_name
83n/a # next the command will be initialized using that name
84n/a bdist_base = self.get_finalized_command('bdist').bdist_base
85n/a self.bdist_dir = os.path.join(bdist_base, 'wininst')
86n/a
87n/a if not self.target_version:
88n/a self.target_version = ""
89n/a
90n/a if not self.skip_build and self.distribution.has_ext_modules():
91n/a short_version = get_python_version()
92n/a if self.target_version and self.target_version != short_version:
93n/a raise PackagingOptionError("target version can only be %s, or the '--skip-build'" \
94n/a " option must be specified" % (short_version,))
95n/a self.target_version = short_version
96n/a
97n/a self.set_undefined_options('bdist', 'dist_dir', 'plat_name')
98n/a
99n/a if self.install_script:
100n/a for script in self.distribution.scripts:
101n/a if self.install_script == os.path.basename(script):
102n/a break
103n/a else:
104n/a raise PackagingOptionError("install_script '%s' not found in scripts" % \
105n/a self.install_script)
106n/a
107n/a def run(self):
108n/a if (sys.platform != "win32" and
109n/a (self.distribution.has_ext_modules() or
110n/a self.distribution.has_c_libraries())):
111n/a raise PackagingPlatformError \
112n/a ("distribution contains extensions and/or C libraries; "
113n/a "must be compiled on a Windows 32 platform")
114n/a
115n/a if not self.skip_build:
116n/a self.run_command('build')
117n/a
118n/a install = self.reinitialize_command('install', reinit_subcommands=True)
119n/a install.root = self.bdist_dir
120n/a install.skip_build = self.skip_build
121n/a install.warn_dir = False
122n/a install.plat_name = self.plat_name
123n/a
124n/a install_lib = self.reinitialize_command('install_lib')
125n/a # we do not want to include pyc or pyo files
126n/a install_lib.compile = False
127n/a install_lib.optimize = 0
128n/a
129n/a if self.distribution.has_ext_modules():
130n/a # If we are building an installer for a Python version other
131n/a # than the one we are currently running, then we need to ensure
132n/a # our build_lib reflects the other Python version rather than ours.
133n/a # Note that for target_version!=sys.version, we must have skipped the
134n/a # build step, so there is no issue with enforcing the build of this
135n/a # version.
136n/a target_version = self.target_version
137n/a if not target_version:
138n/a assert self.skip_build, "Should have already checked this"
139n/a target_version = '%s.%s' % sys.version_info[:2]
140n/a plat_specifier = ".%s-%s" % (self.plat_name, target_version)
141n/a build = self.get_finalized_command('build')
142n/a build.build_lib = os.path.join(build.build_base,
143n/a 'lib' + plat_specifier)
144n/a
145n/a # Use a custom scheme for the zip-file, because we have to decide
146n/a # at installation time which scheme to use.
147n/a for key in ('purelib', 'platlib', 'headers', 'scripts', 'data'):
148n/a value = key.upper()
149n/a if key == 'headers':
150n/a value = value + '/Include/$dist_name'
151n/a setattr(install,
152n/a 'install_' + key,
153n/a value)
154n/a
155n/a logger.info("installing to %s", self.bdist_dir)
156n/a install.ensure_finalized()
157n/a
158n/a # avoid warning of 'install_lib' about installing
159n/a # into a directory not in sys.path
160n/a sys.path.insert(0, os.path.join(self.bdist_dir, 'PURELIB'))
161n/a
162n/a install.run()
163n/a
164n/a del sys.path[0]
165n/a
166n/a # And make an archive relative to the root of the
167n/a # pseudo-installation tree.
168n/a from tempfile import NamedTemporaryFile
169n/a archive_basename = NamedTemporaryFile().name
170n/a fullname = self.distribution.get_fullname()
171n/a arcname = self.make_archive(archive_basename, "zip",
172n/a root_dir=self.bdist_dir)
173n/a # create an exe containing the zip-file
174n/a self.create_exe(arcname, fullname, self.bitmap)
175n/a if self.distribution.has_ext_modules():
176n/a pyversion = get_python_version()
177n/a else:
178n/a pyversion = 'any'
179n/a self.distribution.dist_files.append(('bdist_wininst', pyversion,
180n/a self.get_installer_filename(fullname)))
181n/a # remove the zip-file again
182n/a logger.debug("removing temporary file '%s'", arcname)
183n/a os.remove(arcname)
184n/a
185n/a if not self.keep_temp:
186n/a logger.info('removing %s', self.bdist_dir)
187n/a if not self.dry_run:
188n/a rmtree(self.bdist_dir)
189n/a
190n/a def get_inidata(self):
191n/a # Return data describing the installation.
192n/a
193n/a lines = []
194n/a metadata = self.distribution.metadata
195n/a
196n/a # Write the [metadata] section.
197n/a lines.append("[metadata]")
198n/a
199n/a # 'info' will be displayed in the installer's dialog box,
200n/a # describing the items to be installed.
201n/a info = (metadata.long_description or '') + '\n'
202n/a
203n/a # Escape newline characters
204n/a def escape(s):
205n/a return s.replace("\n", "\\n")
206n/a
207n/a for name in ["author", "author_email", "description", "maintainer",
208n/a "maintainer_email", "name", "url", "version"]:
209n/a data = getattr(metadata, name, "")
210n/a if data:
211n/a info = info + ("\n %s: %s" % \
212n/a (name.capitalize(), escape(data)))
213n/a lines.append("%s=%s" % (name, escape(data)))
214n/a
215n/a # The [setup] section contains entries controlling
216n/a # the installer runtime.
217n/a lines.append("\n[Setup]")
218n/a if self.install_script:
219n/a lines.append("install_script=%s" % self.install_script)
220n/a lines.append("info=%s" % escape(info))
221n/a lines.append("target_compile=%d" % (not self.no_target_compile))
222n/a lines.append("target_optimize=%d" % (not self.no_target_optimize))
223n/a if self.target_version:
224n/a lines.append("target_version=%s" % self.target_version)
225n/a if self.user_access_control:
226n/a lines.append("user_access_control=%s" % self.user_access_control)
227n/a
228n/a title = self.title or self.distribution.get_fullname()
229n/a lines.append("title=%s" % escape(title))
230n/a import time
231n/a import packaging
232n/a build_info = "Built %s with packaging-%s" % \
233n/a (time.ctime(time.time()), packaging.__version__)
234n/a lines.append("build_info=%s" % build_info)
235n/a return "\n".join(lines)
236n/a
237n/a def create_exe(self, arcname, fullname, bitmap=None):
238n/a import struct
239n/a
240n/a self.mkpath(self.dist_dir)
241n/a
242n/a cfgdata = self.get_inidata()
243n/a
244n/a installer_name = self.get_installer_filename(fullname)
245n/a logger.info("creating %s", installer_name)
246n/a
247n/a if bitmap:
248n/a with open(bitmap, "rb") as fp:
249n/a bitmapdata = fp.read()
250n/a bitmaplen = len(bitmapdata)
251n/a else:
252n/a bitmaplen = 0
253n/a
254n/a with open(installer_name, "wb") as file:
255n/a file.write(self.get_exe_bytes())
256n/a if bitmap:
257n/a file.write(bitmapdata)
258n/a
259n/a # Convert cfgdata from unicode to ascii, mbcs encoded
260n/a if isinstance(cfgdata, str):
261n/a cfgdata = cfgdata.encode("mbcs")
262n/a
263n/a # Append the pre-install script
264n/a cfgdata = cfgdata + b"\0"
265n/a if self.pre_install_script:
266n/a # We need to normalize newlines, so we open in text mode and
267n/a # convert back to bytes. "latin-1" simply avoids any possible
268n/a # failures.
269n/a with open(self.pre_install_script, encoding="latin-1") as fp:
270n/a script_data = fp.read().encode("latin-1")
271n/a cfgdata = cfgdata + script_data + b"\n\0"
272n/a else:
273n/a # empty pre-install script
274n/a cfgdata = cfgdata + b"\0"
275n/a file.write(cfgdata)
276n/a
277n/a # The 'magic number' 0x1234567B is used to make sure that the
278n/a # binary layout of 'cfgdata' is what the wininst.exe binary
279n/a # expects. If the layout changes, increment that number, make
280n/a # the corresponding changes to the wininst.exe sources, and
281n/a # recompile them.
282n/a header = struct.pack("<iii",
283n/a 0x1234567B, # tag
284n/a len(cfgdata), # length
285n/a bitmaplen, # number of bytes in bitmap
286n/a )
287n/a file.write(header)
288n/a with open(arcname, "rb") as fp:
289n/a file.write(fp.read())
290n/a
291n/a def get_installer_filename(self, fullname):
292n/a # Factored out to allow overriding in subclasses
293n/a if self.target_version:
294n/a # if we create an installer for a specific python version,
295n/a # it's better to include this in the name
296n/a installer_name = os.path.join(self.dist_dir,
297n/a "%s.%s-py%s.exe" %
298n/a (fullname, self.plat_name, self.target_version))
299n/a else:
300n/a installer_name = os.path.join(self.dist_dir,
301n/a "%s.%s.exe" % (fullname, self.plat_name))
302n/a return installer_name
303n/a
304n/a def get_exe_bytes(self):
305n/a from packaging.compiler.msvccompiler import get_build_version
306n/a # If a target-version other than the current version has been
307n/a # specified, then using the MSVC version from *this* build is no good.
308n/a # Without actually finding and executing the target version and parsing
309n/a # its sys.version, we just hard-code our knowledge of old versions.
310n/a # NOTE: Possible alternative is to allow "--target-version" to
311n/a # specify a Python executable rather than a simple version string.
312n/a # We can then execute this program to obtain any info we need, such
313n/a # as the real sys.version string for the build.
314n/a cur_version = get_python_version()
315n/a if self.target_version and self.target_version != cur_version:
316n/a # If the target version is *later* than us, then we assume they
317n/a # use what we use
318n/a # string compares seem wrong, but are what sysconfig.py itself uses
319n/a if self.target_version > cur_version:
320n/a bv = get_build_version()
321n/a else:
322n/a if self.target_version < "2.4":
323n/a bv = 6.0
324n/a else:
325n/a bv = 7.1
326n/a else:
327n/a # for current version - use authoritative check.
328n/a bv = get_build_version()
329n/a
330n/a # wininst-x.y.exe is in the same directory as this file
331n/a directory = os.path.dirname(__file__)
332n/a # we must use a wininst-x.y.exe built with the same C compiler
333n/a # used for python. XXX What about mingw, borland, and so on?
334n/a
335n/a # if plat_name starts with "win" but is not "win32"
336n/a # we want to strip "win" and leave the rest (e.g. -amd64)
337n/a # for all other cases, we don't want any suffix
338n/a if self.plat_name != 'win32' and self.plat_name[:3] == 'win':
339n/a sfix = self.plat_name[3:]
340n/a else:
341n/a sfix = ''
342n/a
343n/a filename = os.path.join(directory, "wininst-%.1f%s.exe" % (bv, sfix))
344n/a with open(filename, "rb") as fp:
345n/a return fp.read()