~bzr-pqm/bzr/bzr.dev

1442.1.1 by Robert Collins
move config_dir into bzrlib.config
1
# Copyright (C) 2005 by Canonical Ltd
2
#   Authors: Robert Collins <robert.collins@canonical.com>
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
#
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
16
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17
1442.1.20 by Robert Collins
add some documentation on options
18
"""Configuration that affects the behaviour of Bazaar.
19
20
Currently this configuration resides in ~/.bazaar/bazaar.conf
21
and ~/.bazaar/branches.conf, which is written to by bzr.
22
1461 by Robert Collins
Typo in config.py (Thanks Fabbione)
23
In bazaar.conf the following options may be set:
1442.1.20 by Robert Collins
add some documentation on options
24
[DEFAULT]
25
editor=name-of-program
26
email=Your Name <your@email.address>
27
check_signatures=require|ignore|check-available(default)
28
create_signatures=always|never|when-required(default)
1442.1.56 by Robert Collins
gpg_signing_command configuration item
29
gpg_signing_command=name-of-program
1442.1.20 by Robert Collins
add some documentation on options
30
31
in branches.conf, you specify the url of a branch and options for it.
32
Wildcards may be used - * and ? as normal in shell completion. Options
33
set in both bazaar.conf and branches.conf are overriden by the branches.conf
34
setting.
35
[/home/robertc/source]
36
recurse=False|True(default)
37
email= as above
38
check_signatures= as abive 
39
create_signatures= as above.
40
41
explanation of options
42
----------------------
43
editor - this option sets the pop up editor to use during commits.
44
email - this option sets the user id bzr will use when committing.
45
check_signatures - this option controls whether bzr will require good gpg
46
                   signatures, ignore them, or check them if they are 
47
                   present.
48
create_signatures - this option controls whether bzr will always create 
49
                    gpg signatures, never create them, or create them if the
50
                    branch is configured to require them.
1442.1.21 by Robert Collins
create signature_needed() call for commit to trigger creating signatures
51
                    NB: This option is planned, but not implemented yet.
1442.1.20 by Robert Collins
add some documentation on options
52
"""
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
53
1474 by Robert Collins
Merge from Aaron Bentley.
54
55
import errno
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
56
import os
1185.38.1 by John Arbash Meinel
Adding my win32 patch for moving the home directory.
57
import sys
1442.1.12 by Robert Collins
LocationConfig section retrieval falls into my lap
58
from fnmatch import fnmatch
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
59
import re
60
61
import bzrlib
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
62
import bzrlib.errors as errors
1185.31.32 by John Arbash Meinel
Updated the bzr sourcecode to use bzrlib.osutils.pathjoin rather than os.path.join to enforce internal use of / instead of \
63
from bzrlib.osutils import pathjoin
1185.31.39 by John Arbash Meinel
Replacing os.getcwdu() with osutils.getcwd(),
64
from bzrlib.trace import mutter
1474 by Robert Collins
Merge from Aaron Bentley.
65
import bzrlib.util.configobj.configobj as configobj
1185.35.11 by Aaron Bentley
Added support for branch nicks
66
from StringIO import StringIO
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
67
1442.1.14 by Robert Collins
Create a default signature checking policy of CHECK_IF_POSSIBLE
68
CHECK_IF_POSSIBLE=0
69
CHECK_ALWAYS=1
70
CHECK_NEVER=2
71
72
1474 by Robert Collins
Merge from Aaron Bentley.
73
class ConfigObj(configobj.ConfigObj):
74
75
    def get_bool(self, section, key):
76
        val = self[section][key].lower()
77
        if val in ('1', 'yes', 'true', 'on'):
78
            return True
79
        elif val in ('0', 'no', 'false', 'off'):
80
            return False
81
        else:
82
            raise ValueError("Value %r is not boolean" % val)
83
84
    def get_value(self, section, name):
85
        # Try [] for the old DEFAULT section.
86
        if section == "DEFAULT":
87
            try:
88
                return self[name]
89
            except KeyError:
90
                pass
91
        return self[section][name]
92
93
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
94
class Config(object):
95
    """A configuration policy - what username, editor, gpg needs etc."""
96
97
    def get_editor(self):
98
        """Get the users pop up editor."""
99
        raise NotImplementedError
100
1442.1.15 by Robert Collins
make getting the signature checking policy a template method
101
    def _get_signature_checking(self):
102
        """Template method to override signature checking policy."""
103
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
104
    def _get_user_option(self, option_name):
105
        """Template method to provide a user option."""
106
        return None
107
108
    def get_user_option(self, option_name):
109
        """Get a generic option - no special process, no default."""
110
        return self._get_user_option(option_name)
111
1442.1.56 by Robert Collins
gpg_signing_command configuration item
112
    def gpg_signing_command(self):
113
        """What program should be used to sign signatures?"""
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
114
        result = self._gpg_signing_command()
115
        if result is None:
116
            result = "gpg"
117
        return result
118
119
    def _gpg_signing_command(self):
120
        """See gpg_signing_command()."""
121
        return None
1442.1.56 by Robert Collins
gpg_signing_command configuration item
122
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
123
    def __init__(self):
124
        super(Config, self).__init__()
125
1472 by Robert Collins
post commit hook, first pass implementation
126
    def post_commit(self):
127
        """An ordered list of python functions to call.
128
129
        Each function takes branch, rev_id as parameters.
130
        """
131
        return self._post_commit()
132
133
    def _post_commit(self):
134
        """See Config.post_commit."""
135
        return None
136
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
137
    def user_email(self):
138
        """Return just the email component of a username."""
1185.33.31 by Martin Pool
Make annotate cope better with revisions committed without a valid
139
        return extract_email_address(self.username())
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
140
141
    def username(self):
142
        """Return email-style username.
143
    
144
        Something similar to 'Martin Pool <mbp@sourcefrog.net>'
145
        
146
        $BZREMAIL can be set to override this, then
147
        the concrete policy type is checked, and finally
1185.37.2 by Jamie Wilkinson
Fix a typo and grammar in Config.username() docstring.
148
        $EMAIL is examined.
149
        If none is found, a reasonable default is (hopefully)
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
150
        created.
151
    
152
        TODO: Check it's reasonably well-formed.
153
        """
154
        v = os.environ.get('BZREMAIL')
155
        if v:
156
            return v.decode(bzrlib.user_encoding)
157
    
158
        v = self._get_user_id()
159
        if v:
160
            return v
161
        
162
        v = os.environ.get('EMAIL')
163
        if v:
164
            return v.decode(bzrlib.user_encoding)
165
166
        name, email = _auto_user_id()
167
        if name:
168
            return '%s <%s>' % (name, email)
169
        else:
170
            return email
171
1442.1.14 by Robert Collins
Create a default signature checking policy of CHECK_IF_POSSIBLE
172
    def signature_checking(self):
173
        """What is the current policy for signature checking?."""
1442.1.15 by Robert Collins
make getting the signature checking policy a template method
174
        policy = self._get_signature_checking()
175
        if policy is not None:
176
            return policy
1442.1.14 by Robert Collins
Create a default signature checking policy of CHECK_IF_POSSIBLE
177
        return CHECK_IF_POSSIBLE
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
178
1442.1.21 by Robert Collins
create signature_needed() call for commit to trigger creating signatures
179
    def signature_needed(self):
180
        """Is a signature needed when committing ?."""
181
        policy = self._get_signature_checking()
182
        if policy == CHECK_ALWAYS:
183
            return True
184
        return False
185
1442.1.15 by Robert Collins
make getting the signature checking policy a template method
186
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
187
class IniBasedConfig(Config):
188
    """A configuration policy that draws from ini files."""
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
189
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
190
    def _get_parser(self, file=None):
1185.12.51 by Aaron Bentley
Allowed second call of _get_parser() to not require a file
191
        if self._parser is not None:
192
            return self._parser
1185.12.49 by Aaron Bentley
Switched to ConfigObj
193
        if file is None:
194
            input = self._get_filename()
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
195
        else:
1185.12.49 by Aaron Bentley
Switched to ConfigObj
196
            input = file
1185.12.51 by Aaron Bentley
Allowed second call of _get_parser() to not require a file
197
        try:
198
            self._parser = ConfigObj(input)
1474 by Robert Collins
Merge from Aaron Bentley.
199
        except configobj.ConfigObjError, e:
