~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/config.py

  • Committer: Martin Pool
  • Date: 2006-06-20 03:57:11 UTC
  • mto: This revision was merged to the branch mainline in revision 1798.
  • Revision ID: mbp@sourcefrog.net-20060620035711-400bb6b6bc6ff95b
Add pyflakes makefile target; fix many warnings

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 Canonical Ltd
 
1
# Copyright (C) 2005 by Canonical Ltd
2
2
#   Authors: Robert Collins <robert.collins@canonical.com>
3
 
#            and others
4
3
#
5
4
# This program is free software; you can redistribute it and/or modify
6
5
# it under the terms of the GNU General Public License as published by
14
13
#
15
14
# You should have received a copy of the GNU General Public License
16
15
# along with this program; if not, write to the Free Software
17
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18
17
 
19
18
"""Configuration that affects the behaviour of Bazaar.
20
19
 
21
20
Currently this configuration resides in ~/.bazaar/bazaar.conf
22
 
and ~/.bazaar/locations.conf, which is written to by bzr.
 
21
and ~/.bazaar/branches.conf, which is written to by bzr.
23
22
 
24
23
In bazaar.conf the following options may be set:
25
24
[DEFAULT]
30
29
gpg_signing_command=name-of-program
31
30
log_format=name-of-format
32
31
 
33
 
in locations.conf, you specify the url of a branch and options for it.
 
32
in branches.conf, you specify the url of a branch and options for it.
34
33
Wildcards may be used - * and ? as normal in shell completion. Options
35
 
set in both bazaar.conf and locations.conf are overridden by the locations.conf
 
34
set in both bazaar.conf and branches.conf are overridden by the branches.conf
36
35
setting.
37
36
[/home/robertc/source]
38
37
recurse=False|True(default)
39
38
email= as above
40
 
check_signatures= as above
 
39
check_signatures= as above 
41
40
create_signatures= as above.
42
41
 
43
42
explanation of options
45
44
editor - this option sets the pop up editor to use during commits.
46
45
email - this option sets the user id bzr will use when committing.
47
46
check_signatures - this option controls whether bzr will require good gpg
48
 
                   signatures, ignore them, or check them if they are
 
47
                   signatures, ignore them, or check them if they are 
49
48
                   present.
50
 
create_signatures - this option controls whether bzr will always create
 
49
create_signatures - this option controls whether bzr will always create 
51
50
                    gpg signatures, never create them, or create them if the
52
51
                    branch is configured to require them.
53
 
log_format - this option sets the default log format.  Possible values are
54
 
             long, short, line, or a plugin can register new formats.
 
52
                    NB: This option is planned, but not implemented yet.
 
53
log_format - This options set the default log format.  Options are long, 
 
54
             short, line, or a plugin can register new formats
55
55
 
56
56
In bazaar.conf you can also define aliases in the ALIASES sections, example
57
57
 
62
62
up=pull
63
63
"""
64
64
 
 
65
 
 
66
import errno
65
67
import os
66
68
import sys
67
 
 
68
 
from bzrlib import commands
69
 
from bzrlib.decorators import needs_write_lock
70
 
from bzrlib.lazy_import import lazy_import
71
 
lazy_import(globals(), """
72
 
import errno
73
 
import fnmatch
 
69
from fnmatch import fnmatch
74
70
import re
75
 
from cStringIO import StringIO
76
71
 
77
72
import bzrlib
78
 
from bzrlib import (
79
 
    atomicfile,
80
 
    bzrdir,
81
 
    debug,
82
 
    errors,
83
 
    lockdir,
84
 
    mail_client,
85
 
    osutils,
86
 
    registry,
87
 
    symbol_versioning,
88
 
    trace,
89
 
    transport,
90
 
    ui,
91
 
    urlutils,
92
 
    win32utils,
93
 
    )
94
 
from bzrlib.util.configobj import configobj
95
 
""")
96
 
 
 
73
import bzrlib.errors as errors
 
74
from bzrlib.osutils import pathjoin
 
75
from bzrlib.trace import mutter
 
76
import bzrlib.util.configobj.configobj as configobj
 
77
from StringIO import StringIO
97
78
 
98
79
CHECK_IF_POSSIBLE=0
99
80
CHECK_ALWAYS=1
100
81
CHECK_NEVER=2
101
82
 
102
83
 
103
 
SIGN_WHEN_REQUIRED=0
104
 
SIGN_ALWAYS=1
105
 
SIGN_NEVER=2
106
 
 
107
 
 
108
 
POLICY_NONE = 0
109
 
POLICY_NORECURSE = 1
110
 
POLICY_APPENDPATH = 2
111
 
 
112
 
_policy_name = {
113
 
    POLICY_NONE: None,
114
 
    POLICY_NORECURSE: 'norecurse',
115
 
    POLICY_APPENDPATH: 'appendpath',
116
 
    }
117
 
_policy_value = {
118
 
    None: POLICY_NONE,
119
 
    'none': POLICY_NONE,
120
 
    'norecurse': POLICY_NORECURSE,
121
 
    'appendpath': POLICY_APPENDPATH,
122
 
    }
123
 
 
124
 
 
125
 
STORE_LOCATION = POLICY_NONE
126
 
STORE_LOCATION_NORECURSE = POLICY_NORECURSE
127
 
STORE_LOCATION_APPENDPATH = POLICY_APPENDPATH
128
 
STORE_BRANCH = 3
129
 
STORE_GLOBAL = 4
130
 
 
131
 
_ConfigObj = None
132
 
def ConfigObj(*args, **kwargs):
133
 
    global _ConfigObj
134
 
    if _ConfigObj is None:
135
 
        class ConfigObj(configobj.ConfigObj):
136
 
 
137
 
            def get_bool(self, section, key):
138
 
                return self[section].as_bool(key)
139
 
 
140
 
            def get_value(self, section, name):
141
 
                # Try [] for the old DEFAULT section.
142
 
                if section == "DEFAULT":
143
 
                    try:
144
 
                        return self[name]
145
 
                    except KeyError:
146
 
                        pass
147
 
                return self[section][name]
148
 
        _ConfigObj = ConfigObj
149
 
    return _ConfigObj(*args, **kwargs)
 
84
class ConfigObj(configobj.ConfigObj):
 
85
 
 
86
    def get_bool(self, section, key):
 
87
        return self[section].as_bool(key)
 
88
 
 
89
    def get_value(self, section, name):
 
90
        # Try [] for the old DEFAULT section.
 
91
        if section == "DEFAULT":
 
92
            try:
 
93
                return self[name]
 
94
            except KeyError:
 
95
                pass
 
96
        return self[section][name]
150
97
 
151
98
 
152
99
class Config(object):
153
100
    """A configuration policy - what username, editor, gpg needs etc."""
154
101
 
155
 
    def __init__(self):
156
 
        super(Config, self).__init__()
157
 
 
158
 
    def config_id(self):
159
 
        """Returns a unique ID for the config."""
160
 
        raise NotImplementedError(self.config_id)
161
 
 
162
102
    def get_editor(self):
163
103
        """Get the users pop up editor."""
164
104
        raise NotImplementedError
165
105
 
166
 
    def get_change_editor(self, old_tree, new_tree):
167
 
        from bzrlib import diff
168
 
        cmd = self._get_change_editor()
169
 
        if cmd is None:
170
 
            return None
171
 
        return diff.DiffFromTool.from_string(cmd, old_tree, new_tree,
172
 
                                             sys.stdout)
173
 
 
174
 
 
175
 
    def get_mail_client(self):
176
 
        """Get a mail client to use"""
177
 
        selected_client = self.get_user_option('mail_client')
178
 
        _registry = mail_client.mail_client_registry
179
 
        try:
180
 
            mail_client_class = _registry.get(selected_client)
181
 
        except KeyError:
182
 
            raise errors.UnknownMailClient(selected_client)
183
 
        return mail_client_class(self)
184
 
 
185
106
    def _get_signature_checking(self):
186
107
        """Template method to override signature checking policy."""
187
108
 
188
 
    def _get_signing_policy(self):
189
 
        """Template method to override signature creation policy."""
190
 
 
191
109
    def _get_user_option(self, option_name):
192
110
        """Template method to provide a user option."""
193
111
        return None
196
114
        """Get a generic option - no special process, no default."""
197
115
        return self._get_user_option(option_name)
198
116
 
199
 
    def get_user_option_as_bool(self, option_name):
200
 
        """Get a generic option as a boolean - no special process, no default.
201
 
 
202
 
        :return None if the option doesn't exist or its value can't be
203
 
            interpreted as a boolean. Returns True or False otherwise.
204
 
        """
205
 
        s = self._get_user_option(option_name)
206
 
        if s is None:
207
 
            # The option doesn't exist
208
 
            return None
209
 
        val = ui.bool_from_string(s)
210
 
        if val is None:
211
 
            # The value can't be interpreted as a boolean
212
 
            trace.warning('Value "%s" is not a boolean for "%s"',
213
 
                          s, option_name)
214
 
        return val
215
 
 
216
 
    def get_user_option_as_list(self, option_name):
217
 
        """Get a generic option as a list - no special process, no default.
218
 
 
219
 
        :return None if the option doesn't exist. Returns the value as a list
220
 
            otherwise.
221
 
        """
222
 
        l = self._get_user_option(option_name)
223
 
        if isinstance(l, (str, unicode)):
224
 
            # A single value, most probably the user forgot the final ','
225
 
            l = [l]
226
 
        return l
227
 
 
228
117
    def gpg_signing_command(self):
229
118
        """What program should be used to sign signatures?"""
230
119
        result = self._gpg_signing_command()
247
136
        """See log_format()."""
248
137
        return None
249
138
 
 
139
    def __init__(self):
 
140
        super(Config, self).__init__()
 
141
 
250
142
    def post_commit(self):
251
143
        """An ordered list of python functions to call.
252
144
 
264
156
 
265
157
    def username(self):
266
158
        """Return email-style username.
267
 
 
 
159
    
268
160
        Something similar to 'Martin Pool <mbp@sourcefrog.net>'
269
 
 
270
 
        $BZR_EMAIL can be set to override this, then
 
161
        
 
162
        $BZREMAIL can be set to override this, then
271
163
        the concrete policy type is checked, and finally
272
164
        $EMAIL is examined.
273
 
        If no username can be found, errors.NoWhoami exception is raised.
274
 
 
 
165
        If none is found, a reasonable default is (hopefully)
 
166
        created.
 
167
    
275
168
        TODO: Check it's reasonably well-formed.
