You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

349 lines
12 KiB

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