PageRenderTime 68ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/scons-local-2.3.2/SCons/Tool/packaging/rpm.py

https://github.com/dustyleary/scons-local
Python | 357 lines | 309 code | 13 blank | 35 comment | 5 complexity | 1422e5fd7e64b3e8d92e784c2241343f MD5 | raw file
  1. """SCons.Tool.Packaging.rpm
  2. The rpm packager.
  3. """
  4. #
  5. # Copyright (c) 2001 - 2014 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/rpm.py 2014/07/05 09:42:21 garyo"
  26. import os
  27. import SCons.Builder
  28. import SCons.Tool.rpmutils
  29. from SCons.Environment import OverrideEnvironment
  30. from SCons.Tool.packaging import stripinstallbuilder, src_targz
  31. from SCons.Errors import UserError
  32. def package(env, target, source, PACKAGEROOT, NAME, VERSION,
  33. PACKAGEVERSION, DESCRIPTION, SUMMARY, X_RPM_GROUP, LICENSE,
  34. **kw):
  35. # initialize the rpm tool
  36. SCons.Tool.Tool('rpm').generate(env)
  37. bld = env['BUILDERS']['Rpm']
  38. # Generate a UserError whenever the target name has been set explicitly,
  39. # since rpm does not allow for controlling it. This is detected by
  40. # checking if the target has been set to the default by the Package()
  41. # Environment function.
  42. if str(target[0])!="%s-%s"%(NAME, VERSION):
  43. raise UserError( "Setting target is not supported for rpm." )
  44. else:
  45. # This should be overridable from the construction environment,
  46. # which it is by using ARCHITECTURE=.
  47. buildarchitecture = SCons.Tool.rpmutils.defaultMachine()
  48. if 'ARCHITECTURE' in kw:
  49. buildarchitecture = kw['ARCHITECTURE']
  50. fmt = '%s-%s-%s.%s.rpm'
  51. srcrpm = fmt % (NAME, VERSION, PACKAGEVERSION, 'src')
  52. binrpm = fmt % (NAME, VERSION, PACKAGEVERSION, buildarchitecture)
  53. target = [ srcrpm, binrpm ]
  54. # get the correct arguments into the kw hash
  55. loc=locals()
  56. del loc['kw']
  57. kw.update(loc)
  58. del kw['source'], kw['target'], kw['env']
  59. # if no "SOURCE_URL" tag is given add a default one.
  60. if 'SOURCE_URL' not in kw:
  61. #kw['SOURCE_URL']=(str(target[0])+".tar.gz").replace('.rpm', '')
  62. kw['SOURCE_URL']=(str(target[0])+".tar.gz").replace('.rpm', '')
  63. # mangle the source and target list for the rpmbuild
  64. env = OverrideEnvironment(env, kw)
  65. target, source = stripinstallbuilder(target, source, env)
  66. target, source = addspecfile(target, source, env)
  67. target, source = collectintargz(target, source, env)
  68. # now call the rpm builder to actually build the packet.
  69. return bld(env, target, source, **kw)
  70. def collectintargz(target, source, env):
  71. """ Puts all source files into a tar.gz file. """
  72. # the rpm tool depends on a source package, until this is chagned
  73. # this hack needs to be here that tries to pack all sources in.
  74. sources = env.FindSourceFiles()
  75. # filter out the target we are building the source list for.
  76. #sources = [s for s in sources if not (s in target)]
  77. sources = [s for s in sources if s not in target]
  78. # find the .spec file for rpm and add it since it is not necessarily found
  79. # by the FindSourceFiles function.
  80. #sources.extend( [s for s in source if str(s).rfind('.spec')!=-1] )
  81. spec_file = lambda s: str(s).rfind('.spec') != -1
  82. sources.extend( list(filter(spec_file, source)) )
  83. # as the source contains the url of the source package this rpm package
  84. # is built from, we extract the target name
  85. #tarball = (str(target[0])+".tar.gz").replace('.rpm', '')
  86. tarball = (str(target[0])+".tar.gz").replace('.rpm', '')
  87. try:
  88. #tarball = env['SOURCE_URL'].split('/')[-1]
  89. tarball = env['SOURCE_URL'].split('/')[-1]
  90. except KeyError, e:
  91. raise SCons.Errors.UserError( "Missing PackageTag '%s' for RPM packager" % e.args[0] )
  92. tarball = src_targz.package(env, source=sources, target=tarball,
  93. PACKAGEROOT=env['PACKAGEROOT'], )
  94. return (target, tarball)
  95. def addspecfile(target, source, env):
  96. specfile = "%s-%s" % (env['NAME'], env['VERSION'])
  97. bld = SCons.Builder.Builder(action = build_specfile,
  98. suffix = '.spec',
  99. target_factory = SCons.Node.FS.File)
  100. source.extend(bld(env, specfile, source))
  101. return (target,source)
  102. def build_specfile(target, source, env):
  103. """ Builds a RPM specfile from a dictionary with string metadata and
  104. by analyzing a tree of nodes.
  105. """
  106. file = open(target[0].abspath, 'w')
  107. str = ""
  108. try:
  109. file.write( build_specfile_header(env) )
  110. file.write( build_specfile_sections(env) )
  111. file.write( build_specfile_filesection(env, source) )
  112. file.close()
  113. # call a user specified function
  114. if 'CHANGE_SPECFILE' in env:
  115. env['CHANGE_SPECFILE'](target, source)
  116. except KeyError, e:
  117. raise SCons.Errors.UserError( '"%s" package field for RPM is missing.' % e.args[0] )
  118. #
  119. # mandatory and optional package tag section
  120. #
  121. def build_specfile_sections(spec):
  122. """ Builds the sections of a rpm specfile.
  123. """
  124. str = ""
  125. mandatory_sections = {
  126. 'DESCRIPTION' : '\n%%description\n%s\n\n', }
  127. str = str + SimpleTagCompiler(mandatory_sections).compile( spec )
  128. optional_sections = {
  129. 'DESCRIPTION_' : '%%description -l %s\n%s\n\n',
  130. 'CHANGELOG' : '%%changelog\n%s\n\n',
  131. 'X_RPM_PREINSTALL' : '%%pre\n%s\n\n',
  132. 'X_RPM_POSTINSTALL' : '%%post\n%s\n\n',
  133. 'X_RPM_PREUNINSTALL' : '%%preun\n%s\n\n',
  134. 'X_RPM_POSTUNINSTALL' : '%%postun\n%s\n\n',
  135. 'X_RPM_VERIFY' : '%%verify\n%s\n\n',
  136. # These are for internal use but could possibly be overriden
  137. 'X_RPM_PREP' : '%%prep\n%s\n\n',
  138. 'X_RPM_BUILD' : '%%build\n%s\n\n',
  139. 'X_RPM_INSTALL' : '%%install\n%s\n\n',
  140. 'X_RPM_CLEAN' : '%%clean\n%s\n\n',
  141. }
  142. # Default prep, build, install and clean rules
  143. # TODO: optimize those build steps, to not compile the project a second time
  144. if 'X_RPM_PREP' not in spec:
  145. spec['X_RPM_PREP'] = '[ -n "$RPM_BUILD_ROOT" -a "$RPM_BUILD_ROOT" != / ] && rm -rf "$RPM_BUILD_ROOT"' + '\n%setup -q'
  146. if 'X_RPM_BUILD' not in spec:
  147. spec['X_RPM_BUILD'] = 'mkdir "$RPM_BUILD_ROOT"'
  148. if 'X_RPM_INSTALL' not in spec:
  149. spec['X_RPM_INSTALL'] = 'scons --install-sandbox="$RPM_BUILD_ROOT" "$RPM_BUILD_ROOT"'
  150. if 'X_RPM_CLEAN' not in spec:
  151. spec['X_RPM_CLEAN'] = '[ -n "$RPM_BUILD_ROOT" -a "$RPM_BUILD_ROOT" != / ] && rm -rf "$RPM_BUILD_ROOT"'
  152. str = str + SimpleTagCompiler(optional_sections, mandatory=0).compile( spec )
  153. return str
  154. def build_specfile_header(spec):
  155. """ Builds all section but the %file of a rpm specfile
  156. """
  157. str = ""
  158. # first the mandatory sections
  159. mandatory_header_fields = {
  160. 'NAME' : '%%define name %s\nName: %%{name}\n',
  161. 'VERSION' : '%%define version %s\nVersion: %%{version}\n',
  162. 'PACKAGEVERSION' : '%%define release %s\nRelease: %%{release}\n',
  163. 'X_RPM_GROUP' : 'Group: %s\n',
  164. 'SUMMARY' : 'Summary: %s\n',
  165. 'LICENSE' : 'License: %s\n', }
  166. str = str + SimpleTagCompiler(mandatory_header_fields).compile( spec )
  167. # now the optional tags
  168. optional_header_fields = {
  169. 'VENDOR' : 'Vendor: %s\n',
  170. 'X_RPM_URL' : 'Url: %s\n',
  171. 'SOURCE_URL' : 'Source: %s\n',
  172. 'SUMMARY_' : 'Summary(%s): %s\n',
  173. 'X_RPM_DISTRIBUTION' : 'Distribution: %s\n',
  174. 'X_RPM_ICON' : 'Icon: %s\n',
  175. 'X_RPM_PACKAGER' : 'Packager: %s\n',
  176. 'X_RPM_GROUP_' : 'Group(%s): %s\n',
  177. 'X_RPM_REQUIRES' : 'Requires: %s\n',
  178. 'X_RPM_PROVIDES' : 'Provides: %s\n',
  179. 'X_RPM_CONFLICTS' : 'Conflicts: %s\n',
  180. 'X_RPM_BUILDREQUIRES' : 'BuildRequires: %s\n',
  181. 'X_RPM_SERIAL' : 'Serial: %s\n',
  182. 'X_RPM_EPOCH' : 'Epoch: %s\n',
  183. 'X_RPM_AUTOREQPROV' : 'AutoReqProv: %s\n',
  184. 'X_RPM_EXCLUDEARCH' : 'ExcludeArch: %s\n',
  185. 'X_RPM_EXCLUSIVEARCH' : 'ExclusiveArch: %s\n',
  186. 'X_RPM_PREFIX' : 'Prefix: %s\n',
  187. 'X_RPM_CONFLICTS' : 'Conflicts: %s\n',
  188. # internal use
  189. 'X_RPM_BUILDROOT' : 'BuildRoot: %s\n', }
  190. # fill in default values:
  191. # Adding a BuildRequires renders the .rpm unbuildable under System, which
  192. # are not managed by rpm, since the database to resolve this dependency is
  193. # missing (take Gentoo as an example)
  194. # if not s.has_key('x_rpm_BuildRequires'):
  195. # s['x_rpm_BuildRequires'] = 'scons'
  196. if 'X_RPM_BUILDROOT' not in spec:
  197. spec['X_RPM_BUILDROOT'] = '%{_tmppath}/%{name}-%{version}-%{release}'
  198. str = str + SimpleTagCompiler(optional_header_fields, mandatory=0).compile( spec )
  199. return str
  200. #
  201. # mandatory and optional file tags
  202. #
  203. def build_specfile_filesection(spec, files):
  204. """ builds the %file section of the specfile
  205. """
  206. str = '%files\n'
  207. if 'X_RPM_DEFATTR' not in spec:
  208. spec['X_RPM_DEFATTR'] = '(-,root,root)'
  209. str = str + '%%defattr %s\n' % spec['X_RPM_DEFATTR']
  210. supported_tags = {
  211. 'PACKAGING_CONFIG' : '%%config %s',
  212. 'PACKAGING_CONFIG_NOREPLACE' : '%%config(noreplace) %s',
  213. 'PACKAGING_DOC' : '%%doc %s',
  214. 'PACKAGING_UNIX_ATTR' : '%%attr %s',
  215. 'PACKAGING_LANG_' : '%%lang(%s) %s',
  216. 'PACKAGING_X_RPM_VERIFY' : '%%verify %s',
  217. 'PACKAGING_X_RPM_DIR' : '%%dir %s',
  218. 'PACKAGING_X_RPM_DOCDIR' : '%%docdir %s',
  219. 'PACKAGING_X_RPM_GHOST' : '%%ghost %s', }
  220. for file in files:
  221. # build the tagset
  222. tags = {}
  223. for k in supported_tags.keys():
  224. try:
  225. tags[k]=getattr(file, k)
  226. except AttributeError:
  227. pass
  228. # compile the tagset
  229. str = str + SimpleTagCompiler(supported_tags, mandatory=0).compile( tags )
  230. str = str + ' '
  231. str = str + file.PACKAGING_INSTALL_LOCATION
  232. str = str + '\n\n'
  233. return str
  234. class SimpleTagCompiler(object):
  235. """ This class is a simple string substition utility:
  236. the replacement specfication is stored in the tagset dictionary, something
  237. like:
  238. { "abc" : "cdef %s ",
  239. "abc_" : "cdef %s %s" }
  240. the compile function gets a value dictionary, which may look like:
  241. { "abc" : "ghij",
  242. "abc_gh" : "ij" }
  243. The resulting string will be:
  244. "cdef ghij cdef gh ij"
  245. """
  246. def __init__(self, tagset, mandatory=1):
  247. self.tagset = tagset
  248. self.mandatory = mandatory
  249. def compile(self, values):
  250. """ compiles the tagset and returns a str containing the result
  251. """
  252. def is_international(tag):
  253. #return tag.endswith('_')
  254. return tag[-1:] == '_'
  255. def get_country_code(tag):
  256. return tag[-2:]
  257. def strip_country_code(tag):
  258. return tag[:-2]
  259. replacements = list(self.tagset.items())
  260. str = ""
  261. #domestic = [ (k,v) for k,v in replacements if not is_international(k) ]
  262. domestic = [t for t in replacements if not is_international(t[0])]
  263. for key, replacement in domestic:
  264. try:
  265. str = str + replacement % values[key]
  266. except KeyError, e:
  267. if self.mandatory:
  268. raise e
  269. #international = [ (k,v) for k,v in replacements if is_international(k) ]
  270. international = [t for t in replacements if is_international(t[0])]
  271. for key, replacement in international:
  272. try:
  273. #int_values_for_key = [ (get_country_code(k),v) for k,v in values.items() if strip_country_code(k) == key ]
  274. x = [t for t in values.items() if strip_country_code(t[0]) == key]
  275. int_values_for_key = [(get_country_code(t[0]),t[1]) for t in x]
  276. for v in int_values_for_key:
  277. str = str + replacement % v
  278. except KeyError, e:
  279. if self.mandatory:
  280. raise e
  281. return str
  282. # Local Variables:
  283. # tab-width:4
  284. # indent-tabs-mode:nil
  285. # End:
  286. # vim: set expandtab tabstop=4 shiftwidth=4: