aboutsummaryrefslogtreecommitdiffstats
path: root/lib/python2.7/site-packages/buildbot-0.8.8-py2.7.egg/buildbot/steps/source/p4.py
blob: b6d47daf130acf123c24a66e6ab19d629f83ab28 (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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
# This file is part of Buildbot.  Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
# Portions Copyright 2013 Bad Dog Consulting

import re
import os

from twisted.python import log
from twisted.internet import defer
from buildbot import interfaces, config
from buildbot.process import buildstep
from buildbot.steps.source import Source
from buildbot.interfaces import BuildSlaveTooOldError
from buildbot.process.properties import Interpolate
from types import StringType


# Notes:
#  see
#  http://perforce.com/perforce/doc.current/manuals/cmdref/o.gopts.html#1040647
#   for getting p4 command to output marshalled python dictionaries as output
#   for commands.
#   Perhaps switch to using 'p4 -G' :  From URL above:
#   -G Causes all output (and batch input for form commands with -i) to be
#   formatted as marshalled Python dictionary objects. This is most often used
#   when scripting.

debug_logging = False


class P4(Source):
    """Perform Perforce checkout/update operations."""

    name = 'p4'

    renderables = ['p4base', 'p4client', 'p4viewspec', 'p4branch']
    possible_modes = ('incremental', 'full')

    def __init__(self, mode='incremental',
                 method=None, p4base=None, p4branch=None,
                 p4port=None, p4user=None,
                 p4passwd=None, p4extra_views=(), p4line_end='local',
                 p4viewspec=None,
                 p4client=Interpolate('buildbot_%(prop:slavename)s_%(prop:buildername)s'),
                 p4bin='p4',
                 **kwargs):
        self.method = method
        self.mode = mode
        self.p4branch = p4branch
        self.p4bin = p4bin
        self.p4base = p4base
        self.p4port = p4port
        self.p4user = p4user
        self.p4passwd = p4passwd
        self.p4extra_views = p4extra_views
        self.p4viewspec = p4viewspec
        self.p4line_end = p4line_end
        self.p4client = p4client

        Source.__init__(self, **kwargs)

        if self.mode not in self.possible_modes:
            config.error("mode %s is not one of %s" % (self.mode, self.possible_modes))

        if not p4viewspec and p4base is None:
            config.error("You must provide p4base or p4viewspec")

        if p4viewspec and (p4base or p4branch or p4extra_views):
            config.error("Either provide p4viewspec or p4base and p4branch (and optionally p4extra_views")

        if p4viewspec and type(p4viewspec) is StringType:
            config.error("p4viewspec must not be a string, and should be a sequence of 2 element sequences")

        if not interfaces.IRenderable.providedBy(p4base) and p4base and p4base.endswith('/'):
            config.error('p4base should not end with a trailing / [p4base = %s]' % p4base)

        if not interfaces.IRenderable.providedBy(p4branch) and p4branch and p4branch.endswith('/'):
            config.error('p4branch should not end with a trailing / [p4branch = %s]' % p4branch)

        if (p4branch or p4extra_views) and not p4base:
            config.error('If you specify either p4branch or p4extra_views you must also specify p4base')

    def startVC(self, branch, revision, patch):
        if debug_logging:
            log.msg('in startVC')

        self.revision = revision
        self.method = self._getMethod()
        self.stdio_log = self.addLogForRemoteCommands("stdio")

        d = self.checkP4()

        def checkInstall(p4Installed):
            if not p4Installed:
                raise BuildSlaveTooOldError("p4 is not installed on slave")
            return 0
        d.addCallback(checkInstall)

        if self.mode == 'full':
            d.addCallback(self.full)
        elif self.mode == 'incremental':
            d.addCallback(self.incremental)

        d.addCallback(self.parseGotRevision)
        d.addCallback(self.finish)
        d.addErrback(self.failed)
        return d

    @defer.inlineCallbacks
    def full(self, _):
        if debug_logging:
            log.msg("P4:full()..")

        # First we need to create the client
        yield self._createClientSpec()

        # Then p4 sync #none
        yield self._dovccmd(['sync', '#none'])

        # Then remove directory.
        yield self.runRmdir(self.workdir)

        # Then we need to sync the client
        if self.revision:
            if debug_logging:
                log.msg("P4: full() sync command based on :base:%s changeset:%d", self.p4base, int(self.revision))
            yield self._dovccmd(['sync', '%s...@%d' % (self.p4base, int(self.revision))], collectStdout=True)
        else:
            if debug_logging:
                log.msg("P4: full() sync command based on :base:%s no revision", self.p4base)
            yield self._dovccmd(['sync'], collectStdout=True)

        if debug_logging:
            log.msg("P4: full() sync done.")

    @defer.inlineCallbacks
    def incremental(self, _):
        if debug_logging:
            log.msg("P4:incremental()")

        # First we need to create the client
        yield self._createClientSpec()

        # and plan to do a checkout
        command = ['sync', ]

        if self.revision:
            command.extend(['%s...@%d' % (self.p4base, int(self.revision))])

        if debug_logging:
            log.msg("P4:incremental() command:%s revision:%s", command, self.revision)
        yield self._dovccmd(command)

    def finish(self, res):
        d = defer.succeed(res)

        def _gotResults(results):
            self.setStatus(self.cmd, results)
            return results
        d.addCallback(_gotResults)
        d.addCallbacks(self.finished, self.checkDisconnect)
        return d

    def _buildVCCommand(self, doCommand):
        assert doCommand, "No command specified"

        command = [self.p4bin, ]

        if self.p4port:
            command.extend(['-p', self.p4port])
        if self.p4user:
            command.extend(['-u', self.p4user])
        if self.p4passwd:
            # Need to find out if there's a way to obfuscate this
            command.extend(['-P', self.p4passwd])
        if self.p4client:
            command.extend(['-c', self.p4client])

        command.extend(doCommand)

        command = [c.encode('utf-8') for c in command]
        return command

    def _dovccmd(self, command, collectStdout=False, initialStdin=None):
        command = self._buildVCCommand(command)

        if debug_logging:
            log.msg("P4:_dovccmd():workdir->%s" % self.workdir)
        cmd = buildstep.RemoteShellCommand(self.workdir, command,
                                           env=self.env,
                                           logEnviron=self.logEnviron,
                                           collectStdout=collectStdout,
                                           initialStdin=initialStdin,)
        cmd.useLog(self.stdio_log, False)
        if debug_logging:
            log.msg("Starting p4 command : p4 %s" % (" ".join(command),))

        d = self.runCommand(cmd)

        def evaluateCommand(cmd):
            if cmd.rc != 0:
                if debug_logging:
                    log.msg("P4:_dovccmd():Source step failed while running command %s" % cmd)
                raise buildstep.BuildStepFailed()
            if collectStdout:
                return cmd.stdout
            else:
                return cmd.rc
        d.addCallback(lambda _: evaluateCommand(cmd))
        return d

    def _getMethod(self):
        if self.method is not None and self.mode != 'incremental':
            return self.method
        elif self.mode == 'incremental':
            return None
        elif self.method is None and self.mode == 'full':
            return 'fresh'

    def _sourcedirIsUpdatable(self):
        # In general you should always be able to write to the directory
        # You just specified as the root of your client
        # So just return.
        # If we find a case where this is no longer true, then this
        # needs to be implemented
        return defer.succeed(True)

    @defer.inlineCallbacks
    def _createClientSpec(self):
        builddir = self.getProperty('builddir')

        if debug_logging:
            log.msg("P4:_createClientSpec() builddir:%s" % builddir)
            log.msg("P4:_createClientSpec() SELF.workdir:%s" % self.workdir)

        prop_dict = self.getProperties().asDict()
        prop_dict['p4client'] = self.p4client

        client_spec = ''
        client_spec += "Client: %s\n\n" % self.p4client
        client_spec += "Owner: %s\n\n" % self.p4user
        client_spec += "Description:\n\tCreated by %s\n\n" % self.p4user
        client_spec += "Root:\t%s\n\n" % os.path.join(builddir, self.workdir)
        client_spec += "Options:\tallwrite rmdir\n\n"
        if self.p4line_end:
            client_spec += "LineEnd:\t%s\n\n" % self.p4line_end
        else:
            client_spec += "LineEnd:\tlocal\n\n"

        # Setup a view
        client_spec += "View:\n"

        if self.p4viewspec:
            # uses only p4viewspec array of tuples to build view
            # If the user specifies a viewspec via an array of tuples then
            # Ignore any specified p4base,p4branch, and/or p4extra_views
            for k, v in self.p4viewspec:
                if debug_logging:
                    log.msg('P4:_createClientSpec():key:%s value:%s' % (k, v))
                client_spec += '\t%s... //%s/%s...\n' % (k, self.p4client, v)
        else:
            # Uses p4base, p4branch, p4extra_views
            client_spec += "\t%s" % (self.p4base)

            if self.p4branch:
                client_spec += "/%s" % (self.p4branch)

            client_spec += "/... //%s/...\n" % (self.p4client)

            if self.p4extra_views:
                for k, v in self.p4extra_views:
                    client_spec += "\t%s/... //%s/%s/...\n" % (k, self.p4client, v)

        client_spec = client_spec.encode('utf-8')  # resolve unicode issues
        if debug_logging:
            log.msg(client_spec)

        stdout = yield self._dovccmd(['client', '-i'], collectStdout=True, initialStdin=client_spec)
        mo = re.search(r'Client (\S+) (.+)$', stdout, re.M)
        defer.returnValue(mo and (mo.group(2) == 'saved.' or mo.group(2) == 'not changed.'))

    def parseGotRevision(self, _):
        command = self._buildVCCommand(['changes', '-m1', '#have'])

        cmd = buildstep.RemoteShellCommand(self.workdir, command,
                                           env=self.env,
                                           logEnviron=self.logEnviron,
                                           collectStdout=True)
        cmd.useLog(self.stdio_log, False)
        d = self.runCommand(cmd)

        def _setrev(_):
            stdout = cmd.stdout.strip()
            # Example output from p4 changes -m1 #have
            #     Change 212798 on 2012/04/13 by user@user-unix-bldng2 'change to pickup build'
            revision = stdout.split()[1]
            try:
                int(revision)
            except ValueError:
                msg = ("p4.parseGotRevision unable to parse output "
                       "of 'p4 changes -m1 \"#have\"': '%s'" % stdout)
                log.msg(msg)
                raise buildstep.BuildStepFailed()

            if debug_logging:
                log.msg("Got p4 revision %s" % (revision,))
            self.updateSourceProperty('got_revision', revision)
            return 0
        d.addCallback(lambda _: _setrev(cmd.rc))
        return d

    def purge(self, ignore_ignores):
        """Delete everything that shown up on status."""
        command = ['sync', '#none']
        if ignore_ignores:
            command.append('--no-ignore')
        d = self._dovccmd(command, collectStdout=True)

        # add deferred to rm tree

        # then add defer to sync to revision
        return d

    def checkP4(self):
        cmd = buildstep.RemoteShellCommand(self.workdir, ['p4', '-V'],
                                           env=self.env,
                                           logEnviron=self.logEnviron)
        cmd.useLog(self.stdio_log, False)
        d = self.runCommand(cmd)

        def evaluate(cmd):
            if cmd.rc != 0:
                return False
            return True
        d.addCallback(lambda _: evaluate(cmd))
        return d

    def computeSourceRevision(self, changes):
        if not changes or None in [c.revision for c in changes]:
            return None
        lastChange = max([int(c.revision) for c in changes])
        return lastChange