download.py 18 KB
Newer Older
1
# Copyright (c) 2009, 2011 Google Inc. All rights reserved.
2
3
4
5
6
# Copyright (c) 2009 Apple Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
7
#
8
9
10
11
12
13
14
15
16
#     * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
#     * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
17
#
18
19
20
21
22
23
24
25
26
27
28
29
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

30
31
import logging

32
from webkitpy.tool import steps
33

34
35
from webkitpy.common.checkout.changelog import ChangeLog
from webkitpy.common.config import urls
36
from webkitpy.common.system.executive import ScriptError
37
from webkitpy.tool.commands.abstractsequencedcommand import AbstractSequencedCommand
38
from webkitpy.tool.commands.stepsequence import StepSequence
39
from webkitpy.tool.comments import bug_comment_from_commit_text
40
from webkitpy.tool.grammar import pluralize
41
from webkitpy.tool.multicommandtool import Command
42
43

_log = logging.getLogger(__name__)
44
45


46
47
48
49
class Clean(AbstractSequencedCommand):
    name = "clean"
    help_text = "Clean the working copy"
    steps = [
50
        steps.DiscardLocalChanges,
51
52
53
54
55
56
    ]

    def _prepare_state(self, options, args, tool):
        options.force_clean = True


57
58
59
60
class Update(AbstractSequencedCommand):
    name = "update"
    help_text = "Update working copy (used internally)"
    steps = [
61
        steps.DiscardLocalChanges,
62
63
64
65
        steps.Update,
    ]


66
class Build(AbstractSequencedCommand):
67
68
69
    name = "build"
    help_text = "Update working copy and build"
    steps = [
70
        steps.DiscardLocalChanges,
71
72
        steps.Update,
        steps.Build,
73
74
    ]

75
76
77
    def _prepare_state(self, options, args, tool):
        options.build = True

78

79
class BuildAndTest(AbstractSequencedCommand):
80
81
82
    name = "build-and-test"
    help_text = "Update working copy, build, and run the tests"
    steps = [
83
        steps.DiscardLocalChanges,
84
85
86
        steps.Update,
        steps.Build,
        steps.RunTests,
87
88
89
    ]


90
class Land(AbstractSequencedCommand):
91
    name = "land"
92
93
    help_text = "Land the current working directory diff and updates the associated bug if any"
    argument_names = "[BUGID]"
94
    show_in_main_help = True
95
    steps = [
96
        steps.AddSvnMimetypeForPng,
97
        steps.UpdateChangeLogsWithReviewer,
98
        steps.ValidateReviewer,
99
        steps.ValidateChangeLogs, # We do this after UpdateChangeLogsWithReviewer to avoid not having to cache the diff twice.
100
101
102
103
        steps.Build,
        steps.RunTests,
        steps.Commit,
        steps.CloseBugForLandDiff,
104
    ]
105
    long_help = """land commits the current working copy diff (just as svn or git commit would).
106
land will NOT build and run the tests before committing, but you can use the --build option for that.
107
If a bug id is provided, or one can be found in the ChangeLog land will update the bug after committing."""
108

109
    def _prepare_state(self, options, args, tool):
110
        changed_files = self._tool.scm().changed_files(options.git_commit)
111
        return {
112
113
            "changed_files": changed_files,
            "bug_id": (args and args[0]) or tool.checkout().bug_id_for_this_commit(options.git_commit, changed_files),
114
115
116
        }


117
118
119
class LandCowhand(AbstractSequencedCommand):
    # Gender-blind term for cowboy, see: http://en.wiktionary.org/wiki/cowhand
    name = "land-cowhand"
120
121
122
123
    help_text = "Prepares a ChangeLog and lands the current working directory diff."
    steps = [
        steps.PrepareChangeLog,
        steps.EditChangeLog,
124
        steps.CheckStyle,
125
126
127
128
        steps.ConfirmDiff,
        steps.Build,
        steps.RunTests,
        steps.Commit,
129
        steps.CloseBugForLandDiff,
130
131
    ]

