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