/Lib/distutils/command/bdist_wininst.py

http://unladen-swallow.googlecode.com/ · Python · 358 lines · 356 code · 0 blank · 2 comment · 4 complexity · 30d36977223619656886881f72498a52 MD5 · raw file

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