createmsi.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. #!/usr/bin/env python3
  2. # Copyright 2017-2021 The Meson development team
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. '''
  16. This script is for generating MSI packages
  17. for Windows users.
  18. '''
  19. import subprocess
  20. import shutil
  21. import uuid
  22. import sys
  23. import os
  24. from glob import glob
  25. import xml.etree.ElementTree as ET
  26. sys.path.append(os.getcwd())
  27. from mesonbuild import coredata
  28. # Elementtree does not support CDATA. So hack it.
  29. WINVER_CHECK = '<![CDATA[Installed OR (VersionNT64 > 602)]]>'
  30. def gen_guid():
  31. '''
  32. Generate guid
  33. '''
  34. return str(uuid.uuid4()).upper()
  35. class Node:
  36. '''
  37. Node to hold path and directory values
  38. '''
  39. def __init__(self, dirs, files):
  40. self.check_dirs(dirs)
  41. self.check_files(files)
  42. self.dirs = dirs
  43. self.files = files
  44. @staticmethod
  45. def check_dirs(dirs):
  46. '''
  47. Check to see if directory is instance of list
  48. '''
  49. assert isinstance(dirs, list)
  50. @staticmethod
  51. def check_files(files):
  52. '''
  53. Check to see if files is instance of list
  54. '''
  55. assert isinstance(files, list)
  56. class PackageGenerator:
  57. '''
  58. Package generator for MSI packages
  59. '''
  60. def __init__(self):
  61. self.product_name = 'Meson Build System'
  62. self.manufacturer = 'The Meson Development Team'
  63. self.version = coredata.version.replace('dev', '')
  64. self.root = None
  65. self.guid = '*'
  66. self.update_guid = '141527EE-E28A-4D14-97A4-92E6075D28B2'
  67. self.main_xml = 'meson.wxs'
  68. self.main_o = 'meson.wixobj'
  69. self.final_output = f'meson-{self.version}-64.msi'
  70. self.staging_dirs = ['dist', 'dist2']
  71. self.progfile_dir = 'ProgramFiles64Folder'
  72. redist_globs = ['C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Community\\VC\\Redist\\MSVC\\v*\\MergeModules\\Microsoft_VC142_CRT_x64.msm',
  73. 'C:\\Program Files\\Microsoft Visual Studio\\2022\\Community\\VC\\Redist\\MSVC\\v*\\MergeModules\\Microsoft_VC143_CRT_x64.msm']
  74. redist_path = None
  75. for g in redist_globs:
  76. trials = glob(g)
  77. if len(trials) > 1:
  78. sys.exit('MSM glob matched multiple entries:' + '\n'.join(trials))
  79. if len(trials) == 1:
  80. redist_path = trials[0]
  81. break
  82. if redist_path is None:
  83. sys.exit('No MSMs found.')
  84. self.redist_path = redist_path
  85. self.component_num = 0
  86. self.feature_properties = {
  87. self.staging_dirs[0]: {
  88. 'Id': 'MainProgram',
  89. 'Title': 'Meson',
  90. 'Description': 'Meson executables',
  91. 'Level': '1',
  92. 'Absent': 'disallow',
  93. },
  94. self.staging_dirs[1]: {
  95. 'Id': 'NinjaProgram',
  96. 'Title': 'Ninja',
  97. 'Description': 'Ninja build tool',
  98. 'Level': '1',
  99. }
  100. }
  101. self.feature_components = {}
  102. for s_d in self.staging_dirs:
  103. self.feature_components[s_d] = []
  104. def build_dist(self):
  105. '''
  106. Build dist file from PyInstaller info
  107. '''
  108. for sdir in self.staging_dirs:
  109. if os.path.exists(sdir):
  110. shutil.rmtree(sdir)
  111. main_stage, ninja_stage = self.staging_dirs
  112. pyinstaller = shutil.which('pyinstaller')
  113. if not pyinstaller:
  114. print("ERROR: This script requires pyinstaller.")
  115. sys.exit(1)
  116. pyinstaller_tmpdir = 'pyinst-tmp'
  117. if os.path.exists(pyinstaller_tmpdir):
  118. shutil.rmtree(pyinstaller_tmpdir)
  119. pyinst_cmd = [pyinstaller,
  120. '--clean',
  121. '--additional-hooks-dir=packaging',
  122. '--distpath',
  123. pyinstaller_tmpdir]
  124. pyinst_cmd += ['meson.py']
  125. subprocess.check_call(pyinst_cmd)
  126. shutil.move(pyinstaller_tmpdir + '/meson', main_stage)
  127. self.del_infodirs(main_stage)
  128. if not os.path.exists(os.path.join(main_stage, 'meson.exe')):
  129. sys.exit('Meson exe missing from staging dir.')
  130. os.mkdir(ninja_stage)
  131. shutil.copy(shutil.which('ninja'), ninja_stage)
  132. if not os.path.exists(os.path.join(ninja_stage, 'ninja.exe')):
  133. sys.exit('Ninja exe missing from staging dir.')
  134. def del_infodirs(self, dirname):
  135. # Starting with 3.9.something there are some
  136. # extra metadatadirs that have a hyphen in their
  137. # file names. This is a forbidden character in WiX
  138. # filenames so delete them.
  139. for d in glob(os.path.join(dirname, '*-info')):
  140. shutil.rmtree(d)
  141. def generate_files(self):
  142. '''
  143. Generate package files for MSI installer package
  144. '''
  145. self.root = ET.Element('Wix', {'xmlns': 'http://schemas.microsoft.com/wix/2006/wi'})
  146. product = ET.SubElement(self.root, 'Product', {
  147. 'Name': self.product_name,
  148. 'Manufacturer': 'The Meson Development Team',
  149. 'Id': self.guid,
  150. 'UpgradeCode': self.update_guid,
  151. 'Language': '1033',
  152. 'Codepage': '1252',
  153. 'Version': self.version,
  154. })
  155. package = ET.SubElement(product, 'Package', {
  156. 'Id': '*',
  157. 'Keywords': 'Installer',
  158. 'Description': f'Meson {self.version} installer',
  159. 'Comments': 'Meson is a high performance build system',
  160. 'Manufacturer': 'The Meson Development Team',
  161. 'InstallerVersion': '500',
  162. 'Languages': '1033',
  163. 'Compressed': 'yes',
  164. 'SummaryCodepage': '1252',
  165. })
  166. condition = ET.SubElement(product, 'Condition', {'Message': 'This application is only supported on Windows 10 or higher.'})
  167. condition.text = 'X'*len(WINVER_CHECK)
  168. ET.SubElement(product, 'MajorUpgrade',
  169. {'DowngradeErrorMessage': 'A newer version of Meson is already installed.'})
  170. package.set('Platform', 'x64')
  171. ET.SubElement(product, 'Media', {
  172. 'Id': '1',
  173. 'Cabinet': 'meson.cab',
  174. 'EmbedCab': 'yes',
  175. })
  176. targetdir = ET.SubElement(product, 'Directory', {
  177. 'Id': 'TARGETDIR',
  178. 'Name': 'SourceDir',
  179. })
  180. progfiledir = ET.SubElement(targetdir, 'Directory', {
  181. 'Id': self.progfile_dir,
  182. })
  183. installdir = ET.SubElement(progfiledir, 'Directory', {
  184. 'Id': 'INSTALLDIR',
  185. 'Name': 'Meson',
  186. })
  187. ET.SubElement(installdir, 'Merge', {
  188. 'Id': 'VCRedist',
  189. 'SourceFile': self.redist_path,
  190. 'DiskId': '1',
  191. 'Language': '0',
  192. })
  193. ET.SubElement(product, 'Property', {
  194. 'Id': 'WIXUI_INSTALLDIR',
  195. 'Value': 'INSTALLDIR',
  196. })
  197. ET.SubElement(product, 'UIRef', {
  198. 'Id': 'WixUI_FeatureTree',
  199. })
  200. for s_d in self.staging_dirs:
  201. assert os.path.isdir(s_d)
  202. top_feature = ET.SubElement(product, 'Feature', {
  203. 'Id': 'Complete',
  204. 'Title': 'Meson ' + self.version,
  205. 'Description': 'The complete package',
  206. 'Display': 'expand',
  207. 'Level': '1',
  208. 'ConfigurableDirectory': 'INSTALLDIR',
  209. })
  210. for s_d in self.staging_dirs:
  211. nodes = {}
  212. for root, dirs, files in os.walk(s_d):
  213. cur_node = Node(dirs, files)
  214. nodes[root] = cur_node
  215. self.create_xml(nodes, s_d, installdir, s_d)
  216. self.build_features(top_feature, s_d)
  217. vcredist_feature = ET.SubElement(top_feature, 'Feature', {
  218. 'Id': 'VCRedist',
  219. 'Title': 'Visual C++ runtime',
  220. 'AllowAdvertise': 'no',
  221. 'Display': 'hidden',
  222. 'Level': '1',
  223. })
  224. ET.SubElement(vcredist_feature, 'MergeRef', {'Id': 'VCRedist'})
  225. ET.ElementTree(self.root).write(self.main_xml, encoding='utf-8', xml_declaration=True)
  226. # ElementTree can not do prettyprinting so do it manually
  227. import xml.dom.minidom
  228. doc = xml.dom.minidom.parse(self.main_xml)
  229. with open(self.main_xml, 'w') as open_file:
  230. open_file.write(doc.toprettyxml())
  231. # One last fix, add CDATA.
  232. with open(self.main_xml) as open_file:
  233. data = open_file.read()
  234. data = data.replace('X'*len(WINVER_CHECK), WINVER_CHECK)
  235. with open(self.main_xml, 'w') as open_file:
  236. open_file.write(data)
  237. def build_features(self, top_feature, staging_dir):
  238. '''
  239. Generate build features
  240. '''
  241. feature = ET.SubElement(top_feature, 'Feature', self.feature_properties[staging_dir])
  242. for component_id in self.feature_components[staging_dir]:
  243. ET.SubElement(feature, 'ComponentRef', {
  244. 'Id': component_id,
  245. })
  246. def create_xml(self, nodes, current_dir, parent_xml_node, staging_dir):
  247. '''
  248. Create XML file
  249. '''
  250. cur_node = nodes[current_dir]
  251. if cur_node.files:
  252. component_id = f'ApplicationFiles{self.component_num}'
  253. comp_xml_node = ET.SubElement(parent_xml_node, 'Component', {
  254. 'Id': component_id,
  255. 'Guid': gen_guid(),
  256. })
  257. self.feature_components[staging_dir].append(component_id)
  258. comp_xml_node.set('Win64', 'yes')
  259. if self.component_num == 0:
  260. ET.SubElement(comp_xml_node, 'Environment', {
  261. 'Id': 'Environment',
  262. 'Name': 'PATH',
  263. 'Part': 'last',
  264. 'System': 'yes',
  265. 'Action': 'set',
  266. 'Value': '[INSTALLDIR]',
  267. })
  268. self.component_num += 1
  269. for f_node in cur_node.files:
  270. file_id = os.path.join(current_dir, f_node).replace('\\', '_').replace('#', '_').replace('-', '_')
  271. ET.SubElement(comp_xml_node, 'File', {
  272. 'Id': file_id,
  273. 'Name': f_node,
  274. 'Source': os.path.join(current_dir, f_node),
  275. })
  276. for dirname in cur_node.dirs:
  277. dir_id = os.path.join(current_dir, dirname).replace('\\', '_').replace('/', '_')
  278. dir_node = ET.SubElement(parent_xml_node, 'Directory', {
  279. 'Id': dir_id,
  280. 'Name': dirname,
  281. })
  282. self.create_xml(nodes, os.path.join(current_dir, dirname), dir_node, staging_dir)
  283. def build_package(self):
  284. '''
  285. Generate the Meson build MSI package.
  286. '''
  287. wixdir = 'c:\\Program Files\\Wix Toolset v3.11\\bin'
  288. if not os.path.isdir(wixdir):
  289. wixdir = 'c:\\Program Files (x86)\\Wix Toolset v3.11\\bin'
  290. if not os.path.isdir(wixdir):
  291. print("ERROR: This script requires WIX")
  292. sys.exit(1)
  293. subprocess.check_call([os.path.join(wixdir, 'candle'), self.main_xml])
  294. subprocess.check_call([os.path.join(wixdir, 'light'),
  295. '-ext', 'WixUIExtension',
  296. '-cultures:en-us',
  297. '-dWixUILicenseRtf=packaging\\License.rtf',
  298. '-out', self.final_output,
  299. self.main_o])
  300. if __name__ == '__main__':
  301. if not os.path.exists('meson.py'):
  302. sys.exit(print('Run me in the top level source dir.'))
  303. subprocess.check_call(['pip', 'install', '--upgrade', 'pyinstaller'])
  304. p = PackageGenerator()
  305. p.build_dist()
  306. p.generate_files()
  307. p.build_package()