276
169
        """
277
 
        v = os.environ.get('BZR_EMAIL')
 
170
        v = os.environ.get('BZREMAIL')
278
171
        if v:
279
 
            return v.decode(osutils.get_user_encoding())
280
 
 
 
172
            return v.decode(bzrlib.user_encoding)
 
173
    
281
174
        v = self._get_user_id()
282
175
        if v:
283
176
            return v
284
 
 
 
177
        
285
178
        v = os.environ.get('EMAIL')
286
179
        if v:
287
 
            return v.decode(osutils.get_user_encoding())
288
 
 
289
 
        raise errors.NoWhoami()
290
 
 
291
 
    def ensure_username(self):
292
 
        """Raise errors.NoWhoami if username is not set.
293
 
 
294
 
        This method relies on the username() function raising the error.
295
 
        """
296
 
        self.username()
 
180
            return v.decode(bzrlib.user_encoding)
 
181
 
 
182
        name, email = _auto_user_id()
 
183
        if name:
 
184
            return '%s <%s>' % (name, email)
 
185
        else:
 
186
            return email
297
187
 
298
188
    def signature_checking(self):
299
189
        """What is the current policy for signature checking?."""
302
192
            return policy
303
193
        return CHECK_IF_POSSIBLE
304
194
 
305
 
    def signing_policy(self):
306
 
        """What is the current policy for signature checking?."""
307
 
        policy = self._get_signing_policy()
308
 
        if policy is not None:
309
 
            return policy
310
 
        return SIGN_WHEN_REQUIRED
311
 
 
312
195
    def signature_needed(self):
313
196
        """Is a signature needed when committing ?."""
314
 
        policy = self._get_signing_policy()
315
 
        if policy is None:
316
 
            policy = self._get_signature_checking()
317
 
            if policy is not None:
318
 
                trace.warning("Please use create_signatures,"
319
 
                              " not check_signatures to set signing policy.")
320
 
            if policy == CHECK_ALWAYS:
321
 
                return True
322
 
        elif policy == SIGN_ALWAYS:
 
197
        policy = self._get_signature_checking()
 
198
        if policy == CHECK_ALWAYS:
323
199
            return True
324
200
        return False
325
201
 
329
205
    def _get_alias(self, value):
330
206
        pass
331
207
 
332
 
    def get_nickname(self):
333
 
        return self._get_nickname()
334
 
 
335
 
    def _get_nickname(self):
336
 
        return None
337
 
 
338
 
    def get_bzr_remote_path(self):
339
 
        try:
340
 
            return os.environ['BZR_REMOTE_PATH']
341
 
        except KeyError:
342
 
            path = self.get_user_option("bzr_remote_path")
343
 
            if path is None:
344
 
                path = 'bzr'
345
 
            return path
346
 
 
347
 
    def suppress_warning(self, warning):
348
 
        """Should the warning be suppressed or emitted.
349
 
 
350
 
        :param warning: The name of the warning being tested.
351
 
 
352
 
        :returns: True if the warning should be suppressed, False otherwise.
353
 
        """
354
 
        warnings = self.get_user_option_as_list('suppress_warnings')
355
 
        if warnings is None or warning not in warnings:
356
 
            return False
357
 
        else:
358
 
            return True
359
 
 
360
208
 
361
209
class IniBasedConfig(Config):
362
210
    """A configuration policy that draws from ini files."""
363
211
 
364
 
    def __init__(self, get_filename=symbol_versioning.DEPRECATED_PARAMETER,
365
 
                 file_name=None):
366
 
        """Base class for configuration files using an ini-like syntax.
367
 
 
368
 
        :param file_name: The configuration file path.
369
 
        """
370
 
        super(IniBasedConfig, self).__init__()
371
 
        self.file_name = file_name
372
 
        if symbol_versioning.deprecated_passed(get_filename):
373
 
            symbol_versioning.warn(
374
 
                'IniBasedConfig.__init__(get_filename) was deprecated in 2.3.'
375
 
                ' Use file_name instead.',
376
 
                DeprecationWarning,
377
 
                stacklevel=2)
378
 
            if get_filename is not None:
379
 
                self.file_name = get_filename()
380
 
        else:
381
 
            self.file_name = file_name
382
 
        self._content = None
383
 
        self._parser = None
384
 
 
385
 
    @classmethod
386
 
    def from_string(cls, str_or_unicode, file_name=None, save=False):
387
 
        """Create a config object from a string.
388
 
 
389
 
        :param str_or_unicode: A string representing the file content. This will
390
 
            be utf-8 encoded.
391
 
 
392
 
        :param file_name: The configuration file path.
393
 
 
394
 
        :param _save: Whether the file should be saved upon creation.
395
 
        """
396
 
        conf = cls(file_name=file_name)
397
 
        conf._create_from_string(str_or_unicode, save)
398
 
        return conf
399
 
 
400
 
    def _create_from_string(self, str_or_unicode, save):
401
 
        self._content = StringIO(str_or_unicode.encode('utf-8'))
402
 
        # Some tests use in-memory configs, some other always need the config
403
 
        # file to exist on disk.
404
 
        if save:
405
 
            self._write_config_file()
406
 
 
407
 
    def _get_parser(self, file=symbol_versioning.DEPRECATED_PARAMETER):
 
212
    def _get_parser(self, file=None):
408
213
        if self._parser is not None:
409
214
            return self._parser
410
 
        if symbol_versioning.deprecated_passed(file):
411
 
            symbol_versioning.warn(
412
 
                'IniBasedConfig._get_parser(file=xxx) was deprecated in 2.3.'
413
 
                ' Use IniBasedConfig(_content=xxx) instead.',
414
 
                DeprecationWarning,
415
 
                stacklevel=2)
416
 
        if self._content is not None:
417
 
            co_input = self._content
418
 
        elif self.file_name is None:
419
 
            raise AssertionError('We have no content to create the config')
 
215
        if file is None:
 
216
            input = self._get_filename()
420
217
        else:
421
 
            co_input = self.file_name
 
218
            input = file
422
219
        try:
423
 
            self._parser = ConfigObj(co_input, encoding='utf-8')
 
220
            self._parser = ConfigObj(input, encoding='utf-8')
424
221
        except configobj.ConfigObjError, e:
425
222
            raise errors.ParseConfigError(e.errors, e.config.filename)
426
 
        # Make sure self.reload() will use the right file name
427
 
        self._parser.filename = self.file_name
428
223
        return self._parser
429
224
 
430
 
    def reload(self):
431
 
        """Reload the config file from disk."""
432
 
        if self.file_name is None:
433
 
            raise AssertionError('We need a file name to reload the config')
434
 
        if self._parser is not None:
435
 
            self._parser.reload()
436
 
 
437
 
    def _get_matching_sections(self):
438
 
        """Return an ordered list of (section_name, extra_path) pairs.
439
 
 
440
 
        If the section contains inherited configuration, extra_path is
441
 
        a string containing the additional path components.
442
 
        """
443
 
        section = self._get_section()
444
 
        if section is not None:
445
 
            return [(section, '')]
446
 
        else:
447
 
            return []
448
 
 
449
225
    def _get_section(self):
450
226
        """Override this to define the section used by the config."""
451
227
        return "DEFAULT"
452
228
 
453
 
    def _get_sections(self, name=None):
454
 
        """Returns an iterator of the sections specified by ``name``.
455
 
 
456
 
        :param name: The section name. If None is supplied, the default
457
 
            configurations are yielded.
458
 
 
459
 
        :return: A tuple (name, section, config_id) for all sections that will
460
 
            be walked by user_get_option() in the 'right' order. The first one
461
 
            is where set_user_option() will update the value.
462
 
        """
463
 
        parser = self._get_parser()
464
 
        if name is not None:
465
 
            yield (name, parser[name], self.config_id())
466
 
        else:
467
 
            # No section name has been given so we fallback to the configobj
468
 
            # itself which holds the variables defined outside of any section.
469
 
            yield (None, parser, self.config_id())
470
 
 
471
 
    def _get_options(self, sections=None):
472
 
        """Return an ordered list of (name, value, section, config_id) tuples.
473
 
 
474
 
        All options are returned with their associated value and the section
475
 
        they appeared in. ``config_id`` is a unique identifier for the
476
 
        configuration file the option is defined in.
477
 
 
478
 
        :param sections: Default to ``_get_matching_sections`` if not
479
 
            specified. This gives a better control to daughter classes about
480
 
            which sections should be searched. This is a list of (name,
481
 
            configobj) tuples.
