bdist_wininst.py 15 KB

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