1185.12.51 by Aaron Bentley
Allowed second call of _get_parser() to not require a file
200
            raise errors.ParseConfigError(e.errors, e.config.filename)
1185.12.49 by Aaron Bentley
Switched to ConfigObj
201
        return self._parser
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
202
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
203
    def _get_section(self):
204
        """Override this to define the section used by the config."""
205
        return "DEFAULT"
206
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
207
    def _get_signature_checking(self):
208
        """See Config._get_signature_checking."""
1474 by Robert Collins
Merge from Aaron Bentley.
209
        policy = self._get_user_option('check_signatures')
210
        if policy:
211
            return self._string_to_signature_policy(policy)
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
212
213
    def _get_user_id(self):
214
        """Get the user id from the 'email' key in the current section."""
1474 by Robert Collins
Merge from Aaron Bentley.
215
        return self._get_user_option('email')
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
216
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
217
    def _get_user_option(self, option_name):
218
        """See Config._get_user_option."""
1185.12.53 by Aaron Bentley
Merged more from Robert
219
        try:
1474 by Robert Collins
Merge from Aaron Bentley.
220
            return self._get_parser().get_value(self._get_section(),
221
                                                option_name)
1185.12.53 by Aaron Bentley
Merged more from Robert
222
        except KeyError:
223
            pass
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
224
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
225
    def _gpg_signing_command(self):
1442.1.56 by Robert Collins
gpg_signing_command configuration item
226
        """See Config.gpg_signing_command."""
1472 by Robert Collins
post commit hook, first pass implementation
227
        return self._get_user_option('gpg_signing_command')
1442.1.56 by Robert Collins
gpg_signing_command configuration item
228
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
229
    def __init__(self, get_filename):
230
        super(IniBasedConfig, self).__init__()
231
        self._get_filename = get_filename
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
232
        self._parser = None
1472 by Robert Collins
post commit hook, first pass implementation
233
        
234
    def _post_commit(self):
235
        """See Config.post_commit."""
236
        return self._get_user_option('post_commit')
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
237
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
238
    def _string_to_signature_policy(self, signature_string):
239
        """Convert a string to a signing policy."""
1442.1.17 by Robert Collins
allow global overriding of signature policy to force checking, or (pointless but allowed) to set auto checking
240
        if signature_string.lower() == 'check-available':
241
            return CHECK_IF_POSSIBLE
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
242
        if signature_string.lower() == 'ignore':
243
            return CHECK_NEVER
1442.1.17 by Robert Collins
allow global overriding of signature policy to force checking, or (pointless but allowed) to set auto checking
244
        if signature_string.lower() == 'require':
245
            return CHECK_ALWAYS
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
246
        raise errors.BzrError("Invalid signatures policy '%s'"
247
                              % signature_string)
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
248
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
249
250
class GlobalConfig(IniBasedConfig):
251
    """The configuration that should be used for a specific location."""
252
253
    def get_editor(self):
1474 by Robert Collins
Merge from Aaron Bentley.
254
        return self._get_user_option('editor')
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
255
256
    def __init__(self):
257
        super(GlobalConfig, self).__init__(config_filename)
258
259
260
class LocationConfig(IniBasedConfig):
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
261
    """A configuration object that gives the policy for a location."""
262
263
    def __init__(self, location):
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
264
        super(LocationConfig, self).__init__(branches_config_filename)
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
265
        self._global_config = None
266
        self.location = location
267
268
    def _get_global_config(self):
269
        if self._global_config is None:
270
            self._global_config = GlobalConfig()
271
        return self._global_config
272
1442.1.9 by Robert Collins
exact section test passes
273
    def _get_section(self):
274
        """Get the section we should look in for config items.
275
276
        Returns None if none exists. 
277
        TODO: perhaps return a NullSection that thunks through to the 
278
              global config.
279
        """
1185.12.49 by Aaron Bentley
Switched to ConfigObj
280
        sections = self._get_parser()
1442.1.12 by Robert Collins
LocationConfig section retrieval falls into my lap
281
        location_names = self.location.split('/')
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
282
        if self.location.endswith('/'):
283
            del location_names[-1]
1442.1.12 by Robert Collins
LocationConfig section retrieval falls into my lap
284
        matches=[]