482
 
        """
483
 
        opts = []
484
 
        if sections is None:
485
 
            parser = self._get_parser()
486
 
            sections = []
487
 
            for (section_name, _) in self._get_matching_sections():
488
 
                try:
489
 
                    section = parser[section_name]
490
 
                except KeyError:
491
 
                    # This could happen for an empty file for which we define a
492
 
                    # DEFAULT section. FIXME: Force callers to provide sections
493
 
                    # instead ? -- vila 20100930
494
 
                    continue
495
 
                sections.append((section_name, section))
496
 
        config_id = self.config_id()
497
 
        for (section_name, section) in sections:
498
 
            for (name, value) in section.iteritems():
499
 
                yield (name, value, section_name, config_id)
500
 
 
501
 
    def _get_option_policy(self, section, option_name):
502
 
        """Return the policy for the given (section, option_name) pair."""
503
 
        return POLICY_NONE
504
 
 
505
 
    def _get_change_editor(self):
506
 
        return self.get_user_option('change_editor')
507
 
 
508
229
    def _get_signature_checking(self):
509
230
        """See Config._get_signature_checking."""
510
231
        policy = self._get_user_option('check_signatures')
511
232
        if policy:
512
233
            return self._string_to_signature_policy(policy)
513
234
 
514
 
    def _get_signing_policy(self):
515
 
        """See Config._get_signing_policy"""
516
 
        policy = self._get_user_option('create_signatures')
517
 
        if policy:
518
 
            return self._string_to_signing_policy(policy)
519
 
 
520
235
    def _get_user_id(self):
521
236
        """Get the user id from the 'email' key in the current section."""
522
237
        return self._get_user_option('email')
523
238
 
524
239
    def _get_user_option(self, option_name):
525
240
        """See Config._get_user_option."""
526
 
        for (section, extra_path) in self._get_matching_sections():
527
 
            try:
528
 
                value = self._get_parser().get_value(section, option_name)
529
 
            except KeyError:
530
 
                continue
531
 
            policy = self._get_option_policy(section, option_name)
532
 
            if policy == POLICY_NONE:
533
 
                return value
534
 
            elif policy == POLICY_NORECURSE:
535
 
                # norecurse items only apply to the exact path
536
 
                if extra_path:
537
 
                    continue
538
 
                else:
539
 
                    return value
540
 
            elif policy == POLICY_APPENDPATH:
541
 
                if extra_path:
542
 
                    value = urlutils.join(value, extra_path)
543
 
                return value
544
 
            else:
545
 
                raise AssertionError('Unexpected config policy %r' % policy)
546
 
        else:
547
 
            return None
 
241
        try:
 
242
            return self._get_parser().get_value(self._get_section(),
 
243
                                                option_name)
 
244
        except KeyError:
 
245
            pass
548
246
 
549
247
    def _gpg_signing_command(self):
550
248
        """See Config.gpg_signing_command."""
554
252
        """See Config.log_format."""
555
253
        return self._get_user_option('log_format')
556
254
 
 
255
    def __init__(self, get_filename):
 
256
        super(IniBasedConfig, self).__init__()
 
257
        self._get_filename = get_filename
 
258
        self._parser = None
 
259
        
557
260
    def _post_commit(self):
558
261
        """See Config.post_commit."""
559
262
        return self._get_user_option('post_commit')
569
272
        raise errors.BzrError("Invalid signatures policy '%s'"
570
273
                              % signature_string)
571
274
 
572
 
    def _string_to_signing_policy(self, signature_string):
573
 
        """Convert a string to a signing policy."""
574
 
        if signature_string.lower() == 'when-required':
575
 
            return SIGN_WHEN_REQUIRED
576
 
        if signature_string.lower() == 'never':
577
 
            return SIGN_NEVER
578
 
        if signature_string.lower() == 'always':
579
 
            return SIGN_ALWAYS
580
 
        raise errors.BzrError("Invalid signing policy '%s'"
581
 
                              % signature_string)
582
 
 
583
275
    def _get_alias(self, value):
584
276
        try:
585
 
            return self._get_parser().get_value("ALIASES",
 
277
            return self._get_parser().get_value("ALIASES", 
586
278
                                                value)
587
279
        except KeyError:
588
280
            pass
589
281
 
590
 
    def _get_nickname(self):
591
 
        return self.get_user_option('nickname')
592
 
 
593
 
    def remove_user_option(self, option_name, section_name=None):
594
 
        """Remove a user option and save the configuration file.
595
 
 
596
 
        :param option_name: The option to be removed.
597
 
 
598
 
        :param section_name: The section the option is defined in, default to
599
 
            the default section.
600
 
        """
601
 
        self.reload()
602
 
        parser = self._get_parser()
603
 
        if section_name is None:
604
 
            section = parser
605
 
        else:
606
 
            section = parser[section_name]
607
 
        try:
608
 
            del section[option_name]
609
 
        except KeyError:
610
 
            raise errors.NoSuchConfigOption(option_name)
611
 
        self._write_config_file()
612
 
 
613
 
    def _write_config_file(self):
614
 
        if self.file_name is None:
615
 
            raise AssertionError('We cannot save, self.file_name is None')
616
 
        conf_dir = os.path.dirname(self.file_name)
617
 
        ensure_config_dir_exists(conf_dir)
618
 
        atomic_file = atomicfile.AtomicFile(self.file_name)
619
 
        self._get_parser().write(atomic_file)
620
 
        atomic_file.commit()
621
 
        atomic_file.close()
622
 
        osutils.copy_ownership_from_path(self.file_name)
623
 
 
624
 
 
625
 
class LockableConfig(IniBasedConfig):
626
 
    """A configuration needing explicit locking for access.
627
 
 
628
 
    If several processes try to write the config file, the accesses need to be
629
 
    serialized.
630
 
 
631
 
    Daughter classes should decorate all methods that update a config with the
