5db33335fba73fa854449538cce0caffd7c703ec
[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 _to_test_name(self, file_name): 
115         return self._tool.filesystem.relpath(file_name, self._port.layout_tests_dir())
116
117     def execute(self, options, args, tool):
118         self._baseline_optimizer = BaselineOptimizer(tool)
119         self._port = tool.port_factory.get("chromium-win-win7")  # FIXME: This should be selectable.
120
121         for test_name in map(self._to_test_name, self._port.find_test_files(args)):
122             print "Optimizing %s." % test_name
123             self._optimize_baseline(test_name)
124
125
126 class AnalyzeBaselines(AbstractDeclarativeCommand):
127     name = "analyze-baselines"
128     help_text = "Analyzes the baselines for the given tests and prints results that are identical."
129     argument_names = "TEST_NAMES"
130
131     def _print(self, baseline_name, directories_by_result):
132         for result, directories in directories_by_result.items():
133             if len(directories) <= 1:
134                 continue
135             results_names = [self._tool.filesystem.join(directory, baseline_name) for directory in directories]
136             print ' '.join(results_names)
137
138     def _analyze_baseline(self, test_name):
139         for suffix in _baseline_suffix_list:
140             baseline_name = _baseline_name(self._tool.filesystem, test_name, suffix)
141             directories_by_result = self._baseline_optimizer.directories_by_result(baseline_name)
142             self._print(baseline_name, directories_by_result)
143
144     def _to_test_name(self, file_name): 
145         return self._tool.filesystem.relpath(file_name, self._port.layout_tests_dir())
146
147     def execute(self, options, args, tool):
148         self._baseline_optimizer = BaselineOptimizer(tool)
149         self._port = tool.port_factory.get("chromium-win-win7")  # FIXME: This should be selectable.
150
151         for test_name in map(self._to_test_name, self._port.find_test_files(args)):
152             self._analyze_baseline(test_name)
153
154
155 class RebaselineExpectations(AbstractDeclarativeCommand):
156     name = "rebaseline-expectations"
157     help_text = "Rebaselines the tests indicated in test_expectations.txt."
158
159     def _run_webkit_patch(self, args):
160         try:
161             self._tool.executive.run_command([self._tool.path()] + args, cwd=self._tool.scm().checkout_root)
162         except ScriptError, e:
163             pass
164
165     def _is_supported_port(self, port_name):
166         # FIXME: Support non-Chromium ports.
167         return port_name.startswith('chromium-')
168
169     def _expectations(self, port):
170         return TestExpectations(port, None, port.test_expectations(), port.test_configuration())
171
172     def _update_expectations_file(self, port_name):
173         if not self._is_supported_port(port_name):
174             return
175         port = self._tool.port_factory.get(port_name)
176         expectations = self._expectations(port)
177         path = port.path_to_test_expectations_file()
178         self._tool.filesystem.write_text_file(path, expectations.remove_rebaselined_tests(expectations.get_rebaselining_failures()))
179
180     def _tests_to_rebaseline(self, port):
181         return self._expectations(port).get_rebaselining_failures()
182
183     def _rebaseline_port(self, port_name):
184         if not self._is_supported_port(port_name):
185             return
186         builder_name = builders.builder_name_for_port_name(port_name)
187         if not builder_name:
188             return
189         print "Retrieving results for %s from %s." % (port_name, builder_name)
190         for test_name in self._tests_to_rebaseline(self._tool.port_factory.get(port_name)):
191             self._touched_test_names.add(test_name)
192             print "    %s" % test_name
193             self._run_webkit_patch(['rebaseline-test', builder_name, test_name])
194
195     def execute(self, options, args, tool):
196         self._touched_test_names = set([])
197         for port_name in tool.port_factory.all_port_names():
198             self._rebaseline_port(port_name)
199         for port_name in tool.port_factory.all_port_names():
200             self._update_expectations_file(port_name)
201         for test_name in self._touched_test_names:
202             print "Optimizing baselines for %s." % test_name
203             self._run_webkit_patch(['optimize-baselines', test_name])
204
205
206 class Rebaseline(AbstractDeclarativeCommand):
207     name = "rebaseline"
208     help_text = "Replaces local expected.txt files with new results from build bots"
209
210     # FIXME: This should share more code with FailureReason._builder_to_explain
211     def _builder_to_pull_from(self):
212         builder_statuses = self._tool.buildbot.builder_statuses()
213         red_statuses = [status for status in builder_statuses if not status["is_green"]]
214         print "%s failing" % (pluralize("builder", len(red_statuses)))
215         builder_choices = [status["name"] for status in red_statuses]
216         chosen_name = self._tool.user.prompt_with_list("Which builder to pull results from:", builder_choices)
217         # FIXME: prompt_with_list should really take a set of objects and a set of names and then return the object.
218         for status in red_statuses:
219             if status["name"] == chosen_name:
220                 return (self._tool.buildbot.builder_with_name(chosen_name), status["build_number"])
221
222     def _replace_expectation_with_remote_result(self, local_file, remote_file):
223         (downloaded_file, headers) = urllib.urlretrieve(remote_file)
224         shutil.move(downloaded_file, local_file)
225
226     def _tests_to_update(self, build):
227         failing_tests = build.layout_test_results().tests_matching_failure_types([test_failures.FailureTextMismatch])
228         return self._tool.user.prompt_with_list("Which test(s) to rebaseline:", failing_tests, can_choose_multiple=True)
229
230     def _results_url_for_test(self, build, test):
231         test_base = os.path.splitext(test)[0]
232         actual_path = test_base + "-actual.txt"
233         return build.results_url() + "/" + actual_path
234
235     def execute(self, options, args, tool):
236         builder, build_number = self._builder_to_pull_from()
237         build = builder.build(build_number)
238         port = tool.port_factory.get_from_builder_name(builder.name())
239
240         for test in self._tests_to_update(build):
241             results_url = self._results_url_for_test(build, test)
242             # Port operates with absolute paths.
243             expected_file = port.expected_filename(test, '.txt')
244             print test
245             self._replace_expectation_with_remote_result(expected_file, results_url)
246
247         # FIXME: We should handle new results too.