1442.1.10 by Robert Collins
explicit over glob test passes
285
        for section in sections:
1442.1.12 by Robert Collins
LocationConfig section retrieval falls into my lap
286
            section_names = section.split('/')
287
            if section.endswith('/'):
288
                del section_names[-1]
289
            names = zip(location_names, section_names)
290
            matched = True
291
            for name in names:
292
                if not fnmatch(name[0], name[1]):
293
                    matched = False
294
                    break
295
            if not matched:
296
                continue
297
            # so, for the common prefix they matched.
298
            # if section is longer, no match.
299
            if len(section_names) > len(location_names):
300
                continue
301
            # if path is longer, and recurse is not true, no match
302
            if len(section_names) < len(location_names):
1185.12.49 by Aaron Bentley
Switched to ConfigObj
303
                try:
1474 by Robert Collins
Merge from Aaron Bentley.
304
                    if not self._get_parser().get_bool(section, 'recurse'):
1185.12.49 by Aaron Bentley
Switched to ConfigObj
305
                        continue
306
                except KeyError:
307
                    pass
1442.1.12 by Robert Collins
LocationConfig section retrieval falls into my lap
308
            matches.append((len(section_names), section))
309
        if not len(matches):
310
            return None
311
        matches.sort(reverse=True)
312
        return matches[0][1]
1442.1.9 by Robert Collins
exact section test passes
313
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
314
    def _gpg_signing_command(self):
1442.1.56 by Robert Collins
gpg_signing_command configuration item
315
        """See Config.gpg_signing_command."""
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
316
        command = super(LocationConfig, self)._gpg_signing_command()
1442.1.56 by Robert Collins
gpg_signing_command configuration item
317
        if command is not None:
318
            return command
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
319
        return self._get_global_config()._gpg_signing_command()
1442.1.56 by Robert Collins
gpg_signing_command configuration item
320
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
321
    def _get_user_id(self):
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
322
        user_id = super(LocationConfig, self)._get_user_id()
323
        if user_id is not None:
324
            return user_id
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
325
        return self._get_global_config()._get_user_id()
326
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
327
    def _get_user_option(self, option_name):
328
        """See Config._get_user_option."""
329
        option_value = super(LocationConfig, 
330
                             self)._get_user_option(option_name)
331
        if option_value is not None:
332
            return option_value
333
        return self._get_global_config()._get_user_option(option_name)
334
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
335
    def _get_signature_checking(self):
336
        """See Config._get_signature_checking."""
337
        check = super(LocationConfig, self)._get_signature_checking()
338
        if check is not None:
339
            return check
340
        return self._get_global_config()._get_signature_checking()
341
1472 by Robert Collins
post commit hook, first pass implementation
342
    def _post_commit(self):
343
        """See Config.post_commit."""
344
        hook = self._get_user_option('post_commit')
345
        if hook is not None:
346
            return hook
347
        return self._get_global_config()._post_commit()
348
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
349
    def set_user_option(self, option, value):
350
        """Save option and its value in the configuration."""
351
        # FIXME: RBC 20051029 This should refresh the parser and also take a
352
        # file lock on branches.conf.
1185.31.39 by John Arbash Meinel
Replacing os.getcwdu() with osutils.getcwd(),
353
        conf_dir = os.path.dirname(self._get_filename())
1185.31.43 by John Arbash Meinel
Reintroduced ensure_config_dir_exists() for sftp
354
        ensure_config_dir_exists(conf_dir)
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
355
        location = self.location
356
        if location.endswith('/'):
357
            location = location[:-1]
358
        if (not location in self._get_parser() and
359
            not location + '/' in self._get_parser()):
360
            self._get_parser()[location]={}
361
        elif location + '/' in self._get_parser():
362
            location = location + '/'
363
        self._get_parser()[location][option]=value
364
        self._get_parser().write()
365
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
366
367
class BranchConfig(Config):
368
    """A configuration object giving the policy for a branch."""
369
370
    def _get_location_config(self):
371
        if self._location_config is None:
372
            self._location_config = LocationConfig(self.branch.base)
373
        return self._location_config
374
375
    def _get_user_id(self):