132
133
134
    def _prepare_state(self, options, args, tool):
        options.check_style_filter = "-changelog"

135

136
137
138
139
140
141
class LandCowboy(LandCowhand):
    name = "land-cowboy"

    def _prepare_state(self, options, args, tool):
        _log.warning("land-cowboy is deprecated, use land-cowhand instead.")
        LandCowhand._prepare_state(self, options, args, tool)
142
143


144
145
146
147
148
149
150
151
class CheckStyleLocal(AbstractSequencedCommand):
    name = "check-style-local"
    help_text = "Run check-webkit-style on the current working directory diff"
    steps = [
        steps.CheckStyle,
    ]


152
class AbstractPatchProcessingCommand(Command):
153
154
155
    # Subclasses must implement the methods below.  We don't declare them here
    # because we want to be able to implement them with mix-ins.
    #
156
    # pylint: disable=E1101
157
158
    # def _fetch_list_of_patches_to_process(self, options, args, tool):
    # def _prepare_to_process(self, options, args, tool):
159
    # def _process_patch(self, options, args, tool):
160
161
162
163
164

    @staticmethod
    def _collect_patches_by_bug(patches):
        bugs_to_patches = {}
        for patch in patches:
165
            bugs_to_patches[patch.bug_id()] = bugs_to_patches.get(patch.bug_id(), []) + [patch]
166
167
168
169
170
171
172
173
        return bugs_to_patches

    def execute(self, options, args, tool):
        self._prepare_to_process(options, args, tool)
        patches = self._fetch_list_of_patches_to_process(options, args, tool)

        # It's nice to print out total statistics.
        bugs_to_patches = self._collect_patches_by_bug(patches)
174
        _log.info("Processing %s from %s." % (pluralize("patch", len(patches)), pluralize("bug", len(bugs_to_patches))))
175
176
177
178
179

        for patch in patches:
            self._process_patch(patch, options, args, tool)


180
181
182
class AbstractPatchSequencingCommand(AbstractPatchProcessingCommand):
    prepare_steps = None
    main_steps = None
183

184
    def __init__(self):
185
        options = []
186
187
188
        self._prepare_sequence = StepSequence(self.prepare_steps)
        self._main_sequence = StepSequence(self.main_steps)
        options = sorted(set(self._prepare_sequence.options() + self._main_sequence.options()))
189
        AbstractPatchProcessingCommand.__init__(self, options)
190
191

    def _prepare_to_process(self, options, args, tool):
192
193
194
195
196
197
        try:
            self.state = self._prepare_state(options, args, tool)
        except ScriptError, e:
            _log.error(e.message_with_output())
            self._exit(e.exit_code or 2)
        self._prepare_sequence.run_and_handle_errors(tool, options, self.state)
198
199

    def _process_patch(self, patch, options, args, tool):
200
201
202
        state = {}
        state.update(self.state or {})
        state["patch"] = patch
203
        self._main_sequence.run_and_handle_errors(tool, options, state)
204

205
206
207
    def _prepare_state(self, options, args, tool):
        return None

208

209
210
class ProcessAttachmentsMixin(object):
    def _fetch_list_of_patches_to_process(self, options, args, tool):
211
        return map(lambda patch_id: tool.bugs.fetch_attachment(patch_id), args)
212
213
214
215
216
217


class ProcessBugsMixin(object):
    def _fetch_list_of_patches_to_process(self, options, args, tool):
        all_patches = []
        for bug_id in args:
218
            patches = tool.bugs.fetch_bug(bug_id).reviewed_patches()
219
            _log.info("%s found on bug %s." % (pluralize("reviewed patch", len(patches)), bug_id))
220
            all_patches += patches
221
        if not all_patches:
