bdist_wininst.py 15 KB

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