bdist_wininst.py 16 KB

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