222
            _log.info("No reviewed patches found, looking for unreviewed patches.")
223
224
            for bug_id in args:
                patches = tool.bugs.fetch_bug(bug_id).patches()
225
                _log.info("%s found on bug %s." % (pluralize("patch", len(patches)), bug_id))
226
                all_patches += patches
227
228
229
        return all_patches


eric@webkit.org's avatar
eric@webkit.org committed
230
231
232
233
234
235
236
class ProcessURLsMixin(object):
    def _fetch_list_of_patches_to_process(self, options, args, tool):
        all_patches = []
        for url in args:
            bug_id = urls.parse_bug_id(url)
            if bug_id:
                patches = tool.bugs.fetch_bug(bug_id).patches()
237
                _log.info("%s found on bug %s." % (pluralize("patch", len(patches)), bug_id))
eric@webkit.org's avatar
eric@webkit.org committed
238
239
240
241
242
243
244
245
246
                all_patches += patches

            attachment_id = urls.parse_attachment_id(url)
            if attachment_id:
                all_patches += tool.bugs.fetch_attachment(attachment_id)

        return all_patches


247
class CheckStyle(AbstractPatchSequencingCommand, ProcessAttachmentsMixin):
248
    name = "check-style"
249
250
    help_text = "Run check-webkit-style on the specified attachments"
    argument_names = "ATTACHMENT_ID [ATTACHMENT_IDS]"
251
    main_steps = [
252
        steps.DiscardLocalChanges,
253
254
255
        steps.Update,
        steps.ApplyPatch,
        steps.CheckStyle,
256
    ]
257
258


259
class BuildAttachment(AbstractPatchSequencingCommand, ProcessAttachmentsMixin):
260
    name = "build-attachment"
261
262
    help_text = "Apply and build patches from bugzilla"
    argument_names = "ATTACHMENT_ID [ATTACHMENT_IDS]"
263
    main_steps = [
264
        steps.DiscardLocalChanges,
265
266
267
        steps.Update,
        steps.ApplyPatch,
        steps.Build,
268
    ]
269

270

271
272
273
274
275
class BuildAndTestAttachment(AbstractPatchSequencingCommand, ProcessAttachmentsMixin):
    name = "build-and-test-attachment"
    help_text = "Apply, build, and test patches from bugzilla"
    argument_names = "ATTACHMENT_ID [ATTACHMENT_IDS]"
    main_steps = [
276
        steps.DiscardLocalChanges,
277
278
279
280
281
282
283
        steps.Update,
        steps.ApplyPatch,
        steps.Build,
        steps.RunTests,
    ]


284
285
class AbstractPatchApplyingCommand(AbstractPatchSequencingCommand):
    prepare_steps = [
286
        steps.EnsureLocalCommitIfNeeded,
287
        steps.CleanWorkingDirectory,
288
        steps.Update,
289
290
    ]
    main_steps = [
291
        steps.ApplyPatchWithLocalCommit,
292
    ]
293
294
    long_help = """Updates the working copy.
Downloads and applies the patches, creating local commits if necessary."""
295
296


297
class ApplyAttachment(AbstractPatchApplyingCommand, ProcessAttachmentsMixin):
298
    name = "apply-attachment"
299
300
    help_text = "Apply an attachment to the local working directory"
    argument_names = "ATTACHMENT_ID [ATTACHMENT_IDS]"
301
302
303
    show_in_main_help = True


304
305
class ApplyFromBug(AbstractPatchApplyingCommand, ProcessBugsMixin):
    name = "apply-from-bug"
306
307
    help_text = "Apply reviewed patches from provided bugs to the local working directory"
    argument_names = "BUGID [BUGIDS]"
308
309
310
    show_in_main_help = True


311
312
class ApplyWatchList(AbstractPatchSequencingCommand, ProcessAttachmentsMixin):
    name = "apply-watchlist"
313
    help_text = "Applies the watchlist to the specified attachments"
