515ff7dfa581d17b49699531b70d5e1ab4f146e4
[WebKit-https.git] / Tools / Scripts / webkitpy / tool / commands / rebaseline.py
1 # Copyright (c) 2010 Google Inc. All rights reserved.
2 #
3 # Redistribution and use in source and binary forms, with or without
4 # modification, are permitted provided that the following conditions are
5 # met:
6 #
7 #     * Redistributions of source code must retain the above copyright
8 # notice, this list of conditions and the following disclaimer.
9 #     * Redistributions in binary form must reproduce the above
10 # copyright notice, this list of conditions and the following disclaimer
11 # in the documentation and/or other materials provided with the
12 # distribution.
13 #     * Neither the name of Google Inc. nor the names of its
14 # contributors may be used to endorse or promote products derived from
15 # this software without specific prior written permission.
16 #
17 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29 import os.path
30 import re
31 import shutil
32 import urllib
33
34 import webkitpy.common.config.urls as config_urls
35 from webkitpy.common.checkout.baselineoptimizer import BaselineOptimizer
36 from webkitpy.common.net.buildbot import BuildBot
37 from webkitpy.common.net.layouttestresults import LayoutTestResults
38 from webkitpy.common.system.executive import ScriptError
39 from webkitpy.common.system.user import User
40 from webkitpy.layout_tests.controllers.test_result_writer import TestResultWriter
41 from webkitpy.layout_tests.models import test_failures
42 from webkitpy.layout_tests.models.test_expectations import TestExpectations
43 from webkitpy.layout_tests.port import builders
44 from webkitpy.tool.grammar import pluralize
45 from webkitpy.tool.multicommandtool import AbstractDeclarativeCommand
46
47
48 _baseline_suffix_list = ['png', 'txt']
49
50
51 # FIXME: Should TestResultWriter know how to compute this string?
52 def _baseline_name(fs, test_name, suffix):
53     return fs.splitext(test_name)[0] + TestResultWriter.FILENAME_SUFFIX_EXPECTED + "." + suffix
54
55
56 class RebaselineTest(AbstractDeclarativeCommand):
57     name = "rebaseline-test"
58     help_text = "Rebaseline a single test from a buildbot.  (Currently works only with build.chromium.org buildbots.)"
59     argument_names = "BUILDER_NAME TEST_NAME"
60
61     def _results_url(self, builder_name):
62         # FIXME: Generalize this command to work with non-build.chromium.org builders.
63         builder = self._tool.chromium_buildbot().builder_with_name(builder_name)
64         return builder.accumulated_results_url()
65
66     def _baseline_directory(self, builder_name):
67         port = self._tool.port_factory.get_from_builder_name(builder_name)
68         return port.baseline_path()
69
70     def _save_baseline(self, data, target_baseline):
71         if not data:
72             return
73         filesystem = self._tool.filesystem
74         filesystem.maybe_make_directory(filesystem.dirname(target_baseline))
75         filesystem.write_binary_file(target_baseline, data)
76         if not self._tool.scm().exists(target_baseline):
77             self._tool.scm().add(target_baseline)
78
79     def _test_root(self, test_name):
80         return os.path.splitext(test_name)[0]
81
82     def _file_name_for_actual_result(self, test_name, suffix):
83         return "%s-actual.%s" % (self._test_root(test_name), suffix)
84
85     def _file_name_for_expected_result(self, test_name, suffix):
86         return "%s-expected.%s" % (self._test_root(test_name), suffix)
87
88     def _rebaseline_test(self, builder_name, test_name, suffix):
89         results_url = self._results_url(builder_name)
90         baseline_directory = self._baseline_directory(builder_name)
91
92         source_baseline = "%s/%s" % (results_url, self._file_name_for_actual_result(test_name, suffix))
93         target_baseline = os.path.join(baseline_directory, self._file_name_for_expected_result(test_name, suffix))
94
95         print "Retrieving %s." % source_baseline
96         self._save_baseline(self._tool.web.get_binary(source_baseline, convert_404_to_None=True), target_baseline)
97
98     def execute(self, options, args, tool):
99         for suffix in _baseline_suffix_list:
100             self._rebaseline_test(args[0], args[1], suffix)
101
102
103 class OptimizeBaselines(AbstractDeclarativeCommand):
104     name = "optimize-baselines"
105     help_text = "Reshuffles the baselines for the given tests to use as litte space on disk as possible."
106     argument_names = "TEST_NAMES"
107
108     def _optimize_baseline(self, test_name):
109         for suffix in _baseline_suffix_list:
110             baseline_name = _baseline_name(self._tool.filesystem, test_name, suffix)
111             if not self._baseline_optimizer.optimize(baseline_name):
112                 print "Hueristics failed to optimize %s" % baseline_name
113
114     def execute(self, options, args, tool):
115         self._baseline_optimizer = BaselineOptimizer(tool)
116         self._port = tool.port_factory.get("chromium-win-win7")  # FIXME: This should be selectable.
117
118         for test_name in self._port.tests(args):
119             print "Optimizing %s." % test_name
120             self._optimize_baseline(test_name)
121
122
123 class AnalyzeBaselines(AbstractDeclarativeCommand):
124     name = "analyze-baselines"
125     help_text = "Analyzes the baselines for the given tests and prints results that are identical."
126     argument_names = "TEST_NAMES"
127
128     def _print(self, baseline_name, directories_by_result):
129         for result, directories in directories_by_result.items():
130             if len(directories) <= 1:
131                 continue
132             results_names = [self._tool.filesystem.join(directory, baseline_name) for directory in directories]
133             print ' '.join(results_names)
134
135     def _analyze_baseline(self, test_name):
136         for suffix in _baseline_suffix_list:
137             baseline_name = _baseline_name(self._tool.filesystem, test_name, suffix)
138             directories_by_result = self._baseline_optimizer.directories_by_result(baseline_name)
139             self._print(baseline_name, directories_by_result)
140
141     def execute(self, options, args, tool):
142         self._baseline_optimizer = BaselineOptimizer(tool)
143         self._port = tool.port_factory.get("chromium-win-win7")  # FIXME: This should be selectable.
144
145         for test_name in self._port.tests(args):
146             self._analyze_baseline(test_name)
147
148
149 class RebaselineExpectations(AbstractDeclarativeCommand):
150     name = "rebaseline-expectations"
151     help_text = "Rebaselines the tests indicated in test_expectations.txt."
152
153     def _run_webkit_patch(self, args):
154         try:
155             self._tool.executive.run_command([self._tool.path()] + args, cwd=self._tool.scm().checkout_root)
156         except ScriptError, e:
157             pass
158
159     def _is_supported_port(self, port_name):
160         # FIXME: Support non-Chromium ports.
161         return port_name.startswith('chromium-')
162
163     def _expectations(self, port):
164         return TestExpectations(port, None, port.test_expectations(), port.test_configuration())
165
166     def _update_expectations_file(self, port_name):
167         if not self._is_supported_port(port_name):
168             return
169         port = self._tool.port_factory.get(port_name)
170         expectations = self._expectations(port)
171         path = port.path_to_test_expectations_file()
172         self._tool.filesystem.write_text_file(path, expectations.remove_rebaselined_tests(expectations.get_rebaselining_failures()))
173
174     def _tests_to_rebaseline(self, port):
175         return self._expectations(port).get_rebaselining_failures()
176
177     def _rebaseline_port(self, port_name):
178         if not self._is_supported_port(port_name):
179             return
180         builder_name = builders.builder_name_for_port_name(port_name)
181         if not builder_name:
182             return
183         print "Retrieving results for %s from %s." % (port_name, builder_name)
184         for test_name in self._tests_to_rebaseline(self._tool.port_factory.get(port_name)):
185             self._touched_test_names.add(test_name)
186             print "    %s" % test_name
187             self._run_webkit_patch(['rebaseline-test', builder_name, test_name])
188
189     def execute(self, options, args, tool):
190         self._touched_test_names = set([])
191         for port_name in tool.port_factory.all_port_names():
192             self._rebaseline_port(port_name)
193         for port_name in tool.port_factory.all_port_names():
194             self._update_expectations_file(port_name)
195         for test_name in self._touched_test_names:
196             print "Optimizing baselines for %s." % test_name
197             self._run_webkit_patch(['optimize-baselines', test_name])
198
199
200 class Rebaseline(AbstractDeclarativeCommand):
201     name = "rebaseline"
202     help_text = "Replaces local expected.txt files with new results from build bots"
203
204     # FIXME: This should share more code with FailureReason._builder_to_explain
205     def _builder_to_pull_from(self):
206         builder_statuses = self._tool.buildbot.builder_statuses()
207         red_statuses = [status for status in builder_statuses if not status["is_green"]]
208         print "%s failing" % (pluralize("builder", len(red_statuses)))
209         builder_choices = [status["name"] for status in red_statuses]
210         chosen_name = self._tool.user.prompt_with_list("Which builder to pull results from:", builder_choices)
211         # FIXME: prompt_with_list should really take a set of objects and a set of names and then return the object.
212         for status in red_statuses:
213             if status["name"] == chosen_name:
214                 return (self._tool.buildbot.builder_with_name(chosen_name), status["build_number"])
215
216     def _replace_expectation_with_remote_result(self, local_file, remote_file):
217         (downloaded_file, headers) = urllib.urlretrieve(remote_file)
218         shutil.move(downloaded_file, local_file)
219
220     def _tests_to_update(self, build):
221         failing_tests = build.layout_test_results().tests_matching_failure_types([test_failures.FailureTextMismatch])
222         return self._tool.user.prompt_with_list("Which test(s) to rebaseline:", failing_tests, can_choose_multiple=True)
223
224     def _results_url_for_test(self, build, test):
225         test_base = os.path.splitext(test)[0]
226         actual_path = test_base + "-actual.txt"
227         return build.results_url() + "/" + actual_path
228
229     def execute(self, options, args, tool):
230         builder, build_number = self._builder_to_pull_from()
231         build = builder.build(build_number)
232         port = tool.port_factory.get_from_builder_name(builder.name())
233
234         for test in self._tests_to_update(build):
235             results_url = self._results_url_for_test(build, test)
236             # Port operates with absolute paths.
237             expected_file = port.expected_filename(test, '.txt')
238             print test
239             self._replace_expectation_with_remote_result(expected_file, results_url)
240
241         # FIXME: We should handle new results too.