1# Copyright (C) 2011 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# 1.  Redistributions of source code must retain the above copyright
8#     notice, this list of conditions and the following disclaimer.
9# 2.  Redistributions in binary form must reproduce the above copyright
10#     notice, this list of conditions and the following disclaimer in the
11#     documentation and/or other materials provided with the distribution.
12#
13# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
14# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
15# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
16# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
17# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
18# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
19# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24
25from optparse import make_option
26import threading
27
28from webkitpy.tool.multicommandtool import AbstractDeclarativeCommand
29
30
31class AbstractLocalServerCommand(AbstractDeclarativeCommand):
32    server = None
33    launch_path = "/"
34
35    def __init__(self):
36        options = [
37            make_option("--httpd-port", action="store", type="int", default=8127, help="Port to use for the HTTP server"),
38            make_option("--no-show-results", action="store_false", default=True, dest="show_results", help="Don't launch a browser with the rebaseline server"),
39        ]
40        AbstractDeclarativeCommand.__init__(self, options=options)
41
42    def _prepare_config(self, options, args, tool):
43        return None
44
45    def execute(self, options, args, tool):
46        config = self._prepare_config(options, args, tool)
47
48        server_url = "http://localhost:%d%s" % (options.httpd_port, self.launch_path)
49        print "Starting server at %s" % server_url
50        print "Use the 'Exit' link in the UI, %squitquitquit or Ctrl-C to stop" % server_url
51
52        if options.show_results:
53            # FIXME: This seems racy.
54            threading.Timer(0.1, lambda: self._tool.user.open_url(server_url)).start()
55
56        httpd = self.server(httpd_port=options.httpd_port, config=config)  # pylint: disable=E1102
57        httpd.serve_forever()
58