aboutsummaryrefslogtreecommitdiffstats
path: root/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/scripts/tap2rpm.py
blob: 30149b7d67026316ebca9a80fc02904dc33415fe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
# -*- test-case-name: twisted.scripts.test.test_tap2rpm -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

import sys, os, shutil, time, glob
import subprocess
import tempfile
import tarfile
from StringIO import StringIO
import warnings

from twisted.python import usage, log, versions, deprecate


#################################
#  data that goes in /etc/inittab
initFileData = '''\
#!/bin/sh
#
#  Startup script for a Twisted service.
#
#  chkconfig: - 85 15
#  description: Start-up script for the Twisted service "%(tap_file)s".

PATH=/usr/bin:/bin:/usr/sbin:/sbin

pidfile=/var/run/%(rpm_file)s.pid
rundir=/var/lib/twisted-taps/%(rpm_file)s/
file=/etc/twisted-taps/%(tap_file)s
logfile=/var/log/%(rpm_file)s.log

#  load init function library
. /etc/init.d/functions

[ -r /etc/default/%(rpm_file)s ] && . /etc/default/%(rpm_file)s

#  check for required files
if [ ! -x /usr/bin/twistd ]
then
        echo "$0: Aborting, no /usr/bin/twistd found"
        exit 0
fi
if [ ! -r "$file" ]
then
        echo "$0: Aborting, no file $file found."
        exit 0
fi

#  set up run directory if necessary
if [ ! -d "${rundir}" ]
then
        mkdir -p "${rundir}"
fi


case "$1" in
        start)
                echo -n "Starting %(rpm_file)s: twistd"
                daemon twistd  \\
                                --pidfile=$pidfile \\
                                --rundir=$rundir \\
                                --%(twistd_option)s=$file \\
                                --logfile=$logfile
                status %(rpm_file)s
                ;;

        stop)
                echo -n "Stopping %(rpm_file)s: twistd"
                kill `cat "${pidfile}"`
                status %(rpm_file)s
                ;;

        restart)
                "${0}" stop
                "${0}" start
                ;;

    *)
                echo "Usage: ${0} {start|stop|restart|}" >&2
                exit 1
                ;;
esac

exit 0
'''

#######################################
#  the data for creating the spec file
specFileData = '''\
Summary:    %(description)s
Name:       %(rpm_file)s
Version:    %(version)s
Release:    1
License:    Unknown
Group:      Networking/Daemons
Source:     %(tarfile_basename)s
BuildRoot:  %%{_tmppath}/%%{name}-%%{version}-root
Requires:   /usr/bin/twistd
BuildArch:  noarch

%%description
%(long_description)s

%%prep
%%setup
%%build

%%install
[ ! -z "$RPM_BUILD_ROOT" -a "$RPM_BUILD_ROOT" != '/' ] \
                && rm -rf "$RPM_BUILD_ROOT"
mkdir -p "$RPM_BUILD_ROOT"/etc/twisted-taps
mkdir -p "$RPM_BUILD_ROOT"/etc/init.d
mkdir -p "$RPM_BUILD_ROOT"/var/lib/twisted-taps
cp "%(tap_file)s" "$RPM_BUILD_ROOT"/etc/twisted-taps/
cp "%(rpm_file)s.init" "$RPM_BUILD_ROOT"/etc/init.d/"%(rpm_file)s"

%%clean
[ ! -z "$RPM_BUILD_ROOT" -a "$RPM_BUILD_ROOT" != '/' ] \
                && rm -rf "$RPM_BUILD_ROOT"

%%post
/sbin/chkconfig --add %(rpm_file)s
/sbin/chkconfig --level 35 %(rpm_file)s
/etc/init.d/%(rpm_file)s start

%%preun
/etc/init.d/%(rpm_file)s stop
/sbin/chkconfig --del %(rpm_file)s

%%files
%%defattr(-,root,root)
%%attr(0755,root,root) /etc/init.d/%(rpm_file)s
%%attr(0660,root,root) /etc/twisted-taps/%(tap_file)s

%%changelog
* %(date)s %(maintainer)s
- Created by tap2rpm: %(rpm_file)s (%(version)s)
'''

###############################
class MyOptions(usage.Options):
    optFlags = [['quiet', 'q']]
    optParameters = [
                     ["tapfile", "t", "twistd.tap"],
                     ["maintainer", "m", "tap2rpm"],
                     ["protocol", "p", None],
                     ["description", "e", None],
                     ["long_description", "l",
                         "Automatically created by tap2rpm"],
                     ["set-version", "V", "1.0"],
                     ["rpmfile", "r", None],
                     ["type", "y", "tap", "type of configuration: 'tap', 'xml, "
                      "'source' or 'python'"],
                    ]

    compData = usage.Completions(
        optActions={"type": usage.CompleteList(["tap", "xml", "source",
                                                "python"]),
                    "rpmfile": usage.CompleteFiles("*.rpm")}
        )

    def postOptions(self):
        """
        Calculate the default values for certain command-line options.
        """
        # Options whose defaults depend on other parameters.
        if self['protocol'] is None:
            base_tapfile = os.path.basename(self['tapfile'])
            self['protocol'] = os.path.splitext(base_tapfile)[0]
        if self['description'] is None:
            self['description'] = "A TCP server for %s" % (self['protocol'],)
        if self['rpmfile'] is None:
            self['rpmfile'] = 'twisted-%s' % (self['protocol'],)

        # Values that aren't options, but are calculated from options and are
        # handy to have around.
        self['twistd_option'] = type_dict[self['type']]
        self['release-name'] = '%s-%s' % (self['rpmfile'], self['set-version'])


    def opt_unsigned(self):
        """
        Generate an unsigned rather than a signed RPM. (DEPRECATED; unsigned
        is the default)
        """
        msg = deprecate.getDeprecationWarningString(
            self.opt_unsigned, versions.Version("Twisted", 12, 1, 0))
        warnings.warn(msg, category=DeprecationWarning, stacklevel=2)

    # Maintain the -u short flag
    opt_u = opt_unsigned