314
315
    argument_names = "ATTACHMENT_ID [ATTACHMENT_IDS]"
    main_steps = [
316
        steps.DiscardLocalChanges,
317
318
319
320
321
322
323
324
        steps.Update,
        steps.ApplyPatch,
        steps.ApplyWatchList,
    ]
    long_help = """"Applies the watchlist to the specified attachments.
Downloads the attachment, applies it locally, runs the watchlist against it, and updates the bug with the result."""


325
326
class AbstractPatchLandingCommand(AbstractPatchSequencingCommand):
    main_steps = [
327
        steps.DiscardLocalChanges,
328
329
        steps.Update,
        steps.ApplyPatch,
330
        steps.ValidateChangeLogs,
331
        steps.ValidateReviewer,
332
333
334
335
336
        steps.Build,
        steps.RunTests,
        steps.Commit,
        steps.ClosePatch,
        steps.CloseBug,
337
    ]
338
339
340
341
342
343
344
345
    long_help = """Checks to make sure builders are green.
Updates the working copy.
Applies the patch.
Builds.
Runs the layout tests.
Commits the patch.
Clears the flags on the patch.
Closes the bug if no patches are marked for review."""
346
347


348
class LandAttachment(AbstractPatchLandingCommand, ProcessAttachmentsMixin):
349
    name = "land-attachment"
350
351
    help_text = "Land patches from bugzilla, optionally building and testing them first"
    argument_names = "ATTACHMENT_ID [ATTACHMENT_IDS]"
352
    show_in_main_help = True
353
354


355
356
class LandFromBug(AbstractPatchLandingCommand, ProcessBugsMixin):
    name = "land-from-bug"
357
358
    help_text = "Land all patches on the given bugs, optionally building and testing them first"
    argument_names = "BUGID [BUGIDS]"
359
    show_in_main_help = True
360
361


eric@webkit.org's avatar
eric@webkit.org committed
362
363
364
365
366
367
class LandFromURL(AbstractPatchLandingCommand, ProcessURLsMixin):
    name = "land-from-url"
    help_text = "Land all patches on the given URLs, optionally building and testing them first"
    argument_names = "URL [URLS]"


368
369
370
371
372
373
374
375
376
377
378
379
class ValidateChangelog(AbstractSequencedCommand):
    name = "validate-changelog"
    help_text = "Validate that the ChangeLogs and reviewers look reasonable"
    long_help = """Examines the current diff to see whether the ChangeLogs
and the reviewers listed in the ChangeLogs look reasonable.
"""
    steps = [
        steps.ValidateChangeLogs,
        steps.ValidateReviewer,
    ]


380
class AbstractRolloutPrepCommand(AbstractSequencedCommand):
381
    argument_names = "REVISION [REVISIONS] REASON"
382

383
    def _commit_info(self, revision):
384
        commit_info = self._tool.checkout().commit_info_for_revision(revision)
385
        if commit_info and commit_info.bug_id():
386
387
388
389
            # Note: Don't print a bug URL here because it will confuse the
            #       SheriffBot because the SheriffBot just greps the output
            #       of create-rollout for bug URLs.  It should do better
            #       parsing instead.
390
            _log.info("Preparing rollout for bug %s." % commit_info.bug_id())
391
        else:
392
            _log.info("Unable to parse bug number from diff.")
393
        return commit_info
394
395

    def _prepare_state(self, options, args, tool):
396
397
398
399
400
401
402
403
404
405
        revision_list = []
        for revision in str(args[0]).split():
            if revision.isdigit():
                revision_list.append(int(revision))
            else:
                raise ScriptError(message="Invalid svn revision number: " + revision)
        revision_list.sort()

        # We use the earliest revision for the bug info
        earliest_revision = revision_list[0]
406
        state = {
407
408
            "revision": earliest_revision,
            "revision_list": revision_list,
409
            "reason": args[1],
410
        }
