PageRenderTime 26ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/couchjs/scons/scons-local-2.0.1/SCons/Tool/packaging/msi.py

http://github.com/cloudant/bigcouch
Python | 527 lines | 476 code | 6 blank | 45 comment | 1 complexity | 330feb76b0a18acd47a126d7927dae12 MD5 | raw file
Possible License(s): Apache-2.0
  1. """SCons.Tool.packaging.msi
  2. The msi packager.
  3. """
  4. #
  5. # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
  6. #
  7. # Permission is hereby granted, free of charge, to any person obtaining
  8. # a copy of this software and associated documentation files (the
  9. # "Software"), to deal in the Software without restriction, including
  10. # without limitation the rights to use, copy, modify, merge, publish,
  11. # distribute, sublicense, and/or sell copies of the Software, and to
  12. # permit persons to whom the Software is furnished to do so, subject to
  13. # the following conditions:
  14. #
  15. # The above copyright notice and this permission notice shall be included
  16. # in all copies or substantial portions of the Software.
  17. #
  18. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
  19. # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  20. # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  21. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  22. # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  23. # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  24. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  25. __revision__ = "src/engine/SCons/Tool/packaging/msi.py 5134 2010/08/16 23:02:40 bdeegan"
  26. import os
  27. import SCons
  28. from SCons.Action import Action
  29. from SCons.Builder import Builder
  30. from xml.dom.minidom import *
  31. from xml.sax.saxutils import escape
  32. from SCons.Tool.packaging import stripinstallbuilder
  33. #
  34. # Utility functions
  35. #
  36. def convert_to_id(s, id_set):
  37. """ Some parts of .wxs need an Id attribute (for example: The File and
  38. Directory directives. The charset is limited to A-Z, a-z, digits,
  39. underscores, periods. Each Id must begin with a letter or with a
  40. underscore. Google for "CNDL0015" for information about this.
  41. Requirements:
  42. * the string created must only contain chars from the target charset.
  43. * the string created must have a minimal editing distance from the
  44. original string.
  45. * the string created must be unique for the whole .wxs file.
  46. Observation:
  47. * There are 62 chars in the charset.
  48. Idea:
  49. * filter out forbidden characters. Check for a collision with the help
  50. of the id_set. Add the number of the number of the collision at the
  51. end of the created string. Furthermore care for a correct start of
  52. the string.
  53. """
  54. charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYabcdefghijklmnopqrstuvwxyz0123456789_.'
  55. if s[0] in '0123456789.':
  56. s += '_'+s
  57. id = [c for c in s if c in charset]
  58. # did we already generate an id for this file?
  59. try:
  60. return id_set[id][s]
  61. except KeyError:
  62. # no we did not so initialize with the id
  63. if id not in id_set: id_set[id] = { s : id }
  64. # there is a collision, generate an id which is unique by appending
  65. # the collision number
  66. else: id_set[id][s] = id + str(len(id_set[id]))
  67. return id_set[id][s]
  68. def is_dos_short_file_name(file):
  69. """ examine if the given file is in the 8.3 form.
  70. """
  71. fname, ext = os.path.splitext(file)
  72. proper_ext = len(ext) == 0 or (2 <= len(ext) <= 4) # the ext contains the dot
  73. proper_fname = file.isupper() and len(fname) <= 8
  74. return proper_ext and proper_fname
  75. def gen_dos_short_file_name(file, filename_set):
  76. """ see http://support.microsoft.com/default.aspx?scid=kb;en-us;Q142982
  77. These are no complete 8.3 dos short names. The ~ char is missing and
  78. replaced with one character from the filename. WiX warns about such
  79. filenames, since a collision might occur. Google for "CNDL1014" for
  80. more information.
  81. """
  82. # guard this to not confuse the generation
  83. if is_dos_short_file_name(file):
  84. return file
  85. fname, ext = os.path.splitext(file) # ext contains the dot
  86. # first try if it suffices to convert to upper
  87. file = file.upper()
  88. if is_dos_short_file_name(file):
  89. return file
  90. # strip forbidden characters.
  91. forbidden = '."/[]:;=, '
  92. fname = [c for c in fname if c not in forbidden]
  93. # check if we already generated a filename with the same number:
  94. # thisis1.txt, thisis2.txt etc.
  95. duplicate, num = not None, 1
  96. while duplicate:
  97. shortname = "%s%s" % (fname[:8-len(str(num))].upper(),\
  98. str(num))
  99. if len(ext) >= 2:
  100. shortname = "%s%s" % (shortname, ext[:4].upper())
  101. duplicate, num = shortname in filename_set, num+1
  102. assert( is_dos_short_file_name(shortname) ), 'shortname is %s, longname is %s' % (shortname, file)
  103. filename_set.append(shortname)
  104. return shortname
  105. def create_feature_dict(files):
  106. """ X_MSI_FEATURE and doc FileTag's can be used to collect files in a
  107. hierarchy. This function collects the files into this hierarchy.
  108. """
  109. dict = {}
  110. def add_to_dict( feature, file ):
  111. if not SCons.Util.is_List( feature ):
  112. feature = [ feature ]
  113. for f in feature:
  114. if f not in dict:
  115. dict[ f ] = [ file ]
  116. else:
  117. dict[ f ].append( file )
  118. for file in files:
  119. if hasattr( file, 'PACKAGING_X_MSI_FEATURE' ):
  120. add_to_dict(file.PACKAGING_X_MSI_FEATURE, file)
  121. elif hasattr( file, 'PACKAGING_DOC' ):
  122. add_to_dict( 'PACKAGING_DOC', file )
  123. else:
  124. add_to_dict( 'default', file )
  125. return dict
  126. def generate_guids(root):
  127. """ generates globally unique identifiers for parts of the xml which need
  128. them.
  129. Component tags have a special requirement. Their UUID is only allowed to
  130. change if the list of their contained resources has changed. This allows
  131. for clean removal and proper updates.
  132. To handle this requirement, the uuid is generated with an md5 hashing the
  133. whole subtree of a xml node.
  134. """
  135. from hashlib import md5
  136. # specify which tags need a guid and in which attribute this should be stored.
  137. needs_id = { 'Product' : 'Id',
  138. 'Package' : 'Id',
  139. 'Component' : 'Guid',
  140. }
  141. # find all XMl nodes matching the key, retrieve their attribute, hash their
  142. # subtree, convert hash to string and add as a attribute to the xml node.
  143. for (key,value) in needs_id.items():
  144. node_list = root.getElementsByTagName(key)
  145. attribute = value
  146. for node in node_list:
  147. hash = md5(node.toxml()).hexdigest()
  148. hash_str = '%s-%s-%s-%s-%s' % ( hash[:8], hash[8:12], hash[12:16], hash[16:20], hash[20:] )
  149. node.attributes[attribute] = hash_str
  150. def string_wxsfile(target, source, env):
  151. return "building WiX file %s"%( target[0].path )
  152. def build_wxsfile(target, source, env):
  153. """ compiles a .wxs file from the keywords given in env['msi_spec'] and
  154. by analyzing the tree of source nodes and their tags.
  155. """
  156. file = open(target[0].abspath, 'w')
  157. try:
  158. # Create a document with the Wix root tag
  159. doc = Document()
  160. root = doc.createElement( 'Wix' )
  161. root.attributes['xmlns']='http://schemas.microsoft.com/wix/2003/01/wi'
  162. doc.appendChild( root )
  163. filename_set = [] # this is to circumvent duplicates in the shortnames
  164. id_set = {} # this is to circumvent duplicates in the ids
  165. # Create the content
  166. build_wxsfile_header_section(root, env)
  167. build_wxsfile_file_section(root, source, env['NAME'], env['VERSION'], env['VENDOR'], filename_set, id_set)
  168. generate_guids(root)
  169. build_wxsfile_features_section(root, source, env['NAME'], env['VERSION'], env['SUMMARY'], id_set)
  170. build_wxsfile_default_gui(root)
  171. build_license_file(target[0].get_dir(), env)
  172. # write the xml to a file
  173. file.write( doc.toprettyxml() )
  174. # call a user specified function
  175. if 'CHANGE_SPECFILE' in env:
  176. env['CHANGE_SPECFILE'](target, source)
  177. except KeyError, e:
  178. raise SCons.Errors.UserError( '"%s" package field for MSI is missing.' % e.args[0] )
  179. #
  180. # setup function
  181. #
  182. def create_default_directory_layout(root, NAME, VERSION, VENDOR, filename_set):
  183. """ Create the wix default target directory layout and return the innermost
  184. directory.
  185. We assume that the XML tree delivered in the root argument already contains
  186. the Product tag.
  187. Everything is put under the PFiles directory property defined by WiX.
  188. After that a directory with the 'VENDOR' tag is placed and then a
  189. directory with the name of the project and its VERSION. This leads to the
  190. following TARGET Directory Layout:
  191. C:\<PFiles>\<Vendor>\<Projectname-Version>\
  192. Example: C:\Programme\Company\Product-1.2\
  193. """
  194. doc = Document()
  195. d1 = doc.createElement( 'Directory' )
  196. d1.attributes['Id'] = 'TARGETDIR'
  197. d1.attributes['Name'] = 'SourceDir'
  198. d2 = doc.createElement( 'Directory' )
  199. d2.attributes['Id'] = 'ProgramFilesFolder'
  200. d2.attributes['Name'] = 'PFiles'
  201. d3 = doc.createElement( 'Directory' )
  202. d3.attributes['Id'] = 'VENDOR_folder'
  203. d3.attributes['Name'] = escape( gen_dos_short_file_name( VENDOR, filename_set ) )
  204. d3.attributes['LongName'] = escape( VENDOR )
  205. d4 = doc.createElement( 'Directory' )
  206. project_folder = "%s-%s" % ( NAME, VERSION )
  207. d4.attributes['Id'] = 'MY_DEFAULT_FOLDER'
  208. d4.attributes['Name'] = escape( gen_dos_short_file_name( project_folder, filename_set ) )
  209. d4.attributes['LongName'] = escape( project_folder )
  210. d1.childNodes.append( d2 )
  211. d2.childNodes.append( d3 )
  212. d3.childNodes.append( d4 )
  213. root.getElementsByTagName('Product')[0].childNodes.append( d1 )
  214. return d4
  215. #
  216. # mandatory and optional file tags
  217. #
  218. def build_wxsfile_file_section(root, files, NAME, VERSION, VENDOR, filename_set, id_set):
  219. """ builds the Component sections of the wxs file with their included files.
  220. Files need to be specified in 8.3 format and in the long name format, long
  221. filenames will be converted automatically.
  222. Features are specficied with the 'X_MSI_FEATURE' or 'DOC' FileTag.
  223. """
  224. root = create_default_directory_layout( root, NAME, VERSION, VENDOR, filename_set )
  225. components = create_feature_dict( files )
  226. factory = Document()
  227. def get_directory( node, dir ):
  228. """ returns the node under the given node representing the directory.
  229. Returns the component node if dir is None or empty.
  230. """
  231. if dir == '' or not dir:
  232. return node
  233. Directory = node
  234. dir_parts = dir.split(os.path.sep)
  235. # to make sure that our directory ids are unique, the parent folders are
  236. # consecutively added to upper_dir
  237. upper_dir = ''
  238. # walk down the xml tree finding parts of the directory
  239. dir_parts = [d for d in dir_parts if d != '']
  240. for d in dir_parts[:]:
  241. already_created = [c for c in Directory.childNodes
  242. if c.nodeName == 'Directory'
  243. and c.attributes['LongName'].value == escape(d)]
  244. if already_created != []:
  245. Directory = already_created[0]
  246. dir_parts.remove(d)
  247. upper_dir += d
  248. else:
  249. break
  250. for d in dir_parts:
  251. nDirectory = factory.createElement( 'Directory' )
  252. nDirectory.attributes['LongName'] = escape( d )
  253. nDirectory.attributes['Name'] = escape( gen_dos_short_file_name( d, filename_set ) )
  254. upper_dir += d
  255. nDirectory.attributes['Id'] = convert_to_id( upper_dir, id_set )
  256. Directory.childNodes.append( nDirectory )
  257. Directory = nDirectory
  258. return Directory
  259. for file in files:
  260. drive, path = os.path.splitdrive( file.PACKAGING_INSTALL_LOCATION )
  261. filename = os.path.basename( path )
  262. dirname = os.path.dirname( path )
  263. h = {
  264. # tagname : default value
  265. 'PACKAGING_X_MSI_VITAL' : 'yes',
  266. 'PACKAGING_X_MSI_FILEID' : convert_to_id(filename, id_set),
  267. 'PACKAGING_X_MSI_LONGNAME' : filename,
  268. 'PACKAGING_X_MSI_SHORTNAME' : gen_dos_short_file_name(filename, filename_set),
  269. 'PACKAGING_X_MSI_SOURCE' : file.get_path(),
  270. }
  271. # fill in the default tags given above.
  272. for k,v in [ (k, v) for (k,v) in h.items() if not hasattr(file, k) ]:
  273. setattr( file, k, v )
  274. File = factory.createElement( 'File' )
  275. File.attributes['LongName'] = escape( file.PACKAGING_X_MSI_LONGNAME )
  276. File.attributes['Name'] = escape( file.PACKAGING_X_MSI_SHORTNAME )
  277. File.attributes['Source'] = escape( file.PACKAGING_X_MSI_SOURCE )
  278. File.attributes['Id'] = escape( file.PACKAGING_X_MSI_FILEID )
  279. File.attributes['Vital'] = escape( file.PACKAGING_X_MSI_VITAL )
  280. # create the <Component> Tag under which this file should appear
  281. Component = factory.createElement('Component')
  282. Component.attributes['DiskId'] = '1'
  283. Component.attributes['Id'] = convert_to_id( filename, id_set )
  284. # hang the component node under the root node and the file node
  285. # under the component node.
  286. Directory = get_directory( root, dirname )
  287. Directory.childNodes.append( Component )
  288. Component.childNodes.append( File )
  289. #
  290. # additional functions
  291. #
  292. def build_wxsfile_features_section(root, files, NAME, VERSION, SUMMARY, id_set):
  293. """ This function creates the <features> tag based on the supplied xml tree.
  294. This is achieved by finding all <component>s and adding them to a default target.
  295. It should be called after the tree has been built completly. We assume
  296. that a MY_DEFAULT_FOLDER Property is defined in the wxs file tree.
  297. Furthermore a top-level with the name and VERSION of the software will be created.
  298. An PACKAGING_X_MSI_FEATURE can either be a string, where the feature
  299. DESCRIPTION will be the same as its title or a Tuple, where the first
  300. part will be its title and the second its DESCRIPTION.
  301. """
  302. factory = Document()
  303. Feature = factory.createElement('Feature')
  304. Feature.attributes['Id'] = 'complete'
  305. Feature.attributes['ConfigurableDirectory'] = 'MY_DEFAULT_FOLDER'
  306. Feature.attributes['Level'] = '1'
  307. Feature.attributes['Title'] = escape( '%s %s' % (NAME, VERSION) )
  308. Feature.attributes['Description'] = escape( SUMMARY )
  309. Feature.attributes['Display'] = 'expand'
  310. for (feature, files) in create_feature_dict(files).items():
  311. SubFeature = factory.createElement('Feature')
  312. SubFeature.attributes['Level'] = '1'
  313. if SCons.Util.is_Tuple(feature):
  314. SubFeature.attributes['Id'] = convert_to_id( feature[0], id_set )
  315. SubFeature.attributes['Title'] = escape(feature[0])
  316. SubFeature.attributes['Description'] = escape(feature[1])
  317. else:
  318. SubFeature.attributes['Id'] = convert_to_id( feature, id_set )
  319. if feature=='default':
  320. SubFeature.attributes['Description'] = 'Main Part'
  321. SubFeature.attributes['Title'] = 'Main Part'
  322. elif feature=='PACKAGING_DOC':
  323. SubFeature.attributes['Description'] = 'Documentation'
  324. SubFeature.attributes['Title'] = 'Documentation'
  325. else:
  326. SubFeature.attributes['Description'] = escape(feature)
  327. SubFeature.attributes['Title'] = escape(feature)
  328. # build the componentrefs. As one of the design decision is that every
  329. # file is also a component we walk the list of files and create a
  330. # reference.
  331. for f in files:
  332. ComponentRef = factory.createElement('ComponentRef')
  333. ComponentRef.attributes['Id'] = convert_to_id( os.path.basename(f.get_path()), id_set )
  334. SubFeature.childNodes.append(ComponentRef)
  335. Feature.childNodes.append(SubFeature)
  336. root.getElementsByTagName('Product')[0].childNodes.append(Feature)
  337. def build_wxsfile_default_gui(root):
  338. """ this function adds a default GUI to the wxs file
  339. """
  340. factory = Document()
  341. Product = root.getElementsByTagName('Product')[0]
  342. UIRef = factory.createElement('UIRef')
  343. UIRef.attributes['Id'] = 'WixUI_Mondo'
  344. Product.childNodes.append(UIRef)
  345. UIRef = factory.createElement('UIRef')
  346. UIRef.attributes['Id'] = 'WixUI_ErrorProgressText'
  347. Product.childNodes.append(UIRef)
  348. def build_license_file(directory, spec):
  349. """ creates a License.rtf file with the content of "X_MSI_LICENSE_TEXT"
  350. in the given directory
  351. """
  352. name, text = '', ''
  353. try:
  354. name = spec['LICENSE']
  355. text = spec['X_MSI_LICENSE_TEXT']
  356. except KeyError:
  357. pass # ignore this as X_MSI_LICENSE_TEXT is optional
  358. if name!='' or text!='':
  359. file = open( os.path.join(directory.get_path(), 'License.rtf'), 'w' )
  360. file.write('{\\rtf')
  361. if text!='':
  362. file.write(text.replace('\n', '\\par '))
  363. else:
  364. file.write(name+'\\par\\par')
  365. file.write('}')
  366. file.close()
  367. #
  368. # mandatory and optional package tags
  369. #
  370. def build_wxsfile_header_section(root, spec):
  371. """ Adds the xml file node which define the package meta-data.
  372. """
  373. # Create the needed DOM nodes and add them at the correct position in the tree.
  374. factory = Document()
  375. Product = factory.createElement( 'Product' )
  376. Package = factory.createElement( 'Package' )
  377. root.childNodes.append( Product )
  378. Product.childNodes.append( Package )
  379. # set "mandatory" default values
  380. if 'X_MSI_LANGUAGE' not in spec:
  381. spec['X_MSI_LANGUAGE'] = '1033' # select english
  382. # mandatory sections, will throw a KeyError if the tag is not available
  383. Product.attributes['Name'] = escape( spec['NAME'] )
  384. Product.attributes['Version'] = escape( spec['VERSION'] )
  385. Product.attributes['Manufacturer'] = escape( spec['VENDOR'] )
  386. Product.attributes['Language'] = escape( spec['X_MSI_LANGUAGE'] )
  387. Package.attributes['Description'] = escape( spec['SUMMARY'] )
  388. # now the optional tags, for which we avoid the KeyErrror exception
  389. if 'DESCRIPTION' in spec:
  390. Package.attributes['Comments'] = escape( spec['DESCRIPTION'] )
  391. if 'X_MSI_UPGRADE_CODE' in spec:
  392. Package.attributes['X_MSI_UPGRADE_CODE'] = escape( spec['X_MSI_UPGRADE_CODE'] )
  393. # We hardcode the media tag as our current model cannot handle it.
  394. Media = factory.createElement('Media')
  395. Media.attributes['Id'] = '1'
  396. Media.attributes['Cabinet'] = 'default.cab'
  397. Media.attributes['EmbedCab'] = 'yes'
  398. root.getElementsByTagName('Product')[0].childNodes.append(Media)
  399. # this builder is the entry-point for .wxs file compiler.
  400. wxs_builder = Builder(
  401. action = Action( build_wxsfile, string_wxsfile ),
  402. ensure_suffix = '.wxs' )
  403. def package(env, target, source, PACKAGEROOT, NAME, VERSION,
  404. DESCRIPTION, SUMMARY, VENDOR, X_MSI_LANGUAGE, **kw):
  405. # make sure that the Wix Builder is in the environment
  406. SCons.Tool.Tool('wix').generate(env)
  407. # get put the keywords for the specfile compiler. These are the arguments
  408. # given to the package function and all optional ones stored in kw, minus
  409. # the the source, target and env one.
  410. loc = locals()
  411. del loc['kw']
  412. kw.update(loc)
  413. del kw['source'], kw['target'], kw['env']
  414. # strip the install builder from the source files
  415. target, source = stripinstallbuilder(target, source, env)
  416. # put the arguments into the env and call the specfile builder.
  417. env['msi_spec'] = kw
  418. specfile = wxs_builder(* [env, target, source], **kw)
  419. # now call the WiX Tool with the built specfile added as a source.
  420. msifile = env.WiX(target, specfile)
  421. # return the target and source tuple.
  422. return (msifile, source+[specfile])
  423. # Local Variables:
  424. # tab-width:4
  425. # indent-tabs-mode:nil
  426. # End:
  427. # vim: set expandtab tabstop=4 shiftwidth=4: