~loggerhead-team/loggerhead/trunk-rich

352.5.4 by Martin Albisetti
Check the global config before looking at the switch command
1
#
2
# Copyright (C) 2008, 2009 Canonical Ltd
3
#
4
# This program is free software; you can redistribute it and/or modify
5
# it under the terms of the GNU General Public License as published by
6
# the Free Software Foundation; either version 2 of the License, or
7
# (at your option) any later version.
8
#
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU General Public License for more details.
13
#
389.2.3 by Matt Nordhoff
moar
14
"""Configuration tools for Loggerhead."""
352.5.4 by Martin Albisetti
Check the global config before looking at the switch command
15
315.1.2 by Paul Hummer
Moved command_line_parser out of serve branches and into gonfig.py
16
from optparse import OptionParser
17
import sys
315.1.3 by Paul Hummer
Moar integrations for the config codes!
18
import tempfile
315.1.2 by Paul Hummer
Moved command_line_parser out of serve branches and into gonfig.py
19
352.5.4 by Martin Albisetti
Check the global config before looking at the switch command
20
from bzrlib import config
315.1.2 by Paul Hummer
Moved command_line_parser out of serve branches and into gonfig.py
21
324.3.3 by Matt Nordhoff
Don't create the temporary SQL dir until it's actually needed.
22
_temporary_sql_dir = None
23
24
def _get_temporary_sql_dir():
25
    global _temporary_sql_dir
26
    if _temporary_sql_dir is None:
27
        _temporary_sql_dir = tempfile.mkdtemp(prefix='loggerhead-cache-')
28
    return _temporary_sql_dir
324.3.1 by Matt Nordhoff
Quick fix: Create one, global SQL_DIR in loggerhead.config
29
352.5.3 by Martin Albisetti
Actually, I'm stupid
30
def command_line_parser():
31
    parser = OptionParser("%prog [options] <path>")
32
    parser.set_defaults(
33
        user_dirs=False,
34
        show_version=False,
35
        log_folder=None,
36
        use_cdn=False,
37
        sql_dir=None,
359.2.1 by Matt Nordhoff
Add an --allow-writes option to serve-branches and "bzr serve"
38
        allow_writes=False,
431.2.1 by Martin Albisetti
Allow conditionally exporting tarballs, now with 300% less cruft.
39
        export_tarballs=True,
352.5.3 by Martin Albisetti
Actually, I'm stupid
40
        )
329.1.4 by Matt Nordhoff
Remove some unnecessary optparse arguments
41
    parser.add_option("--user-dirs", action="store_true",
352.5.3 by Martin Albisetti
Actually, I'm stupid
42
                      help="Serve user directories as ~user.")
43
    parser.add_option("--trunk-dir", metavar="DIR",
44
                      help="The directory that contains the trunk branches.")
45
    parser.add_option("--port", dest="user_port",
46
                      help=("Port Loggerhead should listen on "
47
                            "(defaults to 8080)."))
48
    parser.add_option("--host", dest="user_host",
49
                      help="Host Loggerhead should listen on.")
393.2.1 by Denis Martinez
other protocol support using flup
50
    parser.add_option("--protocol", dest="protocol",
51
                      help=("Protocol to use: http, scgi, fcgi, ajp"
52
                           "(defaults to http)."))
411.2.1 by John Arbash Meinel
Add 'http_log_level' and --log-level.
53
    parser.add_option("--log-level", default=None, action='callback',
54
                      callback=_optparse_level_to_int_level,
55
                      type="string",
56
                      help="Set the verbosity of logging. Can either"
57
                           " be set to a numeric or string"
58
                           " (eg, 10=debug, 30=warning)")
389.2.3 by Matt Nordhoff
moar
59
    parser.add_option("--memory-profile", action="store_true",
60
                      help="Profile the memory usage using Dozer.")
352.5.3 by Martin Albisetti
Actually, I'm stupid
61
    parser.add_option("--prefix", dest="user_prefix",
62
                      help="Specify host prefix.")
329.1.4 by Matt Nordhoff
Remove some unnecessary optparse arguments
63
    parser.add_option("--profile", action="store_true",
352.5.3 by Martin Albisetti
Actually, I'm stupid
64
                      help="Generate callgrind profile data to "
65
                        "%d-stats.callgrind on each request.")
329.1.4 by Matt Nordhoff
Remove some unnecessary optparse arguments
66
    parser.add_option("--reload", action="store_true",
352.5.3 by Martin Albisetti
Actually, I'm stupid
67
                      help="Restarts the application when changing python"
68
                           " files. Only used for development purposes.")
389.2.3 by Matt Nordhoff
moar
69
    parser.add_option("--log-folder",
329.1.4 by Matt Nordhoff
Remove some unnecessary optparse arguments
70
                      help="The directory to place log files in.")
352.5.3 by Martin Albisetti
Actually, I'm stupid
71
    parser.add_option("--version", action="store_true", dest="show_version",
72
                      help="Print the software version and exit")
352.5.7 by Martin Albisetti
Fail to test it, and a few tweaks
73
    parser.add_option("--use-cdn", action="store_true", dest="use_cdn",
352.5.3 by Martin Albisetti
Actually, I'm stupid
74
                      help="Serve YUI from Yahoo!'s CDN")
352.5.7 by Martin Albisetti
Fail to test it, and a few tweaks
75
    parser.add_option("--cache-dir", dest="sql_dir",
352.5.3 by Martin Albisetti
Actually, I'm stupid
76
                      help="The directory to place the SQL cache in")
389.2.3 by Matt Nordhoff
moar
77
    parser.add_option("--allow-writes", action="store_true",
359.2.1 by Matt Nordhoff
Add an --allow-writes option to serve-branches and "bzr serve"
78
                      help="Allow writing to the Bazaar server.")
431.2.1 by Martin Albisetti
Allow conditionally exporting tarballs, now with 300% less cruft.
79
    parser.add_option("--export-tarballs", action="store_true",
80
                      help="Allow exporting revisions to tarballs.")
352.5.3 by Martin Albisetti
Actually, I'm stupid
81
    return parser
82
315.1.1 by Paul Hummer
Added base config class
83
411.2.1 by John Arbash Meinel
Add 'http_log_level' and --log-level.
84
_log_levels = {
85
    'debug': 10,
86
    'info': 20,
87
    'warning': 30,
88
    'error': 40,
89
    'critical': 50,
90
}
91
92
def _optparse_level_to_int_level(option, opt_str, value, parser):
411.2.4 by John Arbash Meinel
Correctly parse values in the callback for optparse.
93
    parser.values.log_level = _level_to_int_level(value)
411.2.1 by John Arbash Meinel
Add 'http_log_level' and --log-level.
94
95
96
def _level_to_int_level(value):
97
    """Convert a string level to an integer value."""
98
    if value is None:
99
        return None
100
    try:
101
        return int(value)
102
    except ValueError:
103
        pass
104
    return _log_levels[value.lower()]
105
106
323 by Matt Nordhoff
Make LoggerheadConfig a new-style class
107
class LoggerheadConfig(object):
389.2.3 by Matt Nordhoff
moar
108
    """A configuration object."""
315.1.1 by Paul Hummer
Added base config class
109
346.1.1 by Matt Nordhoff
Fix 'bzr serve --http' (bug #377551).
110
    def __init__(self, argv=None):
111
        if argv is None:
352 by Matt Nordhoff
Fix typo.
112
            argv = sys.argv[1:]
352.5.3 by Martin Albisetti
Actually, I'm stupid
113
        self._parser = command_line_parser()
346.1.1 by Matt Nordhoff
Fix 'bzr serve --http' (bug #377551).
114
        self._options, self._args = self._parser.parse_args(argv)
315.1.3 by Paul Hummer
Moar integrations for the config codes!
115
324.3.4 by Matt Nordhoff
Whoops. Test, *then* commit! Not the other way around!
116
        sql_dir = self.get_option('sql_dir')
324.3.3 by Matt Nordhoff
Don't create the temporary SQL dir until it's actually needed.
117
        if sql_dir is None:
118
            sql_dir = _get_temporary_sql_dir()
119
        self.SQL_DIR = sql_dir
120
315.1.2 by Paul Hummer
Moved command_line_parser out of serve branches and into gonfig.py
121
    def get_option(self, option):
329.2.3 by Matt Nordhoff
Remove new trailing whitespace
122
        """Get the value for the config option, either
389.2.3 by Matt Nordhoff
moar
123
        from ~/.bazaar/bazaar.conf or from the command line.
124
        All loggerhead-specific settings start with 'http_'
125
        """
352.5.4 by Martin Albisetti
Check the global config before looking at the switch command
126
        global_config = config.GlobalConfig().get_user_option('http_'+option)
352.5.6 by Martin Albisetti
Make the command line win over global config
127
        cmd_config = getattr(self._options, option)
352.5.7 by Martin Albisetti
Fail to test it, and a few tweaks
128
        if global_config is not None and (
389.2.1 by Matt Nordhoff
Some random PEP 8 and otehr stylistic changes.
129
            cmd_config is None or cmd_config is False):
352.5.4 by Martin Albisetti
Check the global config before looking at the switch command
130
            return global_config
131
        else:
352.5.6 by Martin Albisetti
Make the command line win over global config
132
            return cmd_config
315.1.2 by Paul Hummer
Moved command_line_parser out of serve branches and into gonfig.py
133
411.2.1 by John Arbash Meinel
Add 'http_log_level' and --log-level.
134
    def get_log_level(self):
135
        opt = self.get_option('log_level')
136
        return _level_to_int_level(opt)
137
315.1.2 by Paul Hummer
Moved command_line_parser out of serve branches and into gonfig.py
138
    def get_arg(self, index):
352.5.7 by Martin Albisetti
Fail to test it, and a few tweaks
139
        """Get an arg from the arg list."""
321 by Michael Hudson
fix bug #353230, thanks Peter Bui
140
        return self._args[index]
315.1.1 by Paul Hummer
Added base config class
141
315.1.3 by Paul Hummer
Moar integrations for the config codes!
142
    def print_help(self):
352.5.7 by Martin Albisetti
Fail to test it, and a few tweaks
143
        """Wrapper around OptionParser.print_help."""
315.1.3 by Paul Hummer
Moar integrations for the config codes!
144
        return self._parser.print_help()
145
146
    @property
147
    def arg_count(self):
352.5.7 by Martin Albisetti
Fail to test it, and a few tweaks
148
        """Return the number of args from the option parser."""
315.1.3 by Paul Hummer
Moar integrations for the config codes!
149
        return len(self._args)