632
 
    ``@needs_write_lock`` decorator (they call, directly or indirectly, the
633
 
    ``_write_config_file()`` method. These methods (typically ``set_option()``
634
 
    and variants must reload the config file from disk before calling
635
 
    ``_write_config_file()``), this can be achieved by calling the
636
 
    ``self.reload()`` method. Note that the lock scope should cover both the
637
 
    reading and the writing of the config file which is why the decorator can't
638
 
    be applied to ``_write_config_file()`` only.
639
 
 
640
 
    This should be enough to implement the following logic:
641
 
    - lock for exclusive write access,
642
 
    - reload the config file from disk,
643
 
    - set the new value
644
 
    - unlock
645
 
 
646
 
    This logic guarantees that a writer can update a value without erasing an
647
 
    update made by another writer.
648
 
    """
649
 
 
650
 
    lock_name = 'lock'
651
 
 
652
 
    def __init__(self, file_name):
653
 
        super(LockableConfig, self).__init__(file_name=file_name)
654
 
        self.dir = osutils.dirname(osutils.safe_unicode(self.file_name))
655
 
        self.transport = transport.get_transport(self.dir)
656
 
        self._lock = lockdir.LockDir(self.transport, 'lock')
657
 
 
658
 
    def _create_from_string(self, unicode_bytes, save):
659
 
        super(LockableConfig, self)._create_from_string(unicode_bytes, False)
660
 
        if save:
661
 
            # We need to handle the saving here (as opposed to IniBasedConfig)
662
 
            # to be able to lock
663
 
            self.lock_write()
664
 
            self._write_config_file()
665
 
            self.unlock()
666
 
 
667
 
    def lock_write(self, token=None):
668
 
        """Takes a write lock in the directory containing the config file.
669
 
 
670
 
        If the directory doesn't exist it is created.
671
 
        """
672
 
        ensure_config_dir_exists(self.dir)
673
 
        return self._lock.lock_write(token)
674
 
 
675
 
    def unlock(self):
676
 
        self._lock.unlock()
677
 
 
678
 
    def break_lock(self):
679
 
        self._lock.break_lock()
680
 
 
681
 
    @needs_write_lock
682
 
    def remove_user_option(self, option_name, section_name=None):
683
 
        super(LockableConfig, self).remove_user_option(option_name,
684
 
                                                       section_name)
685
 
 
686
 
    def _write_config_file(self):
687
 
        if self._lock is None or not self._lock.is_held:
688
 
            # NB: if the following exception is raised it probably means a
689
 
            # missing @needs_write_lock decorator on one of the callers.
690
 
            raise errors.ObjectNotLocked(self)
691
 
        super(LockableConfig, self)._write_config_file()
692
 
 
693
 
 
694
 
class GlobalConfig(LockableConfig):
 
282
 
 
283
class GlobalConfig(IniBasedConfig):
695
284
    """The configuration that should be used for a specific location."""
696
285
 
697
 
    def __init__(self):
698
 
        super(GlobalConfig, self).__init__(file_name=config_filename())
699
 
 
700
 
    def config_id(self):
701
 
        return 'bazaar'
702
 
 
703
 
    @classmethod
704
 
    def from_string(cls, str_or_unicode, save=False):
705
 
        """Create a config object from a string.
706
 
 
707
 
        :param str_or_unicode: A string representing the file content. This
708
 
            will be utf-8 encoded.
709
 
 
710
 
        :param save: Whether the file should be saved upon creation.
711
 
        """
712
 
        conf = cls()
713
 
        conf._create_from_string(str_or_unicode, save)
714
 
        return conf
715
 
 
716
286
    def get_editor(self):
717
287
        return self._get_user_option('editor')
718
288
 
719
 
    @needs_write_lock
720
 
    def set_user_option(self, option, value):
721
 
        """Save option and its value in the configuration."""
722
 
        self._set_option(option, value, 'DEFAULT')
723
 
 
724
 
    def get_aliases(self):
725
 
        """Return the aliases section."""
726
 
        if 'ALIASES' in self._get_parser():
727
 
            return self._get_parser()['ALIASES']
728
 
        else:
729
 
            return {}
730
 
 
731
 
    @needs_write_lock
732
 
    def set_alias(self, alias_name, alias_command):
733
 
        """Save the alias in the configuration."""
734
 
        self._set_option(alias_name, alias_command, 'ALIASES')
735
 
 
736
 
    @needs_write_lock
737
 
    def unset_alias(self, alias_name):
738
 
        """Unset an existing alias."""
739
 
        self.reload()
740
 
        aliases = self._get_parser().get('ALIASES')
741
 
        if not aliases or alias_name not in aliases:
742
 
            raise errors.NoSuchAlias(alias_name)
743
 
        del aliases[alias_name]
744
 
        self._write_config_file()
745
 
 
746
 
    def _set_option(self, option, value, section):
747
 
        self.reload()
748
 
        self._get_parser().setdefault(section, {})[option] = value
749
 
        self._write_config_file()
750
 
 
751
 
 
752
 
    def _get_sections(self, name=None):
753
 
        """See IniBasedConfig._get_sections()."""
754
 
        parser = self._get_parser()
755
 
        # We don't give access to options defined outside of any section, we
756
 
        # used the DEFAULT section by... default.
757
 
        if name in (None, 'DEFAULT'):
758
 
            # This could happen for an empty file where the DEFAULT section
759
 
            # doesn't exist yet. So we force DEFAULT when yielding
760
 
            name = 'DEFAULT'
761
 
            if 'DEFAULT' not in parser:
762
 
               parser['DEFAULT']= {}
763
 
        yield (name, parser[name], self.config_id())
764
 
 
765
 
    @needs_write_lock
766
 
    def remove_user_option(self, option_name, section_name=None):
767
 
        if section_name is None:
768
 
            # We need to force the default section.
769
 
            section_name = 'DEFAULT'
770
 
        # We need to avoid the LockableConfig implementation or we'll lock
771
 
        # twice
772
 
        super(LockableConfig, self).remove_user_option(option_name,
773
 
                                                       section_name)
774
 
 
775
 
 
776
 
class LocationConfig(LockableConfig):
 
289
    def __init__(self):
 
290
        super(GlobalConfig, self).__init__(config_filename)
 
291
 
 
292
 
 
293
class LocationConfig(IniBasedConfig):
777
294
    """A configuration object that gives the policy for a location."""
778
295
 
779
296
    def __init__(self, location):
780
 
        super(LocationConfig, self).__init__(
781
 
            file_name=locations_config_filename())
782
 
        # local file locations are looked up by local path, rather than
783
 
        # by file url. This is because the config file is a user
784
 
        # file, and we would rather not expose the user to file urls.
785
 
        if location.startswith('file://'):
786
 
            location = urlutils.local_path_from_url(location)
 
297
        super(LocationConfig, self).__init__(branches_config_filename)
 
298
        self._global_config = None
787
299
        self.location = location
788
300
 
789
 
    def config_id(self):
790
 
        return 'locations'
791
 
 
792
 
    @classmethod
793
 
    def from_string(cls, str_or_unicode, location, save=False):
794
 
        """Create a config object from a string.
795
 
 
796
 
        :param str_or_unicode: A string representing the file content. This will
797
 
            be utf-8 encoded.
798
 
 
799
 
        :param location: The location url to filter the configuration.
800
 
 
801
 
        :param save: Whether the file should be saved upon creation.
 
301
    def _get_global_config(self):
 
302
        if self._global_config is None:
 
303
            self._global_config = GlobalConfig()
 
304
        return self._global_config
 
305
 
 
306
    def _get_section(self):
 
307
        """Get the section we should look in for config items.
 
308
 
 
309
        Returns None if none exists. 
 
310
        TODO: perhaps return a NullSection that thunks through to the 
 
311
              global config.
802
312
        """
803
 
        conf = cls(location)
804
 
        conf._create_from_string(str_or_unicode, save)
805
 
        return conf
806
 
 
807
 
    def _get_matching_sections(self):
808
 
        """Return an ordered list of section names matching this location."""
809
313
        sections = self._get_parser()
810
314
        location_names = self.location.split('/')
811
315
        if self.location.endswith('/'):
812
316
            del location_names[-1]
813
317
        matches=[]
814
318
        for section in sections:
815
 
            # location is a local path if possible, so we need
816
 
            # to convert 'file://' urls to local paths if necessary.
817
 
            # This also avoids having file:///path be a more exact
818
 
            # match than '/path'.
819
 
            if section.startswith('file://'):
820
 
                section_path = urlutils.local_path_from_url(section)
821
 
            else:
822
 
                section_path = section
823
 
            section_names = section_path.split('/')
 
319
            section_names = section.split('/')
824
320
            if section.endswith('/'):
825
321
                del section_names[-1]
826
322
            names = zip(location_names, section_names)
827
323
            matched = True
828
324
            for name in names:
829
 
                if not fnmatch.fnmatch(name[0], name[1]):
 
325
                if not fnmatch(name[0], name[1]):
830
326
                    matched = False
831
327
                    break
832
328
            if not matched:
835
331
            # if section is longer, no match.
836
332
            if len(section_names) > len(location_names):
837
333
                continue
838
 
            matches.append((len(section_names), section,
839
 
                            '/'.join(location_names[len(section_names):])))
840
 
        # put the longest (aka more specific) locations first
 
334
            # if path is longer, and recurse is not true, no match
 
335
            if len(section_names) < len(location_names):
 
336
                try:
 
337
                    if not self._get_parser()[section].as_bool('recurse'):
 
338
                        continue
 
339
                except KeyError:
 
340
                    pass
 
341
            matches.append((len(section_names), section))
 
342
        if not len(matches):
 
343
            return None
841
344
        matches.sort(reverse=True)
842
 
        sections = []
843
 
        for (length, section, extra_path) in matches:
844
 
            sections.append((section, extra_path))
845
 
            # should we stop looking for parent configs here?
846
 
            try:
847
 
                if self._get_parser()[section].as_bool('ignore_parents'):
848
 
                    break
849
 
            except KeyError:
850
 
                pass
851
 
        return sections
852
 
 
853
 
    def _get_sections(self, name=None):
854
 
        """See IniBasedConfig._get_sections()."""
855
 
        # We ignore the name here as the only sections handled are named with
856
 
        # the location path and we don't expose embedded sections either.
857
 
        parser = self._get_parser()
858
 
        for name, extra_path in self._get_matching_sections():
859
 
            yield (name, parser[name], self.config_id())
860
 
 
861
 
    def _get_option_policy(self, section, option_name):
862
 
        """Return the policy for the given (section, option_name) pair."""
863
 
        # check for the old 'recurse=False' flag
864
 
        try:
865
 
            recurse = self._get_parser()[section].as_bool('recurse')
866
 
        except KeyError:
867
 
            recurse = True
868
 
        if not recurse:
869
 
            return POLICY_NORECURSE
870
 
 
871
 
        policy_key = option_name + ':policy'
872
 
        try:
873
 
            policy_name = self._get_parser()[section][policy_key]
874
 
        except KeyError:
875
 
            policy_name = None
876
 
 
877
 
        return _policy_value[policy_name]
878
 
 
879
 
    def _set_option_policy(self, section, option_name, option_policy):
880
 
        """Set the policy for the given option name in the given section."""
881
 
        # The old recurse=False option affects all options in the
882
 
        # section.  To handle multiple policies in the section, we
883
 
        # need to convert it to a policy_norecurse key.
884
 
        try:
885
 
            recurse = self._get_parser()[section].as_bool('recurse')
886
 
        except KeyError:
887
 
            pass
888
 
        else:
889
 
            symbol_versioning.warn(
890
 
                'The recurse option is deprecated as of 0.14.  '
891
 
                'The section "%s" has been converted to use policies.'
892
 
                % section,
893
 
                DeprecationWarning)
894
 
            del self._get_parser()[section]['recurse']
895
 
            if not recurse:
896
 
                for key in self._get_parser()[section].keys():
897
 
                    if not key.endswith(':policy'):
898
 
                        self._get_parser()[section][key +
899
 
                                                    ':policy'] = 'norecurse'
900
 
 
901
 
        policy_key = option_name + ':policy'
902
 
        policy_name = _policy_name[option_policy]
903
 
        if policy_name is not None:
904
 
            self._get_parser()[section][policy_key] = policy_name
905
 
        else:
906
 
            if policy_key in self._get_parser()[section]:
907
 
                del self._get_parser()[section][policy_key]
908
 
 
909
 
    @needs_write_lock
910
 
    def set_user_option(self, option, value, store=STORE_LOCATION):
 
345
        return matches[0][1]
 
346
 
 
347
    def _gpg_signing_command(self):
 
348
        """See Config.gpg_signing_command."""
 
349
        command = super(LocationConfig, self)._gpg_signing_command()
 
350
        if command is not None:
 
351
            return command
 
352
        return self._get_global_config()._gpg_signing_command()
 
353
 
 
354
    def _log_format(self):
 
355
        """See Config.log_format."""
 
356
        command = super(LocationConfig, self)._log_format()
 
357
        if command is not None:
 
358
            return command
 
359
        return self._get_global_config()._log_format()
 
360
 
 
361
    def _get_user_id(self):
 
362
        user_id = super(LocationConfig, self)._get_user_id()
 
363
        if user_id is not None:
 
364
            return user_id
 
365
        return self._get_global_config()._get_user_id()
 
366
 
 
367
    def _get_user_option(self, option_name):
 
368
        """See Config._get_user_option."""
 
369
        option_value = super(LocationConfig, 
 
370
                             self)._get_user_option(option_name)
 
371
        if option_value is not None:
 
372
            return option_value
 
373
        return self._get_global_config()._get_user_option(option_name)
 
374
 
 
375
    def _get_signature_checking(self):
 
376
        """See Config._get_signature_checking."""
 
377
        check = super(LocationConfig, self)._get_signature_checking()
 
378
        if check is not None:
 
379
            return check
 
380
        return self._get_global_config()._get_signature_checking()
 
381
 
 
382
    def _post_commit(self):
 
383
        """See Config.post_commit."""
 
384
        hook = self._get_user_option('post_commit')
 
385
        if hook is not None:
 
386
            return hook
 
387
        return self._get_global_config()._post_commit()
 
388
 
 
389
    def set_user_option(self, option, value):
911
390
        """Save option and its value in the configuration."""
912
 
        if store not in [STORE_LOCATION,
913
 
                         STORE_LOCATION_NORECURSE,
914
 
                         STORE_LOCATION_APPENDPATH]:
915
 
            raise ValueError('bad storage policy %r for %r' %
916
 
                (store, option))
917
 
        self.reload()
 
391
        # FIXME: RBC 20051029 This should refresh the parser and also take a
 
392
        # file lock on branches.conf.
 
393
        conf_dir = os.path.dirname(self._get_filename())
 
394
        ensure_config_dir_exists(conf_dir)
918
395
        location = self.location
919
396
        if location.endswith('/'):
920
397
            location = location[:-1]
921
 
        parser = self._get_parser()
922
 
        if not location in parser and not location + '/' in parser:
923
 
            parser[location] = {}
924
 
        elif location + '/' in parser:
 
398
        if (not location in self._get_parser() and
 
399
            not location + '/' in self._get_parser()):
 
400
            self._get_parser()[location]={}
 
401
        elif location + '/' in self._get_parser():
925
402
            location = location + '/'
926
 
        parser[location][option]=value
927
 
        # the allowed values of store match the config policies
928
 
        self._set_option_policy(location, option, store)
929
 
        self._write_config_file()
 
403
        self._get_parser()[location][option]=value
 
404
        self._get_parser().write(file(self._get_filename(), 'wb'))
930
405
 
931
406
 
932
407
class BranchConfig(Config):
933
408
    """A configuration object giving the policy for a branch."""
934
409
 
935
 
    def __init__(self, branch):
936
 
        super(BranchConfig, self).__init__()
937
 
        self._location_config = None
938
 
        self._branch_data_config = None
939
 
        self._global_config = None
940
 
        self.branch = branch
941
 
        self.option_sources = (self._get_location_config,
942
 
                               self._get_branch_data_config,
943
 
                               self._get_global_config)
944
 
 
945
 
    def config_id(self):
946
 
        return 'branch'
947
 
 
948
 
    def _get_branch_data_config(self):
949
 
        if self._branch_data_config is None:
950
 
            self._branch_data_config = TreeConfig(self.branch)
951
 
            self._branch_data_config.config_id = self.config_id
952
 
        return self._branch_data_config
953
 
 
954
410
    def _get_location_config(self):
955
411
        if self._location_config is None:
956
412
            self._location_config = LocationConfig(self.branch.base)
957
413
        return self._location_config
958
414
 
959
 
    def _get_global_config(self):
960
 
        if self._global_config is None:
961
 
            self._global_config = GlobalConfig()
962
 
        return self._global_config
963
 
 
964
 
    def _get_best_value(self, option_name):
965
 
        """This returns a user option from local, tree or global config.
966
 
 
967
 
        They are tried in that order.  Use get_safe_value if trusted values
968
 
        are necessary.
969
 
        """
970
 
        for source in self.option_sources:
971
 
            value = getattr(source(), option_name)()
972
 
            if value is not None:
973
 
                return value
974
 
        return None
975
 
 
976
 
    def _get_safe_value(self, option_name):
977
 
        """This variant of get_best_value never returns untrusted values.
978
 
 
979
 
        It does not return values from the branch data, because the branch may
980
 
        not be controlled by the user.
981
 
 
982
 
        We may wish to allow locations.conf to control whether branches are
983
 
        trusted in the future.
984
 
        """
985
 
        for source in (self._get_location_config, self._get_global_config):
986
 
            value = getattr(source(), option_name)()
987
 
            if value is not None:
988
 
                return value
989
 
        return None
990
 
 
991
415
    def _get_user_id(self):
992
416
        """Return the full user id for the branch.
993
 
 
994
 
        e.g. "John Hacker <jhacker@example.com>"
 
417
    
 
418
        e.g. "John Hacker <jhacker@foo.org>"
995
419
        This is looked up in the email controlfile for the branch.
996
420
        """
997
421
        try:
998
 
            return (self.branch._transport.get_bytes("email")
999
 
                    .decode(osutils.get_user_encoding())
 
422
            return (self.branch.control_files.get_utf8("email") 
 
423
                    .read()
 
424
                    .decode(bzrlib.user_encoding)
1000
425
                    .rstrip("\r\n"))
1001
426
        except errors.NoSuchFile, e:
1002
427
            pass
1003
 
 
1004
 
        return self._get_best_value('_get_user_id')
1005
 
 
1006
 
    def _get_change_editor(self):
1007
 
        return self._get_best_value('_get_change_editor')
 
428
        
 
429
        return self._get_location_config()._get_user_id()
1008
430
 
1009
431
    def _get_signature_checking(self):
1010
432
        """See Config._get_signature_checking."""
1011
 
        return self._get_best_value('_get_signature_checking')
1012
 
 
1013
 
    def _get_signing_policy(self):
1014
 
        """See Config._get_signing_policy."""
1015
 
        return self._get_best_value('_get_signing_policy')
 
433
        return self._get_location_config()._get_signature_checking()
1016
434
 
1017
435
    def _get_user_option(self, option_name):
1018
436
        """See Config._get_user_option."""
1019
 
        for source in self.option_sources:
1020
 
            value = source()._get_user_option(option_name)
1021
 
            if value is not None:
1022
 
                return value
1023
 
        return None
1024
 
 
1025
 
    def _get_sections(self, name=None):
1026
 
        """See IniBasedConfig.get_sections()."""
1027
 
        for source in self.option_sources:
1028
 
            for section in source()._get_sections(name):
1029
 
                yield section
1030
 
 
1031
 
    def _get_options(self, sections=None):
1032
 
        opts = []
1033
 
        # First the locations options
1034
 
        for option in self._get_location_config()._get_options():
1035
 
            yield option
1036
 
        # Then the branch options
1037
 
        branch_config = self._get_branch_data_config()
1038
 
        if sections is None:
1039
 
            sections = [('DEFAULT', branch_config._get_parser())]
1040
 
        # FIXME: We shouldn't have to duplicate the code in IniBasedConfig but
1041
 
        # Config itself has no notion of sections :( -- vila 20101001
1042
 
        config_id = self.config_id()
1043
 
        for (section_name, section) in sections:
1044
 
            for (name, value) in section.iteritems():
1045
 
                yield (name, value, section_name, config_id)
1046
 
        # Then the global options
1047
 
        for option in self._get_global_config()._get_options():
1048
 
            yield option
1049
 
 
1050
 
    def set_user_option(self, name, value, store=STORE_BRANCH,
1051
 
        warn_masked=False):
1052
 
        if store == STORE_BRANCH:
1053
 
            self._get_branch_data_config().set_option(value, name)
1054
 
        elif store == STORE_GLOBAL:
1055
 
            self._get_global_config().set_user_option(name, value)
1056
 
        else:
1057
 
            self._get_location_config().set_user_option(name, value, store)
1058
 
        if not warn_masked:
1059
 
            return
1060
 
        if store in (STORE_GLOBAL, STORE_BRANCH):
1061
 
            mask_value = self._get_location_config().get_user_option(name)
1062
 
            if mask_value is not None:
1063
 
                trace.warning('Value "%s" is masked by "%s" from'
1064
 
                              ' locations.conf', value, mask_value)
1065
 
            else:
1066
 
                if store == STORE_GLOBAL:
1067
 
                    branch_config = self._get_branch_data_config()
1068
 
                    mask_value = branch_config.get_user_option(name)
1069
 
                    if mask_value is not None:
1070
 
                        trace.warning('Value "%s" is masked by "%s" from'
1071
 
                                      ' branch.conf', value, mask_value)
1072
 
 
1073
 
    def remove_user_option(self, option_name, section_name=None):
1074
 
        self._get_branch_data_config().remove_option(option_name, section_name)
 
437
        return self._get_location_config()._get_user_option(option_name)
1075
438
 
1076
439
    def _gpg_signing_command(self):
1077
440
        """See Config.gpg_signing_command."""
1078
 
        return self._get_safe_value('_gpg_signing_command')
 
441
        return self._get_location_config()._gpg_signing_command()
 
442
        
 
443
    def __init__(self, branch):
 
444
        super(BranchConfig, self).__init__()
 
445
        self._location_config = None
 
446
        self.branch = branch
1079
447
 
1080
448
    def _post_commit(self):
1081
449
        """See Config.post_commit."""
1082
 
        return self._get_safe_value('_post_commit')
1083
 
 
1084
 
    def _get_nickname(self):
1085
 
        value = self._get_explicit_nickname()
1086
 
        if value is not None:
1087
 
            return value
1088
 
        return urlutils.unescape(self.branch.base.split('/')[-2])
1089
 
 
1090
 
    def has_explicit_nickname(self):
1091
 
        """Return true if a nickname has been explicitly assigned."""
1092
 
        return self._get_explicit_nickname() is not None
1093
 
 
1094
 
    def _get_explicit_nickname(self):
1095
 
        return self._get_best_value('_get_nickname')
 
450
        return self._get_location_config()._post_commit()
1096
451
 
1097
452
    def _log_format(self):
1098
453
        """See Config.log_format."""
1099
 
        return self._get_best_value('_log_format')
 
454
        return self._get_location_config()._log_format()
1100
455
 
1101
456
 
1102
457
def ensure_config_dir_exists(path=None):
1111
466
        if sys.platform == 'win32':
1112
467
            parent_dir = os.path.dirname(path)
1113
468
            if not os.path.isdir(parent_dir):
1114
 
                trace.mutter('creating config parent directory: %r', parent_dir)
1115
 
                os.mkdir(parent_dir)
1116
 
        trace.mutter('creating config directory: %r', path)
 
469
                mutter('creating config parent directory: %r', parent_dir)
 
470
            os.mkdir(parent_dir)
 
471
        mutter('creating config directory: %r', path)
1117
472
        os.mkdir(path)
1118
 
        osutils.copy_ownership_from_path(path)
1119
473
 
1120
474
 
1121
475
def config_dir():
1122
476
    """Return per-user configuration directory.
1123
477
 
1124
478
    By default this is ~/.bazaar/
1125
 
 
 
479
    
1126
480
    TODO: Global option --config-dir to override this.
1127
481
    """
1128
482
    base = os.environ.get('BZR_HOME', None)
1129
483
    if sys.platform == 'win32':
1130
484
        if base is None:
1131
 
            base = win32utils.get_appdata_location_unicode()
 
485
            base = os.environ.get('APPDATA', None)
1132
486
        if base is None:
1133
487
            base = os.environ.get('HOME', None)
1134
488
        if base is None:
1135
 
            raise errors.BzrError('You must have one of BZR_HOME, APPDATA,'
1136
 
                                  ' or HOME set')
1137
 
        return osutils.pathjoin(base, 'bazaar', '2.0')
 
489
            raise errors.BzrError('You must have one of BZR_HOME, APPDATA, or HOME set')
 
490
        return pathjoin(base, 'bazaar', '2.0')
1138
491
    else:
 
492
        # cygwin, linux, and darwin all have a $HOME directory
1139
493
        if base is None:
1140
494
            base = os.path.expanduser("~")
1141
 
        return osutils.pathjoin(base, ".bazaar")
 
495
        return pathjoin(base, ".bazaar")
1142
496
 
1143
497
 
1144
498
def config_filename():
1145
499
    """Return per-user configuration ini file filename."""
1146
 
    return osutils.pathjoin(config_dir(), 'bazaar.conf')
1147
 
 
1148
 
 
1149
 
def locations_config_filename():
 
500
    return pathjoin(config_dir(), 'bazaar.conf')
 
501
 
 
502
 
 
503
def branches_config_filename():
1150
504
    """Return per-user configuration ini file filename."""
1151
 
    return osutils.pathjoin(config_dir(), 'locations.conf')
1152
 
 
1153
 
 
1154
 
def authentication_config_filename():
1155
 
    """Return per-user authentication ini file filename."""
1156
 
    return osutils.pathjoin(config_dir(), 'authentication.conf')
1157
 
 
1158
 
 
1159
 
def user_ignore_config_filename():
1160
 
    """Return the user default ignore filename"""
1161
 
    return osutils.pathjoin(config_dir(), 'ignore')
1162
 
 
1163
 
 
1164
 
def crash_dir():
1165
 
    """Return the directory name to store crash files.
1166
 
 
1167
 
    This doesn't implicitly create it.
1168
 
 
1169
 
    On Windows it's in the config directory; elsewhere it's /var/crash
1170
 
    which may be monitored by apport.  It can be overridden by
1171
 
    $APPORT_CRASH_DIR.
 
505
    return pathjoin(config_dir(), 'branches.conf')
 
506
 
 
507
 
 
508
def _auto_user_id():
 
509
    """Calculate automatic user identification.
 
510
 
 
511
    Returns (realname, email).
 
512
 
 
513
    Only used when none is set in the environment or the id file.
 
514
 
 
515
    This previously used the FQDN as the default domain, but that can
 
516
    be very slow on machines where DNS is broken.  So now we simply
 
517
    use the hostname.
1172
518
    """
1173
 
    if sys.platform == 'win32':
1174
 
        return osutils.pathjoin(config_dir(), 'Crash')
1175
 
    else:
1176
 
        # XXX: hardcoded in apport_python_hook.py; therefore here too -- mbp
1177
 
        # 2010-01-31
1178
 
        return os.environ.get('APPORT_CRASH_DIR', '/var/crash')
1179
 
 
1180
 
 
1181
 
def xdg_cache_dir():
1182
 
    # See http://standards.freedesktop.org/basedir-spec/latest/ar01s03.html
1183
 
    # Possibly this should be different on Windows?
1184
 
    e = os.environ.get('XDG_CACHE_DIR', None)
1185
 
    if e:
1186
 
        return e
1187
 
    else:
1188
 
        return os.path.expanduser('~/.cache')
1189
 
 
1190
 
 
1191
 
def parse_username(username):
1192
 
    """Parse e-mail username and return a (name, address) tuple."""
1193
 
    match = re.match(r'(.*?)\s*<?([\w+.-]+@[\w+.-]+)>?', username)
1194
 
    if match is None:
1195
 
        return (username, '')
1196
 
    else:
1197
 
        return (match.group(1), match.group(2))
 
519
    import socket
 
520
 
 
521
    # XXX: Any good way to get real user name on win32?
 
522
 
 
523
    try:
 
524
        import pwd
 
525
        uid = os.getuid()
 
526
        w = pwd.getpwuid(uid)
 
527
 
 
528
        try:
 
529
            gecos = w.pw_gecos.decode(bzrlib.user_encoding)
 
530
            username = w.pw_name.decode(bzrlib.user_encoding)
 
531
        except UnicodeDecodeError:
 
532
            # We're using pwd, therefore we're on Unix, so /etc/passwd is ok.
 
533
            raise errors.BzrError("Can't decode username in " \
 
534
                    "/etc/passwd as %s." % bzrlib.user_encoding)
 
535
 
 
536
        comma = gecos.find(',')
 
537
        if comma == -1:
 
538
            realname = gecos
 
539
        else:
 
540
            realname = gecos[:comma]
 
541
        if not realname:
 
542
            realname = username
 
543
 
 
544
    except ImportError:
 
545
        import getpass
 
546
        try:
 
547
            realname = username = getpass.getuser().decode(bzrlib.user_encoding)
 
548
        except UnicodeDecodeError:
 
549
            raise errors.BzrError("Can't decode username as %s." % \
 
550
                    bzrlib.user_encoding)
 
551
 
 
552
    return realname, (username + '@' + socket.gethostname())
1198
553
 
1199
554
 
1200
555
def extract_email_address(e):
1201
556
    """Return just the address part of an email string.
1202
 
 
1203
 
    That is just the user@domain part, nothing else.
 
557
    
 
558
    That is just the user@domain part, nothing else. 
1204
559
    This part is required to contain only ascii characters.
1205
560
    If it can't be extracted, raises an error.
1206
 
 
 
561
    
1207
562
    >>> extract_email_address('Jane Tester <jane@test.com>')
1208
563
    "jane@test.com"
1209
564
    """
1210
 
    name, email = parse_username(e)
1211
 
    if not email:
1212
 
        raise errors.NoEmailInUsername(e)
1213
 
    return email
1214
 
 
1215
 
 
1216
 
class TreeConfig(IniBasedConfig):
 
565
    m = re.search(r'[\w+.-]+@[\w+.-]+', e)
 
566
    if not m:
 
567
        raise errors.BzrError("%r doesn't seem to contain "
 
568
                              "a reasonable email address" % e)
 
569
    return m.group(0)
 
570
 
 
571
 
 
572
class TreeConfig(object):
1217
573
    """Branch configuration data associated with its contents, not location"""
1218
 
 
1219
 
    # XXX: Really needs a better name, as this is not part of the tree! -- mbp 20080507
1220
 
 
1221
574
    def __init__(self, branch):
1222
 
        self._config = branch._get_config()
1223
575
        self.branch = branch
1224
576
 
1225
 
    def _get_parser(self, file=None):
1226
 
        if file is not None:
1227
 
            return IniBasedConfig._get_parser(file)
1228
 
        return self._config._get_configobj()
 
577
    def _get_config(self):
 
578
        try:
 
579
            obj = ConfigObj(self.branch.control_files.get('branch.conf'), 
 
580
                            encoding='utf-8')
 
581
        except errors.NoSuchFile:
 
582
            obj = ConfigObj(encoding='utf=8')
 
583
        return obj
1229
584
 
1230
585
    def get_option(self, name, section=None, default=None):
1231
586
        self.branch.lock_read()
1232
587
        try:
1233
 
            return self._config.get_option(name, section, default)
 
588
            obj = self._get_config()
 
589
            try:
 
590
                if section is not None:
 
591
                    obj[section]
 
592
                result = obj[name]
 
593
            except KeyError:
 
594
                result = default
1234
595
        finally:
1235
596
            self.branch.unlock()
 
597
        return result
1236
598
 
1237
599
    def set_option(self, value, name, section=None):
1238
600
        """Set a per-branch configuration option"""
1239
 
        # FIXME: We shouldn't need to lock explicitly here but rather rely on
1240
 
        # higher levels providing the right lock -- vila 20101004
1241
 
        self.branch.lock_write()
1242
 
        try:
1243
 
            self._config.set_option(value, name, section)
1244
 
        finally:
1245
 
            self.branch.unlock()
1246
 
 
1247
 
    def remove_option(self, option_name, section_name=None):
1248
 
        # FIXME: We shouldn't need to lock explicitly here but rather rely on
1249
 
        # higher levels providing the right lock -- vila 20101004
1250
 
        self.branch.lock_write()
1251
 
        try:
1252
 
            self._config.remove_option(option_name, section_name)
1253
 
        finally:
1254
 
            self.branch.unlock()
1255
 
 
1256
 
 
1257
 
class AuthenticationConfig(object):
1258
 
    """The authentication configuration file based on a ini file.
1259
 
 
1260
 
    Implements the authentication.conf file described in
1261
 
    doc/developers/authentication-ring.txt.
1262
 
    """
1263
 
 
1264
 
    def __init__(self, _file=None):
1265
 
        self._config = None # The ConfigObj
1266
 
        if _file is None:
1267
 
            self._filename = authentication_config_filename()
1268
 
            self._input = self._filename = authentication_config_filename()
1269
 
        else:
1270
 
            # Tests can provide a string as _file
1271
 
            self._filename = None
1272
 
            self._input = _file
1273
 
 
1274
 
    def _get_config(self):
1275
 
        if self._config is not None:
1276
 
            return self._config
1277
 
        try:
1278
 
            # FIXME: Should we validate something here ? Includes: empty
1279
 
            # sections are useless, at least one of
1280
 
            # user/password/password_encoding should be defined, etc.
1281
 
 
1282
 
            # Note: the encoding below declares that the file itself is utf-8
1283
 
            # encoded, but the values in the ConfigObj are always Unicode.
1284
 
            self._config = ConfigObj(self._input, encoding='utf-8')
1285
 
        except configobj.ConfigObjError, e:
1286
 
            raise errors.ParseConfigError(e.errors, e.config.filename)
1287
 
        return self._config
1288
 
 
1289
 
    def _save(self):
1290
 
        """Save the config file, only tests should use it for now."""
1291
 
        conf_dir = os.path.dirname(self._filename)
1292
 
        ensure_config_dir_exists(conf_dir)
1293
 
        f = file(self._filename, 'wb')
1294
 
        try:
1295
 
            self._get_config().write(f)
1296
 
        finally:
1297
 
            f.close()
1298
 
 
1299
 
    def _set_option(self, section_name, option_name, value):
1300
 
        """Set an authentication configuration option"""
1301
 
        conf = self._get_config()
1302
 
        section = conf.get(section_name)
1303
 
        if section is None:
1304
 
            conf[section] = {}
1305
 
            section = conf[section]
1306
 
        section[option_name] = value
1307
 
        self._save()
1308
 
 
1309
 
    def get_credentials(self, scheme, host, port=None, user=None, path=None, 
1310
 
                        realm=None):
1311
 
        """Returns the matching credentials from authentication.conf file.
1312
 
 
1313
 
        :param scheme: protocol
1314
 
 
1315
 
        :param host: the server address
1316
 
 
1317
 
        :param port: the associated port (optional)
1318
 
 
1319
 
        :param user: login (optional)
1320
 
 
1321
 
        :param path: the absolute path on the server (optional)
1322
 
        
1323
 
        :param realm: the http authentication realm (optional)
1324
 
 
1325
 
        :return: A dict containing the matching credentials or None.
1326
 
           This includes:
1327
 
           - name: the section name of the credentials in the
1328
 
             authentication.conf file,
1329
 
           - user: can't be different from the provided user if any,
1330
 
           - scheme: the server protocol,
1331
 
           - host: the server address,
1332
 
           - port: the server port (can be None),
1333
 
           - path: the absolute server path (can be None),
1334
 
           - realm: the http specific authentication realm (can be None),
1335
 
           - password: the decoded password, could be None if the credential
1336
 
             defines only the user
1337
 
           - verify_certificates: https specific, True if the server
1338
 
             certificate should be verified, False otherwise.
1339
 
        """
1340
 
        credentials = None
1341
 
        for auth_def_name, auth_def in self._get_config().items():
1342
 
            if type(auth_def) is not configobj.Section:
1343
 
                raise ValueError("%s defined outside a section" % auth_def_name)
1344
 
 
1345
 
            a_scheme, a_host, a_user, a_path = map(
1346
 
                auth_def.get, ['scheme', 'host', 'user', 'path'])
1347
 
 
1348
 
            try:
1349
 
                a_port = auth_def.as_int('port')
1350
 
            except KeyError:
1351
 
                a_port = None
1352
 
            except ValueError:
1353
 
                raise ValueError("'port' not numeric in %s" % auth_def_name)
1354
 
            try:
1355
 
                a_verify_certificates = auth_def.as_bool('verify_certificates')
1356
 
            except KeyError:
1357
 
                a_verify_certificates = True
1358
 
            except ValueError:
1359
 
                raise ValueError(
1360
 
                    "'verify_certificates' not boolean in %s" % auth_def_name)
1361
 
 
1362
 
            # Attempt matching
1363
 
            if a_scheme is not None and scheme != a_scheme:
1364
 
                continue
1365
 
            if a_host is not None:
1366
 
                if not (host == a_host
1367
 
                        or (a_host.startswith('.') and host.endswith(a_host))):
1368
 
                    continue
1369
 
            if a_port is not None and port != a_port:
1370
 
                continue
1371
 
            if (a_path is not None and path is not None
1372
 
                and not path.startswith(a_path)):
1373
 
                continue
1374
 
            if (a_user is not None and user is not None
1375
 
                and a_user != user):
1376
 
                # Never contradict the caller about the user to be used
1377
 
                continue
1378
 
            if a_user is None:
1379
 
                # Can't find a user
1380
 
                continue
1381
 
            # Prepare a credentials dictionary with additional keys
1382
 
            # for the credential providers
1383
 
            credentials = dict(name=auth_def_name,
1384
 
                               user=a_user,
1385
 
                               scheme=a_scheme,
1386
 
                               host=host,
1387
 
                               port=port,
1388
 
                               path=path,
1389
 
                               realm=realm,
1390
 
                               password=auth_def.get('password', None),
1391
 
                               verify_certificates=a_verify_certificates)
1392
 
            # Decode the password in the credentials (or get one)
1393
 
            self.decode_password(credentials,
1394
 
                                 auth_def.get('password_encoding', None))
1395
 
            if 'auth' in debug.debug_flags:
1396
 
                trace.mutter("Using authentication section: %r", auth_def_name)
1397
 
            break
1398
 
 
1399
 
        if credentials is None:
1400
 
            # No credentials were found in authentication.conf, try the fallback
1401
 
            # credentials stores.
1402
 
            credentials = credential_store_registry.get_fallback_credentials(
1403
 
                scheme, host, port, user, path, realm)
1404
 
 
1405
 
        return credentials
1406
 
 
1407
 
    def set_credentials(self, name, host, user, scheme=None, password=None,
1408
 
                        port=None, path=None, verify_certificates=None,
1409
 
                        realm=None):
1410
 
        """Set authentication credentials for a host.
1411
 
 
1412
 
        Any existing credentials with matching scheme, host, port and path
1413
 
        will be deleted, regardless of name.
1414
 
 
1415
 
        :param name: An arbitrary name to describe this set of credentials.
1416
 
        :param host: Name of the host that accepts these credentials.
1417
 
        :param user: The username portion of these credentials.
1418
 
        :param scheme: The URL scheme (e.g. ssh, http) the credentials apply
1419
 
            to.
1420
 
        :param password: Password portion of these credentials.
1421
 
        :param port: The IP port on the host that these credentials apply to.
1422
 
        :param path: A filesystem path on the host that these credentials
1423
 
            apply to.
1424
 
        :param verify_certificates: On https, verify server certificates if
1425
 
            True.
1426
 
        :param realm: The http authentication realm (optional).
1427
 
        """
1428
 
        values = {'host': host, 'user': user}
1429
 
        if password is not None:
1430
 
            values['password'] = password
1431
 
        if scheme is not None:
1432
 
            values['scheme'] = scheme
1433
 
        if port is not None:
1434
 
            values['port'] = '%d' % port
1435
 
        if path is not None:
1436
 
            values['path'] = path
1437
 
        if verify_certificates is not None:
1438
 
            values['verify_certificates'] = str(verify_certificates)
1439
 
        if realm is not None:
1440
 
            values['realm'] = realm
1441
 
        config = self._get_config()
1442
 
        for_deletion = []
1443
 
        for section, existing_values in config.items():
1444
 
            for key in ('scheme', 'host', 'port', 'path', 'realm'):
1445
 
                if existing_values.get(key) != values.get(key):
1446
 
                    break
1447
 
            else:
1448
 
                del config[section]
1449
 
        config.update({name: values})
1450
 
        self._save()
1451
 
 
1452
 
    def get_user(self, scheme, host, port=None, realm=None, path=None,
1453
 
                 prompt=None, ask=False, default=None):
1454
 
        """Get a user from authentication file.
1455
 
 
1456
 
        :param scheme: protocol
1457
 
 
1458
 
        :param host: the server address
1459
 
 
1460
 
        :param port: the associated port (optional)
1461
 
 
1462
 
        :param realm: the realm sent by the server (optional)
1463
 
 
1464
 
        :param path: the absolute path on the server (optional)
1465
 
 
1466
 
        :param ask: Ask the user if there is no explicitly configured username 
1467
 
                    (optional)
1468
 
 
1469
 
        :param default: The username returned if none is defined (optional).
1470
 
 
1471
 
        :return: The found user.
1472
 
        """
1473
 
        credentials = self.get_credentials(scheme, host, port, user=None,
1474
 
                                           path=path, realm=realm)
1475
 
        if credentials is not None:
1476
 
            user = credentials['user']
1477
 
        else:
1478
 
            user = None
1479
 
        if user is None:
1480
 
            if ask:
1481
 
                if prompt is None:
1482
 
                    # Create a default prompt suitable for most cases
1483
 
                    prompt = scheme.upper() + ' %(host)s username'
1484
 
                # Special handling for optional fields in the prompt
1485
 
                if port is not None:
1486
 
                    prompt_host = '%s:%d' % (host, port)
1487
 
                else:
1488
 
                    prompt_host = host
1489
 
                user = ui.ui_factory.get_username(prompt, host=prompt_host)
1490
 
            else:
1491
 
                user = default
1492
 
        return user
1493
 
 
1494
 
    def get_password(self, scheme, host, user, port=None,
1495
 
                     realm=None, path=None, prompt=None):
1496
 
        """Get a password from authentication file or prompt the user for one.
1497
 
 
1498
 
        :param scheme: protocol
1499
 
 
1500
 
        :param host: the server address
1501
 
 
1502
 
        :param port: the associated port (optional)
1503
 
 
1504
 
        :param user: login
1505
 
 
1506
 
        :param realm: the realm sent by the server (optional)
1507
 
 
1508
 
        :param path: the absolute path on the server (optional)
1509
 
 
1510
 
        :return: The found password or the one entered by the user.
1511
 
        """
1512
 
        credentials = self.get_credentials(scheme, host, port, user, path,
1513
 
                                           realm)
1514
 
        if credentials is not None:
1515
 
            password = credentials['password']
1516
 
            if password is not None and scheme is 'ssh':
1517
 
                trace.warning('password ignored in section [%s],'
1518
 
                              ' use an ssh agent instead'
1519
 
                              % credentials['name'])
1520
 
                password = None
1521
 
        else:
1522
 
            password = None
1523
 
        # Prompt user only if we could't find a password
1524
 
        if password is None:
1525
 
            if prompt is None:
1526
 
                # Create a default prompt suitable for most cases
1527
 
                prompt = '%s' % scheme.upper() + ' %(user)s@%(host)s password'
1528
 
            # Special handling for optional fields in the prompt
1529
 
            if port is not None:
1530
 
                prompt_host = '%s:%d' % (host, port)
1531
 
            else:
1532
 
                prompt_host = host
1533
 
            password = ui.ui_factory.get_password(prompt,
1534
 
                                                  host=prompt_host, user=user)
1535
 
        return password
1536
 
 
1537
 
    def decode_password(self, credentials, encoding):
1538
 
        try:
1539
 
            cs = credential_store_registry.get_credential_store(encoding)
1540
 
        except KeyError:
1541
 
            raise ValueError('%r is not a known password_encoding' % encoding)
1542
 
        credentials['password'] = cs.decode_password(credentials)
1543
 
        return credentials
1544
 
 
1545
 
 
1546
 
class CredentialStoreRegistry(registry.Registry):
1547
 
    """A class that registers credential stores.
1548
 
 
1549
 
    A credential store provides access to credentials via the password_encoding
1550
 
    field in authentication.conf sections.
1551
 
 
1552
 
    Except for stores provided by bzr itself, most stores are expected to be
1553
 
    provided by plugins that will therefore use
1554
 
    register_lazy(password_encoding, module_name, member_name, help=help,
1555
 
    fallback=fallback) to install themselves.
1556
 
 
1557
 
    A fallback credential store is one that is queried if no credentials can be
1558
 
    found via authentication.conf.
1559
 
    """
1560
 
 
1561
 
    def get_credential_store(self, encoding=None):
1562
 
        cs = self.get(encoding)
1563
 
        if callable(cs):
1564
 
            cs = cs()
1565
 
        return cs
1566
 
 
1567
 
    def is_fallback(self, name):
1568
 
        """Check if the named credentials store should be used as fallback."""
1569
 
        return self.get_info(name)
1570
 
 
1571
 
    def get_fallback_credentials(self, scheme, host, port=None, user=None,
1572
 
                                 path=None, realm=None):
1573
 
        """Request credentials from all fallback credentials stores.
1574
 
 
1575
 
        The first credentials store that can provide credentials wins.
1576
 
        """
1577
 
        credentials = None
1578
 
        for name in self.keys():
1579
 
            if not self.is_fallback(name):
1580
 
                continue
1581
 
            cs = self.get_credential_store(name)
1582
 
            credentials = cs.get_credentials(scheme, host, port, user,
1583
 
                                             path, realm)
1584
 
            if credentials is not None:
1585
 
                # We found some credentials
1586
 
                break
1587
 
        return credentials
1588
 
 
1589
 
    def register(self, key, obj, help=None, override_existing=False,
1590
 
                 fallback=False):
1591
 
        """Register a new object to a name.
1592
 
 
1593
 
        :param key: This is the key to use to request the object later.
1594
 
        :param obj: The object to register.
1595
 
        :param help: Help text for this entry. This may be a string or
1596
 
                a callable. If it is a callable, it should take two
1597
 
                parameters (registry, key): this registry and the key that
1598
 
                the help was registered under.
1599
 
        :param override_existing: Raise KeyErorr if False and something has
1600
 
                already been registered for that key. If True, ignore if there
1601
 
                is an existing key (always register the new value).
1602
 
        :param fallback: Whether this credential store should be 
1603
 
                used as fallback.
1604
 
        """
1605
 
        return super(CredentialStoreRegistry,
1606
 
                     self).register(key, obj, help, info=fallback,
1607
 
                                    override_existing=override_existing)
1608
 
 
1609
 
    def register_lazy(self, key, module_name, member_name,
1610
 
                      help=None, override_existing=False,
1611
 
                      fallback=False):
1612
 
        """Register a new credential store to be loaded on request.
1613
 
 
1614
 
        :param module_name: The python path to the module. Such as 'os.path'.
1615
 
        :param member_name: The member of the module to return.  If empty or
1616
 
                None, get() will return the module itself.
1617
 
        :param help: Help text for this entry. This may be a string or
1618
 
                a callable.
1619
 
        :param override_existing: If True, replace the existing object
1620
 
                with the new one. If False, if there is already something
1621
 
                registered with the same key, raise a KeyError
1622
 
        :param fallback: Whether this credential store should be 
1623
 
                used as fallback.
1624
 
        """
1625
 
        return super(CredentialStoreRegistry, self).register_lazy(
1626
 
            key, module_name, member_name, help,
1627
 
            info=fallback, override_existing=override_existing)
1628
 
 
1629
 
 
1630
 
credential_store_registry = CredentialStoreRegistry()
1631
 
 
1632
 
 
1633
 
class CredentialStore(object):
1634
 
    """An abstract class to implement storage for credentials"""
1635
 
 
1636
 
    def decode_password(self, credentials):
1637
 
        """Returns a clear text password for the provided credentials."""
1638
 
        raise NotImplementedError(self.decode_password)
1639
 
 
1640
 
    def get_credentials(self, scheme, host, port=None, user=None, path=None,
1641
 
                        realm=None):
1642
 
        """Return the matching credentials from this credential store.
1643
 
 
1644
 
        This method is only called on fallback credential stores.
1645
 
        """
1646
 
        raise NotImplementedError(self.get_credentials)
1647
 
 
1648
 
 
1649
 
 
1650
 
class PlainTextCredentialStore(CredentialStore):
1651
 
    __doc__ = """Plain text credential store for the authentication.conf file"""
1652
 
 
1653
 
    def decode_password(self, credentials):
1654
 
        """See CredentialStore.decode_password."""
1655
 
        return credentials['password']
1656
 
 
1657
 
 
1658
 
credential_store_registry.register('plain', PlainTextCredentialStore,
1659
 
                                   help=PlainTextCredentialStore.__doc__)
1660
 
credential_store_registry.default_key = 'plain'
1661
 
 
1662
 
 
1663
 
class BzrDirConfig(object):
1664
 
 
1665
 
    def __init__(self, bzrdir):
1666
 
        self._bzrdir = bzrdir
1667
 
        self._config = bzrdir._get_config()
1668
 
 
1669
 
    def set_default_stack_on(self, value):
1670
 
        """Set the default stacking location.
1671
 
 
1672
 
        It may be set to a location, or None.
1673
 
 
1674
 
        This policy affects all branches contained by this bzrdir, except for
1675
 
        those under repositories.
1676
 
        """
1677
 
        if self._config is None:
1678
 
            raise errors.BzrError("Cannot set configuration in %s" % self._bzrdir)
1679
 
        if value is None:
1680
 
            self._config.set_option('', 'default_stack_on')
1681
 
        else:
1682
 
            self._config.set_option(value, 'default_stack_on')
1683
 
 
1684
 
    def get_default_stack_on(self):
1685
 
        """Return the default stacking location.
1686
 
 
1687
 
        This will either be a location, or None.
1688
 
 
1689
 
        This policy affects all branches contained by this bzrdir, except for
1690
 
        those under repositories.
1691
 
        """
1692
 
        if self._config is None:
1693
 
            return None
1694
 
        value = self._config.get_option('default_stack_on')
1695
 
        if value == '':
1696
 
            value = None
1697
 
        return value
1698
 
 
1699
 
 
1700
 
class TransportConfig(object):
1701
 
    """A Config that reads/writes a config file on a Transport.
1702
 
 
1703
 
    It is a low-level object that considers config data to be name/value pairs
1704
 
    that may be associated with a section.  Assigning meaning to these values
1705
 
    is done at higher levels like TreeConfig.
1706
 
    """
1707
 
 
1708
 
    def __init__(self, transport, filename):
1709
 
        self._transport = transport
1710
 
        self._filename = filename
1711
 
 
1712
 
    def get_option(self, name, section=None, default=None):
1713
 
        """Return the value associated with a named option.
1714
 
 
1715
 
        :param name: The name of the value
1716
 
        :param section: The section the option is in (if any)
1717
 
        :param default: The value to return if the value is not set
1718
 
        :return: The value or default value
1719
 
        """
1720
 
        configobj = self._get_configobj()
1721
 
        if section is None:
1722
 
            section_obj = configobj
1723
 
        else:
1724
 
            try:
1725
 
                section_obj = configobj[section]
1726
 
            except KeyError:
1727
 
                return default
1728
 
        return section_obj.get(name, default)
1729
 
 
1730
 
    def set_option(self, value, name, section=None):
1731
 
        """Set the value associated with a named option.
1732
 
 
1733
 
        :param value: The value to set
1734
 
        :param name: The name of the value to set
1735
 
        :param section: The section the option is in (if any)
1736
 
        """
1737
 
        configobj = self._get_configobj()
1738
 
        if section is None:
1739
 
            configobj[name] = value
1740
 
        else:
1741
 
            configobj.setdefault(section, {})[name] = value
1742
 
        self._set_configobj(configobj)
1743
 
 
1744
 
    def remove_option(self, option_name, section_name=None):
1745
 
        configobj = self._get_configobj()
1746
 
        if section_name is None:
1747
 
            del configobj[option_name]
1748
 
        else:
1749
 
            del configobj[section_name][option_name]
1750
 
        self._set_configobj(configobj)
1751
 
 
1752
 
    def _get_config_file(self):
1753
 
        try:
1754
 
            return StringIO(self._transport.get_bytes(self._filename))
1755
 
        except errors.NoSuchFile:
1756
 
            return StringIO()
1757
 
 
1758
 
    def _get_configobj(self):
1759
 
        f = self._get_config_file()
1760
 
        try:
1761
 
            return ConfigObj(f, encoding='utf-8')
1762
 
        finally:
1763
 
            f.close()
1764
 
 
1765
 
    def _set_configobj(self, configobj):
1766
 
        out_file = StringIO()
1767
 
        configobj.write(out_file)
1768
 
        out_file.seek(0)
1769
 
        self._transport.put_file(self._filename, out_file)
1770
 
 
1771
 
 
1772
 
class cmd_config(commands.Command):
1773
 
    __doc__ = """Display, set or remove a configuration option.
1774
 
 
1775
 
    Display the MATCHING configuration options mentioning their scope (the
1776
 
    configuration file they are defined in). The active value that bzr will
1777
 
    take into account is the first one displayed.
1778
 
 
1779
 
    Setting a value is achieved by using name=value without spaces. The value
1780
 
    is set in the most relevant scope and can be checked by displaying the
1781
 
    option again.
1782
 
    """
1783
 
 
1784
 
    aliases = ['conf']
1785
 
    takes_args = ['matching?']
1786
 
 
1787
 
    takes_options = [
1788
 
        'directory',
1789
 
        # FIXME: This should be a registry option so that plugins can register
1790
 
        # their own config files (or not) -- vila 20101002
1791
 
        commands.Option('scope', help='Reduce the scope to the specified'
1792
 
                        ' configuration file',
1793
 
                        type=unicode),
1794
 
        commands.Option('remove', help='Remove the option from'
1795
 
                        ' the configuration file'),
1796
 
        ]
1797
 
 
1798
 
    @commands.display_command
1799
 
    def run(self, matching=None, directory=None, scope=None, remove=False):
1800
 
        if directory is None:
1801
 
            directory = '.'
1802
 
        directory = urlutils.normalize_url(directory)
1803
 
        if matching is None:
1804
 
            self._show_config('*', directory)
1805
 
        else:
1806
 
            if remove:
1807
 
                self._remove_config_option(matching, directory, scope)
1808
 
            else:
1809
 
                pos = matching.find('=')
1810
 
                if pos == -1:
1811
 
                    self._show_config(matching, directory)
1812
 
                else:
1813
 
                    self._set_config_option(matching[:pos], matching[pos+1:],
1814
 
                                            directory, scope)
1815
 
 
1816
 
    def _get_configs(self, directory, scope=None):
1817
 
        """Iterate the configurations specified by ``directory`` and ``scope``.
1818
 
 
1819
 
        :param directory: Where the configurations are derived from.
1820
 
 
1821
 
        :param scope: A specific config to start from.
1822
 
        """
1823
 
        if scope is not None:
1824
 
            if scope == 'bazaar':
1825
 
                yield GlobalConfig()
1826
 
            elif scope == 'locations':
1827
 
                yield LocationConfig(directory)
1828
 
            elif scope == 'branch':
1829
 
                (_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
1830
 
                    directory)
1831
 
                yield br.get_config()
1832
 
        else:
1833
 
            try:
1834
 
                (_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
1835
 
                    directory)
1836
 
                yield br.get_config()
1837
 
            except errors.NotBranchError:
1838
 
                yield LocationConfig(directory)
1839
 
                yield GlobalConfig()
1840
 
 
1841
 
    def _show_config(self, matching, directory):
1842
 
        # Turn the glob into a regexp
1843
 
        matching_re = re.compile(fnmatch.translate(matching))
1844
 
        cur_conf_id = None
1845
 
        for c in self._get_configs(directory):
1846
 
            for (name, value, section, conf_id) in c._get_options():
1847
 
                if matching_re.search(name):
1848
 
                    if cur_conf_id != conf_id:
1849
 
                        self.outf.write('%s:\n' % (conf_id,))
1850
 
                        cur_conf_id = conf_id
1851
 
                    self.outf.write('  %s = %s\n' % (name, value))
1852
 
 
1853
 
    def _set_config_option(self, name, value, directory, scope):
1854
 
        for conf in self._get_configs(directory, scope):
1855
 
            conf.set_user_option(name, value)
1856
 
            break
1857
 
        else:
1858
 
            raise errors.NoSuchConfig(scope)
1859
 
 
1860
 
    def _remove_config_option(self, name, directory, scope):
1861
 
        removed = False
1862
 
        for conf in self._get_configs(directory, scope):
1863
 
            for (section_name, section, conf_id) in conf._get_sections():
1864
 
                if scope is not None and conf_id != scope:
1865
 
                    # Not the right configuration file
1866
 
                    continue
1867
 
                if name in section:
1868
 
                    if conf_id != conf.config_id():
1869
 
                        conf = self._get_configs(directory, conf_id).next()
1870
 
                    # We use the first section in the first config where the
1871
 
                    # option is defined to remove it
1872
 
                    conf.remove_user_option(name, section_name)
1873
 
                    removed = True
1874
 
                    break
1875
 
            break
1876
 
        else:
1877
 
            raise errors.NoSuchConfig(scope)
1878
 
        if not removed:
1879
 
            raise errors.NoSuchConfigOption(name)
 
601
        self.branch.lock_write()
 
602
        try:
 
603
            cfg_obj = self._get_config()
 
604
            if section is None:
 
605
                obj = cfg_obj
 
606
            else:
 
607
                try:
 
608
                    obj = cfg_obj[section]
 
609
                except KeyError:
 
610
                    cfg_obj[section] = {}
 
611
                    obj = cfg_obj[section]
 
612
            obj[name] = value
 
613
            out_file = StringIO()
 
614
            cfg_obj.write(out_file)
 
615
            out_file.seek(0)
 
616
            self.branch.control_files.put('branch.conf', out_file)
 
617
        finally:
 
618
            self.branch.unlock()