type_dict = {
    'tap': 'file',
    'python': 'python',
    'source': 'source',
    'xml': 'xml',
}



##########################
def makeBuildDir():
    """
    Set up the temporary directory for building RPMs.

    Returns: buildDir, a randomly-named subdirectory of baseDir.
    """
    tmpDir = tempfile.mkdtemp()
    #  set up initial directory contents
    os.makedirs(os.path.join(tmpDir, 'RPMS', 'noarch'))
    os.makedirs(os.path.join(tmpDir, 'SPECS'))
    os.makedirs(os.path.join(tmpDir, 'BUILD'))
    os.makedirs(os.path.join(tmpDir, 'SOURCES'))
    os.makedirs(os.path.join(tmpDir, 'SRPMS'))

    log.msg(format="Created RPM build structure in %(path)r",
            path=tmpDir)
    return tmpDir



def setupBuildFiles(buildDir, config):
    """
    Create files required to build an RPM in the build directory.
    """
    # Create the source tarball in the SOURCES directory.
    tarballName = "%s.tar" % (config['release-name'],)
    tarballPath = os.path.join(buildDir, "SOURCES", tarballName)
    tarballHandle = tarfile.open(tarballPath, "w")

    sourceDirInfo = tarfile.TarInfo(config['release-name'])
    sourceDirInfo.type = tarfile.DIRTYPE
    sourceDirInfo.mode = 0755
    tarballHandle.addfile(sourceDirInfo)

    tapFileBase = os.path.basename(config['tapfile'])

    initFileInfo = tarfile.TarInfo(
            os.path.join(
                config['release-name'],
                '%s.init' % config['rpmfile'],
            )
        )
    initFileInfo.type = tarfile.REGTYPE
    initFileInfo.mode = 0755
    initFileRealData = initFileData % {
            'tap_file': tapFileBase,
            'rpm_file': config['release-name'],
            'twistd_option': config['twistd_option'],
        }
    initFileInfo.size = len(initFileRealData)
    tarballHandle.addfile(initFileInfo, StringIO(initFileRealData))

    tapFileHandle = open(config['tapfile'], 'rb')
    tapFileInfo = tarballHandle.gettarinfo(
            arcname=os.path.join(config['release-name'], tapFileBase),
            fileobj=tapFileHandle,
        )
    tapFileInfo.mode = 0644
    tarballHandle.addfile(tapFileInfo, tapFileHandle)

    tarballHandle.close()

    log.msg(format="Created dummy source tarball %(tarballPath)r",
            tarballPath=tarballPath)

    # Create the spec file in the SPECS directory.
    specName = "%s.spec" % (config['release-name'],)
    specPath = os.path.join(buildDir, "SPECS", specName)
    specHandle = open(specPath, "w")
    specFileRealData = specFileData % {
            'description': config['description'],
            'rpm_file': config['rpmfile'],
            'version': config['set-version'],
            'tarfile_basename': tarballName,
            'tap_file': tapFileBase,
            'date': time.strftime('%a %b %d %Y', time.localtime(time.time())),
            'maintainer': config['maintainer'],
            'long_description': config['long_description'],
        }
    specHandle.write(specFileRealData)
    specHandle.close()

    log.msg(format="Created RPM spec file %(specPath)r",
            specPath=specPath)

    return specPath



def run(options=None):
    #  parse options
    try:
        config = MyOptions()
        config.parseOptions(options)
    except usage.error, ue:
         sys.exit("%s: %s" % (sys.argv[0], ue))

    #  create RPM build environment
    tmpDir = makeBuildDir()
    specPath = setupBuildFiles(tmpDir, config)

    #  build rpm
    job = subprocess.Popen([
            "rpmbuild",
            "-vv",
            "--define", "_topdir %s" % (tmpDir,),
            "-ba", specPath,
        ], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    stdout, _ = job.communicate()

    # If there was a problem, show people what it was.
    if job.returncode != 0:
        print stdout

    #  copy the RPMs to the local directory
    rpmPath = glob.glob(os.path.join(tmpDir, 'RPMS', 'noarch', '*'))[0]
    srpmPath = glob.glob(os.path.join(tmpDir, 'SRPMS', '*'))[0]
    if not config['quiet']:
        print 'Writing "%s"...' % os.path.basename(rpmPath)
    shutil.copy(rpmPath, '.')
    if not config['quiet']:
        print 'Writing "%s"...' % os.path.basename(srpmPath)
    shutil.copy(srpmPath, '.')

    #  remove the build directory
    shutil.rmtree(tmpDir)

    return [os.path.basename(rpmPath), os.path.basename(srpmPath)]