Ticket #3292: modern-tap2rpm-3292-4.patch

File modern-tap2rpm-3292-4.patch, 12.1 KB (added by TimAllen, 6 years ago)
  • twisted/scripts/tap2rpm.py

    diff --git a/twisted/scripts/tap2rpm.py b/twisted/scripts/tap2rpm.py
    index f3d2e0d..e531257 100755
    a b import tarfile 
    1010from StringIO import StringIO
    1111
    1212from twisted.python import usage, log
    13 from twisted.scripts import tap2deb
    1413
    1514
    1615#################################
    Release: 1 
    9594License:    Unknown
    9695Group:      Networking/Daemons
    9796Source:     %(tarfile_basename)s
    98 BuildRoot:  /var/tmp/%%{name}-%%{version}-root
     97BuildRoot:  %%{_tmppath}/%%{name}-%%{version}-root
    9998Requires:   /usr/bin/twistd
    10099BuildArch:  noarch
    101100
    class MyOptions(usage.Options): 
    143142    optFlags = [["unsigned", "u"], ['quiet', 'q']]
    144143    optParameters = [
    145144                     ["tapfile", "t", "twistd.tap"],
    146                      ["maintainer", "m", ""],
    147                      ["protocol", "p", ""],
    148                      ["description", "e", ""],
    149                      ["long_description", "l", ""],
     145                     ["maintainer", "m", "tap2rpm"],
     146                     ["protocol", "p", None],
     147                     ["description", "e", None],
     148                     ["long_description", "l",
     149                         "Automatically created by tap2rpm"],
    150150                     ["set-version", "V", "1.0"],
    151151                     ["rpmfile", "r", None],
    152152                     ["type", "y", "tap", "type of configuration: 'tap', 'xml, "
    class MyOptions(usage.Options): 
    160160                   "rpmfile":'_files -g "*.rpm"'}
    161161    #zsh_actionDescr = {"logfile":"log file name", "random":"random seed"}
    162162
     163    def postOptions(self):
     164        """
     165        Calculate the default values for certain command-line options.
     166        """
     167        # Options whose defaults depend on other parameters.
     168        if self['protocol'] is None:
     169            base_tapfile = os.path.basename(self['tapfile'])
     170            self['protocol'] = os.path.splitext(base_tapfile)[0]
     171        if self['description'] is None:
     172            self['description'] = "A TCP server for %s" % (self['protocol'],)
     173        if self['rpmfile'] is None:
     174            self['rpmfile'] = 'twisted-%s' % (self['protocol'],)
     175
     176        # Values that aren't options, but are calculated from options and are
     177        # handy to have around.
     178        self['twistd_option'] = type_dict[self['type']]
     179        self['release-name'] = '%s-%s' % (self['rpmfile'], self['set-version'])
     180
     181
    163182
    164183type_dict = {
    165184    'tap': 'file',
    type_dict = { 
    169188}
    170189
    171190
     191
    172192##########################
    173 def makeBuildDir(baseDir):
     193def makeBuildDir():
    174194    '''
    175195    Set up the temporary directory for building RPMs.
    176196
    def makeBuildDir(baseDir): 
    186206    os.makedirs(os.path.join(tmpDir, 'SOURCES'))
    187207    os.makedirs(os.path.join(tmpDir, 'SRPMS'))
    188208
     209    log.msg(format="Created RPM build structure in %(path)r",
     210            path=tmpDir)
    189211    return tmpDir
    190212
    191213
    192 ##########
    193 def run(options=None):
    194     #  parse options
    195     try:
    196         config = MyOptions()
    197         config.parseOptions(options)
    198     except usage.error, ue:
    199          sys.exit("%s: %s" % (sys.argv[0], ue))
    200214
    201     #  set up some useful local variables
    202     tap_file = config['tapfile']
    203     base_tap_file = os.path.basename(config['tapfile'])
    204     protocol = (config['protocol'] or os.path.splitext(base_tap_file)[0])
    205     rpm_file = config['rpmfile'] or 'twisted-'+protocol
    206     version = config['set-version']
    207     maintainer = config['maintainer']
    208     description = config['description'] or ('A TCP server for %(protocol)s' %
    209                                             vars())
    210     long_description = (config['long_description']
    211                         or "Automatically created by tap2rpm")
    212     twistd_option = type_dict[config['type']]
    213     date = time.strftime('%a %b %d %Y', time.localtime(time.time()))
    214     directory = rpm_file + '-' + version
    215     python_version = '%s.%s' % sys.version_info[:2]
    216 
    217     #  set up a blank maintainer if not present
    218     if not maintainer:
    219         maintainer = 'tap2rpm'
    220 
    221     #  create source archive directory
    222     tmp_dir = makeBuildDir('/var/tmp')
    223     source_dir = os.path.join(tmp_dir, directory)
    224     os.makedirs(source_dir)
    225 
    226     #  create source tar
    227     tarfile_name = source_dir + '.tar.gz'
    228     tarfile_basename = os.path.basename(tarfile_name)
    229     tarHandle = tarfile.open(tarfile_name, "w:gz")
    230 
    231     sourceDirInfo = tarfile.TarInfo(directory)
     215def setupBuildFiles(buildDir, config):
     216    """
     217    Create files required to build an RPM in the build directory.
     218    """
     219    # Create the source tarball in the SOURCES directory.
     220    tarballName = "%s.tar" % (config['release-name'],)
     221    tarballPath = os.path.join(buildDir, "SOURCES", tarballName)
     222    tarballHandle = tarfile.open(tarballPath, "w")
     223
     224    sourceDirInfo = tarfile.TarInfo(config['release-name'])
    232225    sourceDirInfo.type = tarfile.DIRTYPE
    233226    sourceDirInfo.mode = 0755
    234     tarHandle.addfile(sourceDirInfo)
     227    tarballHandle.addfile(sourceDirInfo)
    235228
    236     specFileInfo = tarfile.TarInfo(
    237             os.path.join(directory, '%s.spec' % rpm_file))
    238     specFileInfo.type = tarfile.REGTYPE
    239     specFileInfo.mode = 0644
    240     specFileRealData = specFileData % vars()
    241     specFileInfo.size = len(specFileRealData)
    242     tarHandle.addfile(specFileInfo, StringIO(specFileRealData))
     229    tapFileBase = os.path.basename(config['tapfile'])
    243230
    244231    initFileInfo = tarfile.TarInfo(
    245             os.path.join(directory, '%s.init' % rpm_file))
     232            os.path.join(
     233                config['release-name'],
     234                '%s.init' % config['rpmfile'],
     235            )
     236        )
    246237    initFileInfo.type = tarfile.REGTYPE
    247238    initFileInfo.mode = 0755
    248     initFileRealData = initFileData % vars()
     239    initFileRealData = initFileData % {
     240            'tap_file': tapFileBase,
     241            'rpm_file': config['release-name'],
     242            'twistd_option': config['twistd_option'],
     243        }
    249244    initFileInfo.size = len(initFileRealData)
    250     tarHandle.addfile(initFileInfo, StringIO(initFileRealData))
     245    tarballHandle.addfile(initFileInfo, StringIO(initFileRealData))
    251246
    252     tapFileHandle = open(tap_file, 'rb')
    253     tapFileInfo = tarHandle.gettarinfo(
    254             arcname=os.path.join(directory, os.path.basename(tap_file)),
     247    tapFileHandle = open(config['tapfile'], 'rb')
     248    tapFileInfo = tarballHandle.gettarinfo(
     249            arcname=os.path.join(config['release-name'], tapFileBase),
    255250            fileobj=tapFileHandle,
    256251        )
    257252    tapFileInfo.mode = 0644
    258     tarHandle.addfile(tapFileInfo, tapFileHandle)
     253    tarballHandle.addfile(tapFileInfo, tapFileHandle)
     254
     255    tarballHandle.close()
    259256
    260     tarHandle.close()
     257    log.msg(format="Created dummy source tarball %(tarballPath)r",
     258            tarballPath=tarballPath)
     259
     260    # Create the spec file in the SPECS directory.
     261    specName = "%s.spec" % (config['release-name'],)
     262    specPath = os.path.join(buildDir, "SPECS", specName)
     263    specHandle = open(specPath, "w")
     264    specFileRealData = specFileData % {
     265            'description': config['description'],
     266            'rpm_file': config['rpmfile'],
     267            'version': config['set-version'],
     268            'tarfile_basename': tarballName,
     269            'tap_file': tapFileBase,
     270            'date': time.strftime('%a %b %d %Y', time.localtime(time.time())),
     271            'maintainer': config['maintainer'],
     272            'long_description': config['long_description'],
     273        }
     274    specHandle.write(specFileRealData)
     275    specHandle.close()
     276
     277    log.msg(format="Created RPM spec file %(specPath)r",
     278            specPath=specPath)
     279
     280    return specPath
     281
     282
     283
     284def run(options=None):
     285    #  parse options
     286    try:
     287        config = MyOptions()
     288        config.parseOptions(options)
     289    except usage.error, ue:
     290         sys.exit("%s: %s" % (sys.argv[0], ue))
    261291
    262     print "Checking content of tarball %r before we hand it to rpmbuild..." % (
    263             tarfile_name)
    264     os.system('tar tzvf "%(tarfile_name)s"' % vars())
    265     print "done."
     292    #  create RPM build environment
     293    tmp_dir = makeBuildDir()
     294    specPath = setupBuildFiles(tmp_dir, config)
    266295
    267296    #  build rpm
    268297    job = subprocess.Popen([
    269             "strace",
    270             "-s", "1000",
    271298            "rpmbuild",
    272299            "-vv",
    273300            "--define", "_topdir %s" % (tmp_dir,),
    274             "-ta", tarfile_name,
     301            "-ba", specPath,
    275302        ], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    276303    stdout, _ = job.communicate()
    277304
    278305    # If there was a problem, show people what it was.
    279     #if job.returncode != 0:
    280     #    print stdout
    281     print stdout
     306    if job.returncode != 0:
     307        print stdout
    282308   
    283309    #  copy the RPMs to the local directory
    284     log.msg(os.listdir(tmp_dir))
    285     log.msg(os.listdir(os.path.join(tmp_dir, "RPMS")))
    286     log.msg(os.listdir(os.path.join(tmp_dir, "SRPMS")))
    287     log.msg(os.listdir(os.path.join(tmp_dir, "RPMS", "noarch")))
    288310    rpm_path = glob.glob(os.path.join(tmp_dir, 'RPMS', 'noarch', '*'))[0]
    289311    srpm_path = glob.glob(os.path.join(tmp_dir, 'SRPMS', '*'))[0]
    290312    if not config['quiet']:
  • twisted/scripts/test/test_tap2rpm.py

    diff --git a/twisted/scripts/test/test_tap2rpm.py b/twisted/scripts/test/test_tap2rpm.py
    index edabe32..c4b4df2 100644
    a b class TestTap2RPM(TestCase): 
    153153        return d
    154154
    155155
     156    def test_optionDefaults(self):
     157        """
     158        Commandline options should default to sensible values.
     159
     160        "sensible" here is defined as "the same values that previous versions
     161        defaulted to".
     162        """
     163        config = tap2rpm.MyOptions()
     164        config.parseOptions([])
     165
     166        self.assertEquals(config['tapfile'], 'twistd.tap')
     167        self.assertEquals(config['maintainer'], 'tap2rpm')
     168        self.assertEquals(config['protocol'], 'twistd')
     169        self.assertEquals(config['description'], 'A TCP server for twistd')
     170        self.assertEquals(config['long_description'],
     171                'Automatically created by tap2rpm')
     172        self.assertEquals(config['set-version'], '1.0')
     173        self.assertEquals(config['rpmfile'], 'twisted-twistd')
     174        self.assertEquals(config['type'], 'tap')
     175        self.assertEquals(config['quiet'], False)
     176        self.assertEquals(config['twistd_option'], 'file')
     177        self.assertEquals(config['release-name'], 'twisted-twistd-1.0')
     178
     179
     180    def test_protocolCalculatedFromTapFile(self):
     181        """
     182        The protocol name defaults to a value based on the tapfile value.
     183        """
     184        config = tap2rpm.MyOptions()
     185        config.parseOptions(['--tapfile', 'pancakes.tap'])
     186
     187        self.assertEquals(config['tapfile'], 'pancakes.tap')
     188        self.assertEquals(config['protocol'], 'pancakes')
     189
     190
     191    def test_optionsDefaultToProtocolValue(self):
     192        """
     193        Many options default to a value calculated from the protocol name.
     194        """
     195        config = tap2rpm.MyOptions()
     196        config.parseOptions([
     197                '--tapfile', 'sausages.tap',
     198                '--protocol', 'eggs',
     199            ])
     200
     201        self.assertEquals(config['tapfile'], 'sausages.tap')
     202        self.assertEquals(config['maintainer'], 'tap2rpm')
     203        self.assertEquals(config['protocol'], 'eggs')
     204        self.assertEquals(config['description'], 'A TCP server for eggs')
     205        self.assertEquals(config['long_description'],
     206                'Automatically created by tap2rpm')
     207        self.assertEquals(config['set-version'], '1.0')
     208        self.assertEquals(config['rpmfile'], 'twisted-eggs')
     209        self.assertEquals(config['type'], 'tap')
     210        self.assertEquals(config['quiet'], False)
     211        self.assertEquals(config['twistd_option'], 'file')
     212        self.assertEquals(config['release-name'], 'twisted-eggs-1.0')
     213
     214
     215    def test_releaseNameDefaultsToRpmfileValue(self):
     216        """
     217        The release-name option is calculated from rpmfile and set-version.
     218        """
     219        config = tap2rpm.MyOptions()
     220        config.parseOptions([
     221                "--rpmfile", "beans",
     222                "--set-version", "1.2.3",
     223            ])
     224
     225        self.assertEquals(config['release-name'], 'beans-1.2.3')
     226
     227
    156228    def test_basicOperation(self):
    157229        """
    158230        Calling tap2rpm should produce an RPM and SRPM with default metadata.