376
        """Return the full user id for the branch.
377
    
378
        e.g. "John Hacker <jhacker@foo.org>"
379
        This is looked up in the email controlfile for the branch.
380
        """
381
        try:
382
            return (self.branch.controlfile("email", "r") 
383
                    .read()
384
                    .decode(bzrlib.user_encoding)
385
                    .rstrip("\r\n"))
386
        except errors.NoSuchFile, e:
387
            pass
388
        
389
        return self._get_location_config()._get_user_id()
390
1442.1.19 by Robert Collins
BranchConfigs inherit signature_checking policy from their LocationConfig.
391
    def _get_signature_checking(self):
392
        """See Config._get_signature_checking."""
393
        return self._get_location_config()._get_signature_checking()
394
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
395
    def _get_user_option(self, option_name):
396
        """See Config._get_user_option."""
397
        return self._get_location_config()._get_user_option(option_name)
398
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
399
    def _gpg_signing_command(self):
1442.1.56 by Robert Collins
gpg_signing_command configuration item
400
        """See Config.gpg_signing_command."""
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
401
        return self._get_location_config()._gpg_signing_command()
1442.1.56 by Robert Collins
gpg_signing_command configuration item
402
        
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
403
    def __init__(self, branch):
404
        super(BranchConfig, self).__init__()
405
        self._location_config = None
406
        self.branch = branch
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
407
1472 by Robert Collins
post commit hook, first pass implementation
408
    def _post_commit(self):
409
        """See Config.post_commit."""
410
        return self._get_location_config()._post_commit()
411
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
412
1185.31.43 by John Arbash Meinel
Reintroduced ensure_config_dir_exists() for sftp
413
def ensure_config_dir_exists(path=None):
414
    """Make sure a configuration directory exists.
415
    This makes sure that the directory exists.
416
    On windows, since configuration directories are 2 levels deep,
417
    it makes sure both the directory and the parent directory exists.
418
    """
419
    if path is None:
420
        path = config_dir()
421
    if not os.path.isdir(path):
422
        if sys.platform == 'win32':
423
            parent_dir = os.path.dirname(path)
424
            if not os.path.isdir(parent_dir):
425
                mutter('creating config parent directory: %r', parent_dir)
426
            os.mkdir(parent_dir)
427
        mutter('creating config directory: %r', path)
428
        os.mkdir(path)
429
1532 by Robert Collins
Merge in John Meinels integration branch.
430
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
431
def config_dir():
432
    """Return per-user configuration directory.
433
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
434
    By default this is ~/.bazaar/
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
435
    
436
    TODO: Global option --config-dir to override this.
437
    """
1185.38.1 by John Arbash Meinel
Adding my win32 patch for moving the home directory.
438
    base = os.environ.get('BZR_HOME', None)
439
    if sys.platform == 'win32':
440
        if base is None:
441
            base = os.environ.get('APPDATA', None)
442
        if base is None:
443
            base = os.environ.get('HOME', None)
444
        if base is None:
445
            raise BzrError('You must have one of BZR_HOME, APPDATA, or HOME set')
1185.31.32 by John Arbash Meinel
Updated the bzr sourcecode to use bzrlib.osutils.pathjoin rather than os.path.join to enforce internal use of / instead of \
446
        return pathjoin(base, 'bazaar', '2.0')
1185.38.1 by John Arbash Meinel
Adding my win32 patch for moving the home directory.
447
    else:
448
        # cygwin, linux, and darwin all have a $HOME directory
449
        if base is None:
450
            base = os.path.expanduser("~")
1185.31.32 by John Arbash Meinel
Updated the bzr sourcecode to use bzrlib.osutils.pathjoin rather than os.path.join to enforce internal use of / instead of \
451
        return pathjoin(base, ".bazaar")
452
453
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
454
def config_filename():
455
    """Return per-user configuration ini file filename."""
1185.31.32 by John Arbash Meinel
Updated the bzr sourcecode to use bzrlib.osutils.pathjoin rather than os.path.join to enforce internal use of / instead of \
456
    return pathjoin(config_dir(), 'bazaar.conf')
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
457
458
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
459
def branches_config_filename():
460
    """Return per-user configuration ini file filename."""
