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

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

#countcontent
1n/a"""distutils.command.bdist_wininst
2n/a
3n/aImplements the Distutils 'bdist_wininst' command: create a windows installer
4n/aexe-program."""
5n/a
6n/aimport sys, os
7n/afrom distutils.core import Command
8n/afrom distutils.util import get_platform
9n/afrom distutils.dir_util import create_tree, remove_tree
10n/afrom distutils.errors import *
11n/afrom distutils.sysconfig import get_python_version
12n/afrom distutils import log
13n/a
14n/aclass bdist_wininst(Command):
15n/a
16n/a description = "create an executable installer for MS 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 = 0
62n/a self.no_target_compile = 0
63n/a self.no_target_optimize = 0
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', '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 DistutilsOptionError(
94n/a "target version can only be %s, or the '--skip-build'" \
95n/a " option must be specified" % (short_version,))
96n/a self.target_version = short_version
97n/a
98n/a self.set_undefined_options('bdist',
99n/a ('dist_dir', 'dist_dir'),
100n/a ('plat_name', 'plat_name'),
101n/a )
102n/a
103n/a if self.install_script:
104n/a for script in self.distribution.scripts:
105n/a if self.install_script == os.path.basename(script):
106n/a break
107n/a else:
108n/a raise DistutilsOptionError(
109n/a "install_script '%s' not found in scripts"
110n/a % self.install_script)
111n/a
112n/a def run(self):
113n/a if (sys.platform != "win32" and
114n/a (self.distribution.has_ext_modules() or
115n/a self.distribution.has_c_libraries())):
116n/a raise DistutilsPlatformError \
117n/a ("distribution contains extensions and/or C libraries; "
118n/a "must be compiled on a Windows 32 platform")
119n/a
120n/a if not self.skip_build:
121n/a self.run_command('build')
122n/a
123n/a install = self.reinitialize_command('install', reinit_subcommands=1)
124n/a install.root = self.bdist_dir
125n/a install.skip_build = self.skip_build
126n/a install.warn_dir = 0
127n/a install.plat_name = self.plat_name
128n/a
129n/a install_lib = self.reinitialize_command('install_lib')
130n/a # we do not want to include pyc or pyo files
131n/a install_lib.compile = 0
132n/a install_lib.optimize = 0
133n/a
134n/a if self.distribution.has_ext_modules():
135n/a # If we are building an installer for a Python version other
136n/a # than the one we are currently running, then we need to ensure
137n/a # our build_lib reflects the other Python version rather than ours.
138n/a # Note that for target_version!=sys.version, we must have skipped the
139n/a # build step, so there is no issue with enforcing the build of this
140n/a # version.
141n/a target_version = self.target_version
142n/a if not target_version:
143n/a assert self.skip_build, "Should have already checked this"
144n/a target_version = '%d.%d' % sys.version_info[:2]
145n/a plat_specifier = ".%s-%s" % (self.plat_name, target_version)
146n/a build = self.get_finalized_command('build')
147n/a build.build_lib = os.path.join(build.build_base,
148n/a 'lib' + plat_specifier)
149n/a
150n/a # Use a custom scheme for the zip-file, because we have to decide
151n/a # at installation time which scheme to use.
152n/a for key in ('purelib', 'platlib', 'headers', 'scripts', 'data'):
153n/a value = key.upper()
154n/a if key == 'headers':
155n/a value = value + '/Include/$dist_name'
156n/a setattr(install,
157n/a 'install_' + key,
158n/a value)
159n/a
160n/a log.info("installing to %s", self.bdist_dir)
161n/a install.ensure_finalized()
162n/a
163n/a # avoid warning of 'install_lib' about installing
164n/a # into a directory not in sys.path
165n/a sys.path.insert(0, os.path.join(self.bdist_dir, 'PURELIB'))
166n/a
167n/a install.run()
168n/a
169n/a del sys.path[0]
170n/a
171n/a # And make an archive relative to the root of the
172n/a # pseudo-installation tree.
173n/a from tempfile import mktemp
174n/a archive_basename = mktemp()
175n/a fullname = self.distribution.get_fullname()
176n/a arcname = self.make_archive(archive_basename, "zip",
177n/a root_dir=self.bdist_dir)
178n/a # create an exe containing the zip-file
179n/a self.create_exe(arcname, fullname, self.bitmap)
180n/a if self.distribution.has_ext_modules():
181n/a pyversion = get_python_version()
182n/a else:
183n/a pyversion = 'any'
184n/a self.distribution.dist_files.append(('bdist_wininst', pyversion,
185n/a self.get_installer_filename(fullname)))
186n/a # remove the zip-file again
187n/a log.debug("removing temporary file '%s'", arcname)
188n/a os.remove(arcname)
189n/a
190n/a if not self.keep_temp:
191n/a remove_tree(self.bdist_dir, dry_run=self.dry_run)
192n/a
193n/a def get_inidata(self):
194n/a # Return data describing the installation.
195n/a lines = []
196n/a metadata = self.distribution.metadata
197n/a
198n/a # Write the [metadata] section.
199n/a lines.append("[metadata]")
200n/a
201n/a # 'info' will be displayed in the installer's dialog box,
202n/a # describing the items to be installed.
203n/a info = (metadata.long_description or '') + '\n'
204n/a
205n/a # Escape newline characters
206n/a def escape(s):
207n/a return s.replace("\n", "\\n")
208n/a
209n/a for name in ["author", "author_email", "description", "maintainer",
210n/a "maintainer_email", "name", "url", "version"]:
211n/a data = getattr(metadata, name, "")
212n/a if data:
213n/a info = info + ("\n %s: %s" % \
214n/a (name.capitalize(), escape(data)))
215n/a lines.append("%s=%s" % (name, escape(data)))
216n/a
217n/a # The [setup] section contains entries controlling
218n/a # the installer runtime.
219n/a lines.append("\n[Setup]")
220n/a if self.install_script:
221n/a lines.append("install_script=%s" % self.install_script)
222n/a lines.append("info=%s" % escape(info))
223n/a lines.append("target_compile=%d" % (not self.no_target_compile))
224n/a lines.append("target_optimize=%d" % (not self.no_target_optimize))
225n/a if self.target_version:
226n/a lines.append("target_version=%s" % self.target_version)
227n/a if self.user_access_control:
228n/a lines.append("user_access_control=%s" % self.user_access_control)
229n/a
230n/a title = self.title or self.distribution.get_fullname()
231n/a lines.append("title=%s" % escape(title))
232n/a import time
233n/a import distutils
234n/a build_info = "Built %s with distutils-%s" % \
235n/a (time.ctime(time.time()), distutils.__version__)
236n/a lines.append("build_info=%s" % build_info)
237n/a return "\n".join(lines)
238n/a
239n/a def create_exe(self, arcname, fullname, bitmap=None):
240n/a import struct
241n/a
242n/a self.mkpath(self.dist_dir)
243n/a
244n/a cfgdata = self.get_inidata()
245n/a
246n/a installer_name = self.get_installer_filename(fullname)
247n/a self.announce("creating %s" % installer_name)
248n/a
249n/a if bitmap:
250n/a bitmapdata = open(bitmap, "rb").read()
251n/a bitmaplen = len(bitmapdata)
252n/a else:
253n/a bitmaplen = 0
254n/a
255n/a file = open(installer_name, "wb")
256n/a file.write(self.get_exe_bytes())
257n/a if bitmap:
258n/a file.write(bitmapdata)
259n/a
260n/a # Convert cfgdata from unicode to ascii, mbcs encoded
261n/a if isinstance(cfgdata, str):
262n/a cfgdata = cfgdata.encode("mbcs")
263n/a
264n/a # Append the pre-install script
265n/a cfgdata = cfgdata + b"\0"
266n/a if self.pre_install_script:
267n/a # We need to normalize newlines, so we open in text mode and
268n/a # convert back to bytes. "latin-1" simply avoids any possible
269n/a # failures.
270n/a with open(self.pre_install_script, "r",
271n/a encoding="latin-1") as script:
272n/a script_data = script.read().encode("latin-1")
273n/a cfgdata = cfgdata + script_data + b"\n\0"
274n/a else:
275n/a # empty pre-install script
276n/a cfgdata = cfgdata + b"\0"
277n/a file.write(cfgdata)
278n/a
279n/a # The 'magic number' 0x1234567B is used to make sure that the
280n/a # binary layout of 'cfgdata' is what the wininst.exe binary
281n/a # expects. If the layout changes, increment that number, make
282n/a # the corresponding changes to the wininst.exe sources, and
283n/a # recompile them.
284n/a header = struct.pack("<iii",
285n/a 0x1234567B, # tag
286n/a len(cfgdata), # length
287n/a bitmaplen, # number of bytes in bitmap
288n/a )
289n/a file.write(header)
290n/a file.write(open(arcname, "rb").read())
291n/a
292n/a def get_installer_filename(self, fullname):
293n/a # Factored out to allow overriding in subclasses
294n/a if self.target_version:
295n/a # if we create an installer for a specific python version,
296n/a # it's better to include this in the name
297n/a installer_name = os.path.join(self.dist_dir,
298n/a "%s.%s-py%s.exe" %
299n/a (fullname, self.plat_name, self.target_version))
300n/a else:
301n/a installer_name = os.path.join(self.dist_dir,
302n/a "%s.%s.exe" % (fullname, self.plat_name))
303n/a return installer_name
304n/a
305n/a def get_exe_bytes(self):
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
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 and self.target_version < cur_version:
320n/a if self.target_version < "2.4":
321n/a bv = 6.0
322n/a elif self.target_version == "2.4":
323n/a bv = 7.1
324n/a elif self.target_version == "2.5":
325n/a bv = 8.0
326n/a elif self.target_version <= "3.2":
327n/a bv = 9.0
328n/a elif self.target_version <= "3.4":
329n/a bv = 10.0
330n/a else:
331n/a bv = 14.0
332n/a else:
333n/a # for current version - use authoritative check.
334n/a try:
335n/a from msvcrt import CRT_ASSEMBLY_VERSION
336n/a except ImportError:
337n/a # cross-building, so assume the latest version
338n/a bv = 14.0
339n/a else:
340n/a bv = float('.'.join(CRT_ASSEMBLY_VERSION.split('.', 2)[:2]))
341n/a
342n/a
343n/a # wininst-x.y.exe is in the same directory as this file
344n/a directory = os.path.dirname(__file__)
345n/a # we must use a wininst-x.y.exe built with the same C compiler
346n/a # used for python. XXX What about mingw, borland, and so on?
347n/a
348n/a # if plat_name starts with "win" but is not "win32"
349n/a # we want to strip "win" and leave the rest (e.g. -amd64)
350n/a # for all other cases, we don't want any suffix
351n/a if self.plat_name != 'win32' and self.plat_name[:3] == 'win':
352n/a sfix = self.plat_name[3:]
353n/a else:
354n/a sfix = ''
355n/a
356n/a filename = os.path.join(directory, "wininst-%.1f%s.exe" % (bv, sfix))
357n/a f = open(filename, "rb")
358n/a try:
359n/a return f.read()
360n/a finally:
361n/a f.close()