411
412
413
414
415
416
417
418
419
        commit_info = self._commit_info(earliest_revision)
        if commit_info:
            state["bug_id"] = commit_info.bug_id()
            cc_list = sorted([party.bugzilla_email()
                            for party in commit_info.responsible_parties()
                            if party.bugzilla_email()])
            # FIXME: We should used the list as the canonical representation.
            state["bug_cc"] = ",".join(cc_list)
        return state
420
421
422
423


class PrepareRollout(AbstractRolloutPrepCommand):
    name = "prepare-rollout"
424
    help_text = "Revert the given revision(s) in the working copy and prepare ChangeLogs with revert reason"
425
    long_help = """Updates the working copy.
426
Applies the inverse diff for the provided revision(s).
427
428
429
Creates an appropriate rollout ChangeLog, including a trac link and bug link.
"""
    steps = [
430
        steps.DiscardLocalChanges,
431
432
433
434
435
        steps.Update,
        steps.RevertRevision,
        steps.PrepareChangeLogForRevert,
    ]

436

437
438
class CreateRollout(AbstractRolloutPrepCommand):
    name = "create-rollout"
439
    help_text = "Creates a bug to track the broken SVN revision(s) and uploads a rollout patch."
440
    steps = [
441
        steps.DiscardLocalChanges,
442
        steps.Update,
443
444
        steps.RevertRevision,
        steps.CreateBug,
445
446
447
        steps.PrepareChangeLogForRevert,
        steps.PostDiffForRevert,
    ]
448

449
450
451
452
453
454
455
456
457
458
459
    def _prepare_state(self, options, args, tool):
        state = AbstractRolloutPrepCommand._prepare_state(self, options, args, tool)
        # Currently, state["bug_id"] points to the bug that caused the
        # regression.  We want to create a new bug that blocks the old bug
        # so we move state["bug_id"] to state["bug_blocked"] and delete the
        # old state["bug_id"] so that steps.CreateBug will actually create
        # the new bug that we want (and subsequently store its bug id into
        # state["bug_id"])
        state["bug_blocked"] = state["bug_id"]
        del state["bug_id"]
        state["bug_title"] = "REGRESSION(r%s): %s" % (state["revision"], state["reason"])
460
        state["bug_description"] = "%s broke the build:\n%s" % (urls.view_revision_url(state["revision"]), state["reason"])
461
462
463
464
465
466
467
468
469
470
471
        # FIXME: If we had more context here, we could link to other open bugs
        #        that mention the test that regressed.
        if options.parent_command == "sheriff-bot":
            state["bug_description"] += """

This is an automatic bug report generated by the sheriff-bot. If this bug
report was created because of a flaky test, please file a bug for the flaky
test (if we don't already have one on file) and dup this bug against that bug
so that we can track how often these flaky tests case pain.

"Only you can prevent forest fires." -- Smokey the Bear
472
"""
473
474
        return state

475
476

class Rollout(AbstractRolloutPrepCommand):
477
    name = "rollout"
478
    show_in_main_help = True
479
    help_text = "Revert the given revision(s) in the working copy and optionally commit the revert and re-open the original bug"
480
481
482
483
484
485
    long_help = """Updates the working copy.
Applies the inverse diff for the provided revision.
Creates an appropriate rollout ChangeLog, including a trac link and bug link.
Opens the generated ChangeLogs in $EDITOR.
Shows the prepared diff for confirmation.
Commits the revert and updates the bug (including re-opening the bug if necessary)."""
486
    steps = [
487
        steps.DiscardLocalChanges,
488
489
490
        steps.Update,
        steps.RevertRevision,
        steps.PrepareChangeLogForRevert,
491
492
        steps.EditChangeLog,
        steps.ConfirmDiff,
493
494
495
        steps.Build,
        steps.Commit,
        steps.ReopenBugAfterRollout,
496
    ]