1185.31.32 by John Arbash Meinel
Updated the bzr sourcecode to use bzrlib.osutils.pathjoin rather than os.path.join to enforce internal use of / instead of \
461
    return pathjoin(config_dir(), 'branches.conf')
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
462
463
464
def _auto_user_id():
465
    """Calculate automatic user identification.
466
467
    Returns (realname, email).
468
469
    Only used when none is set in the environment or the id file.
470
471
    This previously used the FQDN as the default domain, but that can
472
    be very slow on machines where DNS is broken.  So now we simply
473
    use the hostname.
474
    """
475
    import socket
476
477
    # XXX: Any good way to get real user name on win32?
478
479
    try:
480
        import pwd
481
        uid = os.getuid()
482
        w = pwd.getpwuid(uid)
483
        gecos = w.pw_gecos.decode(bzrlib.user_encoding)
484
        username = w.pw_name.decode(bzrlib.user_encoding)
485
        comma = gecos.find(',')
486
        if comma == -1:
487
            realname = gecos
488
        else:
489
            realname = gecos[:comma]
490
        if not realname:
491
            realname = username
492
493
    except ImportError:
494
        import getpass
495
        realname = username = getpass.getuser().decode(bzrlib.user_encoding)
496
497
    return realname, (username + '@' + socket.gethostname())
498
499
1185.16.52 by Martin Pool
- add extract_email_address
500
def extract_email_address(e):
501
    """Return just the address part of an email string.
502
    
503
    That is just the user@domain part, nothing else. 
504
    This part is required to contain only ascii characters.
505
    If it can't be extracted, raises an error.
506
    
507
    >>> extract_email_address('Jane Tester <jane@test.com>')
508
    "jane@test.com"
509
    """
510
    m = re.search(r'[\w+.-]+@[\w+.-]+', e)
511
    if not m:
1185.33.31 by Martin Pool
Make annotate cope better with revisions committed without a valid
512
        raise errors.BzrError("%r doesn't seem to contain "
513
                              "a reasonable email address" % e)
1185.16.52 by Martin Pool
- add extract_email_address
514
    return m.group(0)
1185.35.11 by Aaron Bentley
Added support for branch nicks
515
516
class TreeConfig(object):
517
    """Branch configuration data associated with its contents, not location"""
518
    def __init__(self, branch):
519
        self.branch = branch
520
521
    def _get_config(self):
522
        try:
1185.35.12 by Aaron Bentley
Got writes of existing tree configs working.
523
            obj = ConfigObj(self.branch.controlfile('branch.conf',
524
                                                    'rb').readlines())
1185.35.27 by Aaron Bentley
Got unicode nicks working properly, even when gannotate is installed.
525
            obj.decode('UTF-8')
1185.35.11 by Aaron Bentley
Added support for branch nicks
526
        except errors.NoSuchFile:
527
            obj = ConfigObj()
528
        return obj
529
530
    def get_option(self, name, section=None, default=None):
531
        self.branch.lock_read()
532
        try:
533
            obj = self._get_config()
534
            try:
535
                if section is not None:
536
                    obj[section]
537
                result = obj[name]
538
            except KeyError:
539
                result = default
540
        finally:
541
            self.branch.unlock()
542
        return result
543
544
    def set_option(self, value, name, section=None):
545
        """Set a per-branch configuration option"""
546
        self.branch.lock_write()
547
        try:
548
            cfg_obj = self._get_config()
549
            if section is None:
550
                obj = cfg_obj
551
            else:
552
                try:
553
                    obj = cfg_obj[section]
554
                except KeyError:
555
                    cfg_obj[section] = {}
556
                    obj = cfg_obj[section]
557
            obj[name] = value
1185.35.27 by Aaron Bentley
Got unicode nicks working properly, even when gannotate is installed.
558
            cfg_obj.encode('UTF-8')
1185.35.11 by Aaron Bentley
Added support for branch nicks
559
            out_file = StringIO(''.join([l+'\n' for l in cfg_obj.write()]))
560
            out_file.seek(0)
1185.35.27 by Aaron Bentley
Got unicode nicks working properly, even when gannotate is installed.
561
            self.branch.put_controlfile('branch.conf', out_file, encode=False)
1185.35.11 by Aaron Bentley
Added support for branch nicks
562
        finally:
563
            self.branch.unlock()