/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/config.py

  • Committer: Martin Pool
  • Date: 2011-06-28 22:39:41 UTC
  • mto: This revision was merged to the branch mainline in revision 6004.
  • Revision ID: mbp@canonical.com-20110628223941-rnxnukj963t1goft
lazy regexp tests should install it explicitly

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 Canonical Ltd
 
1
# Copyright (C) 2005-2011 Canonical Ltd
2
2
#   Authors: Robert Collins <robert.collins@canonical.com>
3
3
#            and others
4
4
#
63
63
"""
64
64
 
65
65
import os
 
66
import string
66
67
import sys
 
68
import weakref
67
69
 
 
70
from bzrlib import commands
 
71
from bzrlib.decorators import needs_write_lock
68
72
from bzrlib.lazy_import import lazy_import
69
73
lazy_import(globals(), """
70
 
import errno
71
 
from fnmatch import fnmatch
 
74
import fnmatch
72
75
import re
73
76
from cStringIO import StringIO
74
77
 
75
78
import bzrlib
76
79
from bzrlib import (
 
80
    atomicfile,
 
81
    bzrdir,
77
82
    debug,
78
83
    errors,
 
84
    lazy_regex,
 
85
    lockdir,
79
86
    mail_client,
 
87
    mergetools,
80
88
    osutils,
81
 
    registry,
82
89
    symbol_versioning,
83
90
    trace,
 
91
    transport,
84
92
    ui,
85
93
    urlutils,
86
94
    win32utils,
87
95
    )
88
96
from bzrlib.util.configobj import configobj
89
97
""")
 
98
from bzrlib import (
 
99
    registry,
 
100
    )
 
101
from bzrlib.symbol_versioning import (
 
102
    deprecated_in,
 
103
    deprecated_method,
 
104
    )
90
105
 
91
106
 
92
107
CHECK_IF_POSSIBLE=0
122
137
STORE_BRANCH = 3
123
138
STORE_GLOBAL = 4
124
139
 
125
 
_ConfigObj = None
126
 
def ConfigObj(*args, **kwargs):
127
 
    global _ConfigObj
128
 
    if _ConfigObj is None:
129
 
        class ConfigObj(configobj.ConfigObj):
130
 
 
131
 
            def get_bool(self, section, key):
132
 
                return self[section].as_bool(key)
133
 
 
134
 
            def get_value(self, section, name):
135
 
                # Try [] for the old DEFAULT section.
136
 
                if section == "DEFAULT":
137
 
                    try:
138
 
                        return self[name]
139
 
                    except KeyError:
140
 
                        pass
141
 
                return self[section][name]
142
 
        _ConfigObj = ConfigObj
143
 
    return _ConfigObj(*args, **kwargs)
 
140
 
 
141
class ConfigObj(configobj.ConfigObj):
 
142
 
 
143
    def __init__(self, infile=None, **kwargs):
 
144
        # We define our own interpolation mechanism calling it option expansion
 
145
        super(ConfigObj, self).__init__(infile=infile,
 
146
                                        interpolation=False,
 
147
                                        **kwargs)
 
148
 
 
149
 
 
150
    def get_bool(self, section, key):
 
151
        return self[section].as_bool(key)
 
152
 
 
153
    def get_value(self, section, name):
 
154
        # Try [] for the old DEFAULT section.
 
155
        if section == "DEFAULT":
 
156
            try:
 
157
                return self[name]
 
158
            except KeyError:
 
159
                pass
 
160
        return self[section][name]
 
161
 
 
162
 
 
163
# FIXME: Until we can guarantee that each config file is loaded once and and
 
164
# only once for a given bzrlib session, we don't want to re-read the file every
 
165
# time we query for an option so we cache the value (bad ! watch out for tests
 
166
# needing to restore the proper value).This shouldn't be part of 2.4.0 final,
 
167
# yell at mgz^W vila and the RM if this is still present at that time
 
168
# -- vila 20110219
 
169
_expand_default_value = None
 
170
def _get_expand_default_value():
 
171
    global _expand_default_value
 
172
    if _expand_default_value is not None:
 
173
        return _expand_default_value
 
174
    conf = GlobalConfig()
 
175
    # Note that we must not use None for the expand value below or we'll run
 
176
    # into infinite recursion. Using False really would be quite silly ;)
 
177
    expand = conf.get_user_option_as_bool('bzr.config.expand', expand=True)
 
178
    if expand is None:
 
179
        # This is an opt-in feature, you *really* need to clearly say you want
 
180
        # to activate it !
 
181
        expand = False
 
182
    _expand_default_value = expand
 
183
    return expand
144
184
 
145
185
 
146
186
class Config(object):
149
189
    def __init__(self):
150
190
        super(Config, self).__init__()
151
191
 
 
192
    def config_id(self):
 
193
        """Returns a unique ID for the config."""
 
194
        raise NotImplementedError(self.config_id)
 
195
 
 
196
    @deprecated_method(deprecated_in((2, 4, 0)))
152
197
    def get_editor(self):
153
198
        """Get the users pop up editor."""
154
199
        raise NotImplementedError
161
206
        return diff.DiffFromTool.from_string(cmd, old_tree, new_tree,
162
207
                                             sys.stdout)
163
208
 
164
 
 
165
209
    def get_mail_client(self):
166
210
        """Get a mail client to use"""
167
211
        selected_client = self.get_user_option('mail_client')
178
222
    def _get_signing_policy(self):
179
223
        """Template method to override signature creation policy."""
180
224
 
 
225
    option_ref_re = None
 
226
 
 
227
    def expand_options(self, string, env=None):
 
228
        """Expand option references in the string in the configuration context.
 
229
 
 
230
        :param string: The string containing option to expand.
 
231
 
 
232
        :param env: An option dict defining additional configuration options or
 
233
            overriding existing ones.
 
234
 
 
235
        :returns: The expanded string.
 
236
        """
 
237
        return self._expand_options_in_string(string, env)
 
238
 
 
239
    def _expand_options_in_list(self, slist, env=None, _ref_stack=None):
 
240
        """Expand options in  a list of strings in the configuration context.
 
241
 
 
242
        :param slist: A list of strings.
 
243
 
 
244
        :param env: An option dict defining additional configuration options or
 
245
            overriding existing ones.
 
246
 
 
247
        :param _ref_stack: Private list containing the options being
 
248
            expanded to detect loops.
 
249
 
 
250
        :returns: The flatten list of expanded strings.
 
251
        """
 
252
        # expand options in each value separately flattening lists
 
253
        result = []
 
254
        for s in slist:
 
255
            value = self._expand_options_in_string(s, env, _ref_stack)
 
256
            if isinstance(value, list):
 
257
                result.extend(value)
 
258
            else:
 
259
                result.append(value)
 
260
        return result
 
261
 
 
262
    def _expand_options_in_string(self, string, env=None, _ref_stack=None):
 
263
        """Expand options in the string in the configuration context.
 
264
 
 
265
        :param string: The string to be expanded.
 
266
 
 
267
        :param env: An option dict defining additional configuration options or
 
268
            overriding existing ones.
 
269
 
 
270
        :param _ref_stack: Private list containing the options being
 
271
            expanded to detect loops.
 
272
 
 
273
        :returns: The expanded string.
 
274
        """
 
275
        if string is None:
 
276
            # Not much to expand there
 
277
            return None
 
278
        if _ref_stack is None:
 
279
            # What references are currently resolved (to detect loops)
 
280
            _ref_stack = []
 
281
        if self.option_ref_re is None:
 
282
            # We want to match the most embedded reference first (i.e. for
 
283
            # '{{foo}}' we will get '{foo}',
 
284
            # for '{bar{baz}}' we will get '{baz}'
 
285
            self.option_ref_re = re.compile('({[^{}]+})')
 
286
        result = string
 
287
        # We need to iterate until no more refs appear ({{foo}} will need two
 
288
        # iterations for example).
 
289
        while True:
 
290
            raw_chunks = self.option_ref_re.split(result)
 
291
            if len(raw_chunks) == 1:
 
292
                # Shorcut the trivial case: no refs
 
293
                return result
 
294
            chunks = []
 
295
            list_value = False
 
296
            # Split will isolate refs so that every other chunk is a ref
 
297
            chunk_is_ref = False
 
298
            for chunk in raw_chunks:
 
299
                if not chunk_is_ref:
 
300
                    if chunk:
 
301
                        # Keep only non-empty strings (or we get bogus empty
 
302
                        # slots when a list value is involved).
 
303
                        chunks.append(chunk)
 
304
                    chunk_is_ref = True
 
305
                else:
 
306
                    name = chunk[1:-1]
 
307
                    if name in _ref_stack:
 
308
                        raise errors.OptionExpansionLoop(string, _ref_stack)
 
309
                    _ref_stack.append(name)
 
310
                    value = self._expand_option(name, env, _ref_stack)
 
311
                    if value is None:
 
312
                        raise errors.ExpandingUnknownOption(name, string)
 
313
                    if isinstance(value, list):
 
314
                        list_value = True
 
315
                        chunks.extend(value)
 
316
                    else:
 
317
                        chunks.append(value)
 
318
                    _ref_stack.pop()
 
319
                    chunk_is_ref = False
 
320
            if list_value:
 
321
                # Once a list appears as the result of an expansion, all
 
322
                # callers will get a list result. This allows a consistent
 
323
                # behavior even when some options in the expansion chain
 
324
                # defined as strings (no comma in their value) but their
 
325
                # expanded value is a list.
 
326
                return self._expand_options_in_list(chunks, env, _ref_stack)
 
327
            else:
 
328
                result = ''.join(chunks)
 
329
        return result
 
330
 
 
331
    def _expand_option(self, name, env, _ref_stack):
 
332
        if env is not None and name in env:
 
333
            # Special case, values provided in env takes precedence over
 
334
            # anything else
 
335
            value = env[name]
 
336
        else:
 
337
            # FIXME: This is a limited implementation, what we really need is a
 
338
            # way to query the bzr config for the value of an option,
 
339
            # respecting the scope rules (That is, once we implement fallback
 
340
            # configs, getting the option value should restart from the top
 
341
            # config, not the current one) -- vila 20101222
 
342
            value = self.get_user_option(name, expand=False)
 
343
            if isinstance(value, list):
 
344
                value = self._expand_options_in_list(value, env, _ref_stack)
 
345
            else:
 
346
                value = self._expand_options_in_string(value, env, _ref_stack)
 
347
        return value
 
348
 
181
349
    def _get_user_option(self, option_name):
182
350
        """Template method to provide a user option."""
183
351
        return None
184
352
 
185
 
    def get_user_option(self, option_name):
186
 
        """Get a generic option - no special process, no default."""
187
 
        return self._get_user_option(option_name)
188
 
 
189
 
    def get_user_option_as_bool(self, option_name):
 
353
    def get_user_option(self, option_name, expand=None):
 
354
        """Get a generic option - no special process, no default.
 
355
 
 
356
        :param option_name: The queried option.
 
357
 
 
358
        :param expand: Whether options references should be expanded.
 
359
 
 
360
        :returns: The value of the option.
 
361
        """
 
362
        if expand is None:
 
363
            expand = _get_expand_default_value()
 
364
        value = self._get_user_option(option_name)
 
365
        if expand:
 
366
            if isinstance(value, list):
 
367
                value = self._expand_options_in_list(value)
 
368
            elif isinstance(value, dict):
 
369
                trace.warning('Cannot expand "%s":'
 
370
                              ' Dicts do not support option expansion'
 
371
                              % (option_name,))
 
372
            else:
 
373
                value = self._expand_options_in_string(value)
 
374
        return value
 
375
 
 
376
    def get_user_option_as_bool(self, option_name, expand=None):
190
377
        """Get a generic option as a boolean - no special process, no default.
191
378
 
192
379
        :return None if the option doesn't exist or its value can't be
193
380
            interpreted as a boolean. Returns True or False otherwise.
194
381
        """
195
 
        s = self._get_user_option(option_name)
 
382
        s = self.get_user_option(option_name, expand=expand)
196
383
        if s is None:
197
384
            # The option doesn't exist
198
385
            return None
203
390
                          s, option_name)
204
391
        return val
205
392
 
206
 
    def get_user_option_as_list(self, option_name):
 
393
    def get_user_option_as_list(self, option_name, expand=None):
207
394
        """Get a generic option as a list - no special process, no default.
208
395
 
209
396
        :return None if the option doesn't exist. Returns the value as a list
210
397
            otherwise.
211
398
        """
212
 
        l = self._get_user_option(option_name)
 
399
        l = self.get_user_option(option_name, expand=expand)
213
400
        if isinstance(l, (str, unicode)):
214
 
            # A single value, most probably the user forgot the final ','
 
401
            # A single value, most probably the user forgot (or didn't care to
 
402
            # add) the final ','
215
403
            l = [l]
216
404
        return l
217
405
 
257
445
 
258
446
        Something similar to 'Martin Pool <mbp@sourcefrog.net>'
259
447
 
260
 
        $BZR_EMAIL can be set to override this (as well as the
261
 
        deprecated $BZREMAIL), then
 
448
        $BZR_EMAIL can be set to override this, then
262
449
        the concrete policy type is checked, and finally
263
450
        $EMAIL is examined.
264
 
        If none is found, a reasonable default is (hopefully)
265
 
        created.
266
 
 
267
 
        TODO: Check it's reasonably well-formed.
 
451
        If no username can be found, errors.NoWhoami exception is raised.
268
452
        """
269
453
        v = os.environ.get('BZR_EMAIL')
270
454
        if v:
271
455
            return v.decode(osutils.get_user_encoding())
272
 
 
273
456
        v = self._get_user_id()
274
457
        if v:
275
458
            return v
276
 
 
277
459
        v = os.environ.get('EMAIL')
278
460
        if v:
279
461
            return v.decode(osutils.get_user_encoding())
280
 
 
281
462
        name, email = _auto_user_id()
282
 
        if name:
 
463
        if name and email:
283
464
            return '%s <%s>' % (name, email)
284
 
        else:
 
465
        elif email:
285
466
            return email
 
467
        raise errors.NoWhoami()
 
468
 
 
469
    def ensure_username(self):
 
470
        """Raise errors.NoWhoami if username is not set.
 
471
 
 
472
        This method relies on the username() function raising the error.
 
473
        """
 
474
        self.username()
286
475
 
287
476
    def signature_checking(self):
288
477
        """What is the current policy for signature checking?."""
346
535
        else:
347
536
            return True
348
537
 
 
538
    def get_merge_tools(self):
 
539
        tools = {}
 
540
        for (oname, value, section, conf_id, parser) in self._get_options():
 
541
            if oname.startswith('bzr.mergetool.'):
 
542
                tool_name = oname[len('bzr.mergetool.'):]
 
543
                tools[tool_name] = value
 
544
        trace.mutter('loaded merge tools: %r' % tools)
 
545
        return tools
 
546
 
 
547
    def find_merge_tool(self, name):
 
548
        # We fake a defaults mechanism here by checking if the given name can 
 
549
        # be found in the known_merge_tools if it's not found in the config.
 
550
        # This should be done through the proposed config defaults mechanism
 
551
        # when it becomes available in the future.
 
552
        command_line = (self.get_user_option('bzr.mergetool.%s' % name,
 
553
                                             expand=False)
 
554
                        or mergetools.known_merge_tools.get(name, None))
 
555
        return command_line
 
556
 
349
557
 
350
558
class IniBasedConfig(Config):
351
559
    """A configuration policy that draws from ini files."""
352
560
 
353
 
    def __init__(self, get_filename):
 
561
    def __init__(self, get_filename=symbol_versioning.DEPRECATED_PARAMETER,
 
562
                 file_name=None):
 
563
        """Base class for configuration files using an ini-like syntax.
 
564
 
 
565
        :param file_name: The configuration file path.
 
566
        """
354
567
        super(IniBasedConfig, self).__init__()
355
 
        self._get_filename = get_filename
 
568
        self.file_name = file_name
 
569
        if symbol_versioning.deprecated_passed(get_filename):
 
570
            symbol_versioning.warn(
 
571
                'IniBasedConfig.__init__(get_filename) was deprecated in 2.3.'
 
572
                ' Use file_name instead.',
 
573
                DeprecationWarning,
 
574
                stacklevel=2)
 
575
            if get_filename is not None:
 
576
                self.file_name = get_filename()
 
577
        else:
 
578
            self.file_name = file_name
 
579
        self._content = None
356
580
        self._parser = None
357
581
 
358
 
    def _get_parser(self, file=None):
 
582
    @classmethod
 
583
    def from_string(cls, str_or_unicode, file_name=None, save=False):
 
584
        """Create a config object from a string.
 
585
 
 
586
        :param str_or_unicode: A string representing the file content. This will
 
587
            be utf-8 encoded.
 
588
 
 
589
        :param file_name: The configuration file path.
 
590
 
 
591
        :param _save: Whether the file should be saved upon creation.
 
592
        """
 
593
        conf = cls(file_name=file_name)
 
594
        conf._create_from_string(str_or_unicode, save)
 
595
        return conf
 
596
 
 
597
    def _create_from_string(self, str_or_unicode, save):
 
598
        self._content = StringIO(str_or_unicode.encode('utf-8'))
 
599
        # Some tests use in-memory configs, some other always need the config
 
600
        # file to exist on disk.
 
601
        if save:
 
602
            self._write_config_file()
 
603
 
 
604
    def _get_parser(self, file=symbol_versioning.DEPRECATED_PARAMETER):
359
605
        if self._parser is not None:
360
606
            return self._parser
361
 
        if file is None:
362
 
            input = self._get_filename()
 
607
        if symbol_versioning.deprecated_passed(file):
 
608
            symbol_versioning.warn(
 
609
                'IniBasedConfig._get_parser(file=xxx) was deprecated in 2.3.'
 
610
                ' Use IniBasedConfig(_content=xxx) instead.',
 
611
                DeprecationWarning,
 
612
                stacklevel=2)
 
613
        if self._content is not None:
 
614
            co_input = self._content
 
615
        elif self.file_name is None:
 
616
            raise AssertionError('We have no content to create the config')
363
617
        else:
364
 
            input = file
 
618
            co_input = self.file_name
365
619
        try:
366
 
            self._parser = ConfigObj(input, encoding='utf-8')
 
620
            self._parser = ConfigObj(co_input, encoding='utf-8')
367
621
        except configobj.ConfigObjError, e:
368
622
            raise errors.ParseConfigError(e.errors, e.config.filename)
 
623
        # Make sure self.reload() will use the right file name
 
624
        self._parser.filename = self.file_name
369
625
        return self._parser
370
626
 
 
627
    def reload(self):
 
628
        """Reload the config file from disk."""
 
629
        if self.file_name is None:
 
630
            raise AssertionError('We need a file name to reload the config')
 
631
        if self._parser is not None:
 
632
            self._parser.reload()
 
633
 
371
634
    def _get_matching_sections(self):
372
635
        """Return an ordered list of (section_name, extra_path) pairs.
373
636
 
384
647
        """Override this to define the section used by the config."""
385
648
        return "DEFAULT"
386
649
 
 
650
    def _get_sections(self, name=None):
 
651
        """Returns an iterator of the sections specified by ``name``.
 
652
 
 
653
        :param name: The section name. If None is supplied, the default
 
654
            configurations are yielded.
 
655
 
 
656
        :return: A tuple (name, section, config_id) for all sections that will
 
657
            be walked by user_get_option() in the 'right' order. The first one
 
658
            is where set_user_option() will update the value.
 
659
        """
 
660
        parser = self._get_parser()
 
661
        if name is not None:
 
662
            yield (name, parser[name], self.config_id())
 
663
        else:
 
664
            # No section name has been given so we fallback to the configobj
 
665
            # itself which holds the variables defined outside of any section.
 
666
            yield (None, parser, self.config_id())
 
667
 
 
668
    def _get_options(self, sections=None):
 
669
        """Return an ordered list of (name, value, section, config_id) tuples.
 
670
 
 
671
        All options are returned with their associated value and the section
 
672
        they appeared in. ``config_id`` is a unique identifier for the
 
673
        configuration file the option is defined in.
 
674
 
 
675
        :param sections: Default to ``_get_matching_sections`` if not
 
676
            specified. This gives a better control to daughter classes about
 
677
            which sections should be searched. This is a list of (name,
 
678
            configobj) tuples.
 
679
        """
 
680
        opts = []
 
681
        if sections is None:
 
682
            parser = self._get_parser()
 
683
            sections = []
 
684
            for (section_name, _) in self._get_matching_sections():
 
685
                try:
 
686
                    section = parser[section_name]
 
687
                except KeyError:
 
688
                    # This could happen for an empty file for which we define a
 
689
                    # DEFAULT section. FIXME: Force callers to provide sections
 
690
                    # instead ? -- vila 20100930
 
691
                    continue
 
692
                sections.append((section_name, section))
 
693
        config_id = self.config_id()
 
694
        for (section_name, section) in sections:
 
695
            for (name, value) in section.iteritems():
 
696
                yield (name, parser._quote(value), section_name,
 
697
                       config_id, parser)
 
698
 
387
699
    def _get_option_policy(self, section, option_name):
388
700
        """Return the policy for the given (section, option_name) pair."""
389
701
        return POLICY_NONE
476
788
    def _get_nickname(self):
477
789
        return self.get_user_option('nickname')
478
790
 
479
 
 
480
 
class GlobalConfig(IniBasedConfig):
 
791
    def remove_user_option(self, option_name, section_name=None):
 
792
        """Remove a user option and save the configuration file.
 
793
 
 
794
        :param option_name: The option to be removed.
 
795
 
 
796
        :param section_name: The section the option is defined in, default to
 
797
            the default section.
 
798
        """
 
799
        self.reload()
 
800
        parser = self._get_parser()
 
801
        if section_name is None:
 
802
            section = parser
 
803
        else:
 
804
            section = parser[section_name]
 
805
        try:
 
806
            del section[option_name]
 
807
        except KeyError:
 
808
            raise errors.NoSuchConfigOption(option_name)
 
809
        self._write_config_file()
 
810
 
 
811
    def _write_config_file(self):
 
812
        if self.file_name is None:
 
813
            raise AssertionError('We cannot save, self.file_name is None')
 
814
        conf_dir = os.path.dirname(self.file_name)
 
815
        ensure_config_dir_exists(conf_dir)
 
816
        atomic_file = atomicfile.AtomicFile(self.file_name)
 
817
        self._get_parser().write(atomic_file)
 
818
        atomic_file.commit()
 
819
        atomic_file.close()
 
820
        osutils.copy_ownership_from_path(self.file_name)
 
821
 
 
822
 
 
823
class LockableConfig(IniBasedConfig):
 
824
    """A configuration needing explicit locking for access.
 
825
 
 
826
    If several processes try to write the config file, the accesses need to be
 
827
    serialized.
 
828
 
 
829
    Daughter classes should decorate all methods that update a config with the
 
830
    ``@needs_write_lock`` decorator (they call, directly or indirectly, the
 
831
    ``_write_config_file()`` method. These methods (typically ``set_option()``
 
832
    and variants must reload the config file from disk before calling
 
833
    ``_write_config_file()``), this can be achieved by calling the
 
834
    ``self.reload()`` method. Note that the lock scope should cover both the
 
835
    reading and the writing of the config file which is why the decorator can't
 
836
    be applied to ``_write_config_file()`` only.
 
837
 
 
838
    This should be enough to implement the following logic:
 
839
    - lock for exclusive write access,
 
840
    - reload the config file from disk,
 
841
    - set the new value
 
842
    - unlock
 
843
 
 
844
    This logic guarantees that a writer can update a value without erasing an
 
845
    update made by another writer.
 
846
    """
 
847
 
 
848
    lock_name = 'lock'
 
849
 
 
850
    def __init__(self, file_name):
 
851
        super(LockableConfig, self).__init__(file_name=file_name)
 
852
        self.dir = osutils.dirname(osutils.safe_unicode(self.file_name))
 
853
        # FIXME: It doesn't matter that we don't provide possible_transports
 
854
        # below since this is currently used only for local config files ;
 
855
        # local transports are not shared. But if/when we start using
 
856
        # LockableConfig for other kind of transports, we will need to reuse
 
857
        # whatever connection is already established -- vila 20100929
 
858
        self.transport = transport.get_transport(self.dir)
 
859
        self._lock = lockdir.LockDir(self.transport, self.lock_name)
 
860
 
 
861
    def _create_from_string(self, unicode_bytes, save):
 
862
        super(LockableConfig, self)._create_from_string(unicode_bytes, False)
 
863
        if save:
 
864
            # We need to handle the saving here (as opposed to IniBasedConfig)
 
865
            # to be able to lock
 
866
            self.lock_write()
 
867
            self._write_config_file()
 
868
            self.unlock()
 
869
 
 
870
    def lock_write(self, token=None):
 
871
        """Takes a write lock in the directory containing the config file.
 
872
 
 
873
        If the directory doesn't exist it is created.
 
874
        """
 
875
        ensure_config_dir_exists(self.dir)
 
876
        return self._lock.lock_write(token)
 
877
 
 
878
    def unlock(self):
 
879
        self._lock.unlock()
 
880
 
 
881
    def break_lock(self):
 
882
        self._lock.break_lock()
 
883
 
 
884
    @needs_write_lock
 
885
    def remove_user_option(self, option_name, section_name=None):
 
886
        super(LockableConfig, self).remove_user_option(option_name,
 
887
                                                       section_name)
 
888
 
 
889
    def _write_config_file(self):
 
890
        if self._lock is None or not self._lock.is_held:
 
891
            # NB: if the following exception is raised it probably means a
 
892
            # missing @needs_write_lock decorator on one of the callers.
 
893
            raise errors.ObjectNotLocked(self)
 
894
        super(LockableConfig, self)._write_config_file()
 
895
 
 
896
 
 
897
class GlobalConfig(LockableConfig):
481
898
    """The configuration that should be used for a specific location."""
482
899
 
 
900
    def __init__(self):
 
901
        super(GlobalConfig, self).__init__(file_name=config_filename())
 
902
 
 
903
    def config_id(self):
 
904
        return 'bazaar'
 
905
 
 
906
    @classmethod
 
907
    def from_string(cls, str_or_unicode, save=False):
 
908
        """Create a config object from a string.
 
909
 
 
910
        :param str_or_unicode: A string representing the file content. This
 
911
            will be utf-8 encoded.
 
912
 
 
913
        :param save: Whether the file should be saved upon creation.
 
914
        """
 
915
        conf = cls()
 
916
        conf._create_from_string(str_or_unicode, save)
 
917
        return conf
 
918
 
 
919
    @deprecated_method(deprecated_in((2, 4, 0)))
483
920
    def get_editor(self):
484
921
        return self._get_user_option('editor')
485
922
 
486
 
    def __init__(self):
487
 
        super(GlobalConfig, self).__init__(config_filename)
488
 
 
 
923
    @needs_write_lock
489
924
    def set_user_option(self, option, value):
490
925
        """Save option and its value in the configuration."""
491
926
        self._set_option(option, value, 'DEFAULT')
497
932
        else:
498
933
            return {}
499
934
 
 
935
    @needs_write_lock
500
936
    def set_alias(self, alias_name, alias_command):
501
937
        """Save the alias in the configuration."""
502
938
        self._set_option(alias_name, alias_command, 'ALIASES')
503
939
 
 
940
    @needs_write_lock
504
941
    def unset_alias(self, alias_name):
505
942
        """Unset an existing alias."""
 
943
        self.reload()
506
944
        aliases = self._get_parser().get('ALIASES')
507
945
        if not aliases or alias_name not in aliases:
508
946
            raise errors.NoSuchAlias(alias_name)
510
948
        self._write_config_file()
511
949
 
512
950
    def _set_option(self, option, value, section):
513
 
        # FIXME: RBC 20051029 This should refresh the parser and also take a
514
 
        # file lock on bazaar.conf.
515
 
        conf_dir = os.path.dirname(self._get_filename())
516
 
        ensure_config_dir_exists(conf_dir)
 
951
        self.reload()
517
952
        self._get_parser().setdefault(section, {})[option] = value
518
953
        self._write_config_file()
519
954
 
520
 
    def _write_config_file(self):
521
 
        path = self._get_filename()
522
 
        f = open(path, 'wb')
523
 
        osutils.copy_ownership_from_path(path)
524
 
        self._get_parser().write(f)
525
 
        f.close()
526
 
 
527
 
 
528
 
class LocationConfig(IniBasedConfig):
 
955
 
 
956
    def _get_sections(self, name=None):
 
957
        """See IniBasedConfig._get_sections()."""
 
958
        parser = self._get_parser()
 
959
        # We don't give access to options defined outside of any section, we
 
960
        # used the DEFAULT section by... default.
 
961
        if name in (None, 'DEFAULT'):
 
962
            # This could happen for an empty file where the DEFAULT section
 
963
            # doesn't exist yet. So we force DEFAULT when yielding
 
964
            name = 'DEFAULT'
 
965
            if 'DEFAULT' not in parser:
 
966
               parser['DEFAULT']= {}
 
967
        yield (name, parser[name], self.config_id())
 
968
 
 
969
    @needs_write_lock
 
970
    def remove_user_option(self, option_name, section_name=None):
 
971
        if section_name is None:
 
972
            # We need to force the default section.
 
973
            section_name = 'DEFAULT'
 
974
        # We need to avoid the LockableConfig implementation or we'll lock
 
975
        # twice
 
976
        super(LockableConfig, self).remove_user_option(option_name,
 
977
                                                       section_name)
 
978
 
 
979
def _iter_for_location_by_parts(sections, location):
 
980
    """Keep only the sessions matching the specified location.
 
981
 
 
982
    :param sections: An iterable of section names.
 
983
 
 
984
    :param location: An url or a local path to match against.
 
985
 
 
986
    :returns: An iterator of (section, extra_path, nb_parts) where nb is the
 
987
        number of path components in the section name, section is the section
 
988
        name and extra_path is the difference between location and the section
 
989
        name.
 
990
 
 
991
    ``location`` will always be a local path and never a 'file://' url but the
 
992
    section names themselves can be in either form.
 
993
    """
 
994
    location_parts = location.rstrip('/').split('/')
 
995
 
 
996
    for section in sections:
 
997
        # location is a local path if possible, so we need to convert 'file://'
 
998
        # urls in section names to local paths if necessary.
 
999
 
 
1000
        # This also avoids having file:///path be a more exact
 
1001
        # match than '/path'.
 
1002
 
 
1003
        # FIXME: This still raises an issue if a user defines both file:///path
 
1004
        # *and* /path. Should we raise an error in this case -- vila 20110505
 
1005
 
 
1006
        if section.startswith('file://'):
 
1007
            section_path = urlutils.local_path_from_url(section)
 
1008
        else:
 
1009
            section_path = section
 
1010
        section_parts = section_path.rstrip('/').split('/')
 
1011
 
 
1012
        matched = True
 
1013
        if len(section_parts) > len(location_parts):
 
1014
            # More path components in the section, they can't match
 
1015
            matched = False
 
1016
        else:
 
1017
            # Rely on zip truncating in length to the length of the shortest
 
1018
            # argument sequence.
 
1019
            names = zip(location_parts, section_parts)
 
1020
            for name in names:
 
1021
                if not fnmatch.fnmatch(name[0], name[1]):
 
1022
                    matched = False
 
1023
                    break
 
1024
        if not matched:
 
1025
            continue
 
1026
        # build the path difference between the section and the location
 
1027
        extra_path = '/'.join(location_parts[len(section_parts):])
 
1028
        yield section, extra_path, len(section_parts)
 
1029
 
 
1030
 
 
1031
class LocationConfig(LockableConfig):
529
1032
    """A configuration object that gives the policy for a location."""
530
1033
 
531
1034
    def __init__(self, location):
532
 
        name_generator = locations_config_filename
533
 
        if (not os.path.exists(name_generator()) and
534
 
                os.path.exists(branches_config_filename())):
535
 
            if sys.platform == 'win32':
536
 
                trace.warning('Please rename %s to %s'
537
 
                              % (branches_config_filename(),
538
 
                                 locations_config_filename()))
539
 
            else:
540
 
                trace.warning('Please rename ~/.bazaar/branches.conf'
541
 
                              ' to ~/.bazaar/locations.conf')
542
 
            name_generator = branches_config_filename
543
 
        super(LocationConfig, self).__init__(name_generator)
 
1035
        super(LocationConfig, self).__init__(
 
1036
            file_name=locations_config_filename())
544
1037
        # local file locations are looked up by local path, rather than
545
1038
        # by file url. This is because the config file is a user
546
1039
        # file, and we would rather not expose the user to file urls.
548
1041
            location = urlutils.local_path_from_url(location)
549
1042
        self.location = location
550
1043
 
 
1044
    def config_id(self):
 
1045
        return 'locations'
 
1046
 
 
1047
    @classmethod
 
1048
    def from_string(cls, str_or_unicode, location, save=False):
 
1049
        """Create a config object from a string.
 
1050
 
 
1051
        :param str_or_unicode: A string representing the file content. This will
 
1052
            be utf-8 encoded.
 
1053
 
 
1054
        :param location: The location url to filter the configuration.
 
1055
 
 
1056
        :param save: Whether the file should be saved upon creation.
 
1057
        """
 
1058
        conf = cls(location)
 
1059
        conf._create_from_string(str_or_unicode, save)
 
1060
        return conf
 
1061
 
551
1062
    def _get_matching_sections(self):
552
1063
        """Return an ordered list of section names matching this location."""
553
 
        sections = self._get_parser()
554
 
        location_names = self.location.split('/')
555
 
        if self.location.endswith('/'):
556
 
            del location_names[-1]
557
 
        matches=[]
558
 
        for section in sections:
559
 
            # location is a local path if possible, so we need
560
 
            # to convert 'file://' urls to local paths if necessary.
561
 
            # This also avoids having file:///path be a more exact
562
 
            # match than '/path'.
563
 
            if section.startswith('file://'):
564
 
                section_path = urlutils.local_path_from_url(section)
565
 
            else:
566
 
                section_path = section
567
 
            section_names = section_path.split('/')
568
 
            if section.endswith('/'):
569
 
                del section_names[-1]
570
 
            names = zip(location_names, section_names)
571
 
            matched = True
572
 
            for name in names:
573
 
                if not fnmatch(name[0], name[1]):
574
 
                    matched = False
575
 
                    break
576
 
            if not matched:
577
 
                continue
578
 
            # so, for the common prefix they matched.
579
 
            # if section is longer, no match.
580
 
            if len(section_names) > len(location_names):
581
 
                continue
582
 
            matches.append((len(section_names), section,
583
 
                            '/'.join(location_names[len(section_names):])))
584
 
        matches.sort(reverse=True)
585
 
        sections = []
586
 
        for (length, section, extra_path) in matches:
587
 
            sections.append((section, extra_path))
 
1064
        matches = list(_iter_for_location_by_parts(self._get_parser(),
 
1065
                                                   self.location))
 
1066
        # put the longest (aka more specific) locations first
 
1067
        matches.sort(
 
1068
            key=lambda (section, extra_path, length): (length, section),
 
1069
            reverse=True)
 
1070
        for (section, extra_path, length) in matches:
 
1071
            yield section, extra_path
588
1072
            # should we stop looking for parent configs here?
589
1073
            try:
590
1074
                if self._get_parser()[section].as_bool('ignore_parents'):
591
1075
                    break
592
1076
            except KeyError:
593
1077
                pass
594
 
        return sections
 
1078
 
 
1079
    def _get_sections(self, name=None):
 
1080
        """See IniBasedConfig._get_sections()."""
 
1081
        # We ignore the name here as the only sections handled are named with
 
1082
        # the location path and we don't expose embedded sections either.
 
1083
        parser = self._get_parser()
 
1084
        for name, extra_path in self._get_matching_sections():
 
1085
            yield (name, parser[name], self.config_id())
595
1086
 
596
1087
    def _get_option_policy(self, section, option_name):
597
1088
        """Return the policy for the given (section, option_name) pair."""
641
1132
            if policy_key in self._get_parser()[section]:
642
1133
                del self._get_parser()[section][policy_key]
643
1134
 
 
1135
    @needs_write_lock
644
1136
    def set_user_option(self, option, value, store=STORE_LOCATION):
645
1137
        """Save option and its value in the configuration."""
646
1138
        if store not in [STORE_LOCATION,
648
1140
                         STORE_LOCATION_APPENDPATH]:
649
1141
            raise ValueError('bad storage policy %r for %r' %
650
1142
                (store, option))
651
 
        # FIXME: RBC 20051029 This should refresh the parser and also take a
652
 
        # file lock on locations.conf.
653
 
        conf_dir = os.path.dirname(self._get_filename())
654
 
        ensure_config_dir_exists(conf_dir)
 
1143
        self.reload()
655
1144
        location = self.location
656
1145
        if location.endswith('/'):
657
1146
            location = location[:-1]
658
 
        if (not location in self._get_parser() and
659
 
            not location + '/' in self._get_parser()):
660
 
            self._get_parser()[location]={}
661
 
        elif location + '/' in self._get_parser():
 
1147
        parser = self._get_parser()
 
1148
        if not location in parser and not location + '/' in parser:
 
1149
            parser[location] = {}
 
1150
        elif location + '/' in parser:
662
1151
            location = location + '/'
663
 
        self._get_parser()[location][option]=value
 
1152
        parser[location][option]=value
664
1153
        # the allowed values of store match the config policies
665
1154
        self._set_option_policy(location, option, store)
666
 
        self._get_parser().write(file(self._get_filename(), 'wb'))
 
1155
        self._write_config_file()
667
1156
 
668
1157
 
669
1158
class BranchConfig(Config):
670
1159
    """A configuration object giving the policy for a branch."""
671
1160
 
 
1161
    def __init__(self, branch):
 
1162
        super(BranchConfig, self).__init__()
 
1163
        self._location_config = None
 
1164
        self._branch_data_config = None
 
1165
        self._global_config = None
 
1166
        self.branch = branch
 
1167
        self.option_sources = (self._get_location_config,
 
1168
                               self._get_branch_data_config,
 
1169
                               self._get_global_config)
 
1170
 
 
1171
    def config_id(self):
 
1172
        return 'branch'
 
1173
 
672
1174
    def _get_branch_data_config(self):
673
1175
        if self._branch_data_config is None:
674
1176
            self._branch_data_config = TreeConfig(self.branch)
 
1177
            self._branch_data_config.config_id = self.config_id
675
1178
        return self._branch_data_config
676
1179
 
677
1180
    def _get_location_config(self):
745
1248
                return value
746
1249
        return None
747
1250
 
 
1251
    def _get_sections(self, name=None):
 
1252
        """See IniBasedConfig.get_sections()."""
 
1253
        for source in self.option_sources:
 
1254
            for section in source()._get_sections(name):
 
1255
                yield section
 
1256
 
 
1257
    def _get_options(self, sections=None):
 
1258
        opts = []
 
1259
        # First the locations options
 
1260
        for option in self._get_location_config()._get_options():
 
1261
            yield option
 
1262
        # Then the branch options
 
1263
        branch_config = self._get_branch_data_config()
 
1264
        if sections is None:
 
1265
            sections = [('DEFAULT', branch_config._get_parser())]
 
1266
        # FIXME: We shouldn't have to duplicate the code in IniBasedConfig but
 
1267
        # Config itself has no notion of sections :( -- vila 20101001
 
1268
        config_id = self.config_id()
 
1269
        for (section_name, section) in sections:
 
1270
            for (name, value) in section.iteritems():
 
1271
                yield (name, value, section_name,
 
1272
                       config_id, branch_config._get_parser())
 
1273
        # Then the global options
 
1274
        for option in self._get_global_config()._get_options():
 
1275
            yield option
 
1276
 
748
1277
    def set_user_option(self, name, value, store=STORE_BRANCH,
749
1278
        warn_masked=False):
750
1279
        if store == STORE_BRANCH:
768
1297
                        trace.warning('Value "%s" is masked by "%s" from'
769
1298
                                      ' branch.conf', value, mask_value)
770
1299
 
 
1300
    def remove_user_option(self, option_name, section_name=None):
 
1301
        self._get_branch_data_config().remove_option(option_name, section_name)
 
1302
 
771
1303
    def _gpg_signing_command(self):
772
1304
        """See Config.gpg_signing_command."""
773
1305
        return self._get_safe_value('_gpg_signing_command')
774
1306
 
775
 
    def __init__(self, branch):
776
 
        super(BranchConfig, self).__init__()
777
 
        self._location_config = None
778
 
        self._branch_data_config = None
779
 
        self._global_config = None
780
 
        self.branch = branch
781
 
        self.option_sources = (self._get_location_config,
782
 
                               self._get_branch_data_config,
783
 
                               self._get_global_config)
784
 
 
785
1307
    def _post_commit(self):
786
1308
        """See Config.post_commit."""
787
1309
        return self._get_safe_value('_post_commit')
817
1339
            parent_dir = os.path.dirname(path)
818
1340
            if not os.path.isdir(parent_dir):
819
1341
                trace.mutter('creating config parent directory: %r', parent_dir)
820
 
            os.mkdir(parent_dir)
 
1342
                os.mkdir(parent_dir)
821
1343
        trace.mutter('creating config directory: %r', path)
822
1344
        os.mkdir(path)
823
1345
        osutils.copy_ownership_from_path(path)
826
1348
def config_dir():
827
1349
    """Return per-user configuration directory.
828
1350
 
829
 
    By default this is ~/.bazaar/
 
1351
    By default this is %APPDATA%/bazaar/2.0 on Windows, ~/.bazaar on Mac OS X
 
1352
    and Linux.  On Linux, if there is a $XDG_CONFIG_HOME/bazaar directory,
 
1353
    that will be used instead.
830
1354
 
831
1355
    TODO: Global option --config-dir to override this.
832
1356
    """
833
1357
    base = os.environ.get('BZR_HOME', None)
834
1358
    if sys.platform == 'win32':
 
1359
        # environ variables on Windows are in user encoding/mbcs. So decode
 
1360
        # before using one
 
1361
        if base is not None:
 
1362
            base = base.decode('mbcs')
835
1363
        if base is None:
836
1364
            base = win32utils.get_appdata_location_unicode()
837
1365
        if base is None:
838
1366
            base = os.environ.get('HOME', None)
 
1367
            if base is not None:
 
1368
                base = base.decode('mbcs')
839
1369
        if base is None:
840
1370
            raise errors.BzrError('You must have one of BZR_HOME, APPDATA,'
841
1371
                                  ' or HOME set')
842
1372
        return osutils.pathjoin(base, 'bazaar', '2.0')
 
1373
    elif sys.platform == 'darwin':
 
1374
        if base is None:
 
1375
            # this takes into account $HOME
 
1376
            base = os.path.expanduser("~")
 
1377
        return osutils.pathjoin(base, '.bazaar')
843
1378
    else:
844
 
        # cygwin, linux, and darwin all have a $HOME directory
845
1379
        if base is None:
 
1380
 
 
1381
            xdg_dir = os.environ.get('XDG_CONFIG_HOME', None)
 
1382
            if xdg_dir is None:
 
1383
                xdg_dir = osutils.pathjoin(os.path.expanduser("~"), ".config")
 
1384
            xdg_dir = osutils.pathjoin(xdg_dir, 'bazaar')
 
1385
            if osutils.isdir(xdg_dir):
 
1386
                trace.mutter(
 
1387
                    "Using configuration in XDG directory %s." % xdg_dir)
 
1388
                return xdg_dir
 
1389
 
846
1390
            base = os.path.expanduser("~")
847
1391
        return osutils.pathjoin(base, ".bazaar")
848
1392
 
852
1396
    return osutils.pathjoin(config_dir(), 'bazaar.conf')
853
1397
 
854
1398
 
855
 
def branches_config_filename():
856
 
    """Return per-user configuration ini file filename."""
857
 
    return osutils.pathjoin(config_dir(), 'branches.conf')
858
 
 
859
 
 
860
1399
def locations_config_filename():
861
1400
    """Return per-user configuration ini file filename."""
862
1401
    return osutils.pathjoin(config_dir(), 'locations.conf')
899
1438
        return os.path.expanduser('~/.cache')
900
1439
 
901
1440
 
 
1441
def _get_default_mail_domain():
 
1442
    """If possible, return the assumed default email domain.
 
1443
 
 
1444
    :returns: string mail domain, or None.
 
1445
    """
 
1446
    if sys.platform == 'win32':
 
1447
        # No implementation yet; patches welcome
 
1448
        return None
 
1449
    try:
 
1450
        f = open('/etc/mailname')
 
1451
    except (IOError, OSError), e:
 
1452
        return None
 
1453
    try:
 
1454
        domain = f.read().strip()
 
1455
        return domain
 
1456
    finally:
 
1457
        f.close()
 
1458
 
 
1459
 
902
1460
def _auto_user_id():
903
1461
    """Calculate automatic user identification.
904
1462
 
905
 
    Returns (realname, email).
 
1463
    :returns: (realname, email), either of which may be None if they can't be
 
1464
    determined.
906
1465
 
907
1466
    Only used when none is set in the environment or the id file.
908
1467
 
909
 
    This previously used the FQDN as the default domain, but that can
910
 
    be very slow on machines where DNS is broken.  So now we simply
911
 
    use the hostname.
 
1468
    This only returns an email address if we can be fairly sure the 
 
1469
    address is reasonable, ie if /etc/mailname is set on unix.
 
1470
 
 
1471
    This doesn't use the FQDN as the default domain because that may be 
 
1472
    slow, and it doesn't use the hostname alone because that's not normally 
 
1473
    a reasonable address.
912
1474
    """
913
 
    import socket
914
 
 
915
1475
    if sys.platform == 'win32':
916
 
        name = win32utils.get_user_name_unicode()
917
 
        if name is None:
918
 
            raise errors.BzrError("Cannot autodetect user name.\n"
919
 
                                  "Please, set your name with command like:\n"
920
 
                                  'bzr whoami "Your Name <name@domain.com>"')
921
 
        host = win32utils.get_host_name_unicode()
922
 
        if host is None:
923
 
            host = socket.gethostname()
924
 
        return name, (name + '@' + host)
925
 
 
926
 
    try:
927
 
        import pwd
928
 
        uid = os.getuid()
929
 
        try:
930
 
            w = pwd.getpwuid(uid)
931
 
        except KeyError:
932
 
            raise errors.BzrCommandError('Unable to determine your name.  '
933
 
                'Please use "bzr whoami" to set it.')
934
 
 
935
 
        # we try utf-8 first, because on many variants (like Linux),
936
 
        # /etc/passwd "should" be in utf-8, and because it's unlikely to give
937
 
        # false positives.  (many users will have their user encoding set to
938
 
        # latin-1, which cannot raise UnicodeError.)
939
 
        try:
940
 
            gecos = w.pw_gecos.decode('utf-8')
941
 
            encoding = 'utf-8'
942
 
        except UnicodeError:
943
 
            try:
944
 
                encoding = osutils.get_user_encoding()
945
 
                gecos = w.pw_gecos.decode(encoding)
946
 
            except UnicodeError:
947
 
                raise errors.BzrCommandError('Unable to determine your name.  '
948
 
                   'Use "bzr whoami" to set it.')
949
 
        try:
950
 
            username = w.pw_name.decode(encoding)
951
 
        except UnicodeError:
952
 
            raise errors.BzrCommandError('Unable to determine your name.  '
953
 
                'Use "bzr whoami" to set it.')
954
 
 
955
 
        comma = gecos.find(',')
956
 
        if comma == -1:
957
 
            realname = gecos
958
 
        else:
959
 
            realname = gecos[:comma]
960
 
        if not realname:
961
 
            realname = username
962
 
 
963
 
    except ImportError:
964
 
        import getpass
965
 
        try:
966
 
            user_encoding = osutils.get_user_encoding()
967
 
            realname = username = getpass.getuser().decode(user_encoding)
968
 
        except UnicodeDecodeError:
969
 
            raise errors.BzrError("Can't decode username as %s." % \
970
 
                    user_encoding)
971
 
 
972
 
    return realname, (username + '@' + socket.gethostname())
 
1476
        # No implementation to reliably determine Windows default mail
 
1477
        # address; please add one.
 
1478
        return None, None
 
1479
 
 
1480
    default_mail_domain = _get_default_mail_domain()
 
1481
    if not default_mail_domain:
 
1482
        return None, None
 
1483
 
 
1484
    import pwd
 
1485
    uid = os.getuid()
 
1486
    try:
 
1487
        w = pwd.getpwuid(uid)
 
1488
    except KeyError:
 
1489
        trace.mutter('no passwd entry for uid %d?' % uid)
 
1490
        return None, None
 
1491
 
 
1492
    # we try utf-8 first, because on many variants (like Linux),
 
1493
    # /etc/passwd "should" be in utf-8, and because it's unlikely to give
 
1494
    # false positives.  (many users will have their user encoding set to
 
1495
    # latin-1, which cannot raise UnicodeError.)
 
1496
    try:
 
1497
        gecos = w.pw_gecos.decode('utf-8')
 
1498
        encoding = 'utf-8'
 
1499
    except UnicodeError:
 
1500
        try:
 
1501
            encoding = osutils.get_user_encoding()
 
1502
            gecos = w.pw_gecos.decode(encoding)
 
1503
        except UnicodeError, e:
 
1504
            trace.mutter("cannot decode passwd entry %s" % w)
 
1505
            return None, None
 
1506
    try:
 
1507
        username = w.pw_name.decode(encoding)
 
1508
    except UnicodeError, e:
 
1509
        trace.mutter("cannot decode passwd entry %s" % w)
 
1510
        return None, None
 
1511
 
 
1512
    comma = gecos.find(',')
 
1513
    if comma == -1:
 
1514
        realname = gecos
 
1515
    else:
 
1516
        realname = gecos[:comma]
 
1517
 
 
1518
    return realname, (username + '@' + default_mail_domain)
973
1519
 
974
1520
 
975
1521
def parse_username(username):
1020
1566
 
1021
1567
    def set_option(self, value, name, section=None):
1022
1568
        """Set a per-branch configuration option"""
 
1569
        # FIXME: We shouldn't need to lock explicitly here but rather rely on
 
1570
        # higher levels providing the right lock -- vila 20101004
1023
1571
        self.branch.lock_write()
1024
1572
        try:
1025
1573
            self._config.set_option(value, name, section)
1026
1574
        finally:
1027
1575
            self.branch.unlock()
1028
1576
 
 
1577
    def remove_option(self, option_name, section_name=None):
 
1578
        # FIXME: We shouldn't need to lock explicitly here but rather rely on
 
1579
        # higher levels providing the right lock -- vila 20101004
 
1580
        self.branch.lock_write()
 
1581
        try:
 
1582
            self._config.remove_option(option_name, section_name)
 
1583
        finally:
 
1584
            self.branch.unlock()
 
1585
 
1029
1586
 
1030
1587
class AuthenticationConfig(object):
1031
1588
    """The authentication configuration file based on a ini file.
1063
1620
        """Save the config file, only tests should use it for now."""
1064
1621
        conf_dir = os.path.dirname(self._filename)
1065
1622
        ensure_config_dir_exists(conf_dir)
1066
 
        self._get_config().write(file(self._filename, 'wb'))
 
1623
        f = file(self._filename, 'wb')
 
1624
        try:
 
1625
            self._get_config().write(f)
 
1626
        finally:
 
1627
            f.close()
1067
1628
 
1068
1629
    def _set_option(self, section_name, option_name, value):
1069
1630
        """Set an authentication configuration option"""
1249
1810
            if ask:
1250
1811
                if prompt is None:
1251
1812
                    # Create a default prompt suitable for most cases
1252
 
                    prompt = scheme.upper() + ' %(host)s username'
 
1813
                    prompt = u'%s' % (scheme.upper(),) + u' %(host)s username'
1253
1814
                # Special handling for optional fields in the prompt
1254
1815
                if port is not None:
1255
1816
                    prompt_host = '%s:%d' % (host, port)
1293
1854
        if password is None:
1294
1855
            if prompt is None:
1295
1856
                # Create a default prompt suitable for most cases
1296
 
                prompt = '%s' % scheme.upper() + ' %(user)s@%(host)s password'
 
1857
                prompt = u'%s' % scheme.upper() + u' %(user)s@%(host)s password'
1297
1858
            # Special handling for optional fields in the prompt
1298
1859
            if port is not None:
1299
1860
                prompt_host = '%s:%d' % (host, port)
1470
2031
    """A Config that reads/writes a config file on a Transport.
1471
2032
 
1472
2033
    It is a low-level object that considers config data to be name/value pairs
1473
 
    that may be associated with a section.  Assigning meaning to the these
1474
 
    values is done at higher levels like TreeConfig.
 
2034
    that may be associated with a section.  Assigning meaning to these values
 
2035
    is done at higher levels like TreeConfig.
1475
2036
    """
1476
2037
 
1477
2038
    def __init__(self, transport, filename):
1510
2071
            configobj.setdefault(section, {})[name] = value
1511
2072
        self._set_configobj(configobj)
1512
2073
 
 
2074
    def remove_option(self, option_name, section_name=None):
 
2075
        configobj = self._get_configobj()
 
2076
        if section_name is None:
 
2077
            del configobj[option_name]
 
2078
        else:
 
2079
            del configobj[section_name][option_name]
 
2080
        self._set_configobj(configobj)
 
2081
 
1513
2082
    def _get_config_file(self):
1514
2083
        try:
1515
2084
            return StringIO(self._transport.get_bytes(self._filename))
1517
2086
            return StringIO()
1518
2087
 
1519
2088
    def _get_configobj(self):
1520
 
        return ConfigObj(self._get_config_file(), encoding='utf-8')
 
2089
        f = self._get_config_file()
 
2090
        try:
 
2091
            return ConfigObj(f, encoding='utf-8')
 
2092
        finally:
 
2093
            f.close()
1521
2094
 
1522
2095
    def _set_configobj(self, configobj):
1523
2096
        out_file = StringIO()
1524
2097
        configobj.write(out_file)
1525
2098
        out_file.seek(0)
1526
2099
        self._transport.put_file(self._filename, out_file)
 
2100
 
 
2101
 
 
2102
class Option(object):
 
2103
    """An option definition.
 
2104
 
 
2105
    The option *values* are stored in config files and found in sections.
 
2106
 
 
2107
    Here we define various properties about the option itself, its default
 
2108
    value, in which config files it can be stored, etc (TBC).
 
2109
    """
 
2110
 
 
2111
    def __init__(self, name, default=None):
 
2112
        self.name = name
 
2113
        self.default = default
 
2114
 
 
2115
    def get_default(self):
 
2116
        return self.default
 
2117
 
 
2118
 
 
2119
# Options registry
 
2120
 
 
2121
option_registry = registry.Registry()
 
2122
 
 
2123
 
 
2124
option_registry.register(
 
2125
    'editor', Option('editor'),
 
2126
    help='The command called to launch an editor to enter a message.')
 
2127
 
 
2128
 
 
2129
class Section(object):
 
2130
    """A section defines a dict of option name => value.
 
2131
 
 
2132
    This is merely a read-only dict which can add some knowledge about the
 
2133
    options. It is *not* a python dict object though and doesn't try to mimic
 
2134
    its API.
 
2135
    """
 
2136
 
 
2137
    def __init__(self, section_id, options):
 
2138
        self.id = section_id
 
2139
        # We re-use the dict-like object received
 
2140
        self.options = options
 
2141
 
 
2142
    def get(self, name, default=None):
 
2143
        return self.options.get(name, default)
 
2144
 
 
2145
    def __repr__(self):
 
2146
        # Mostly for debugging use
 
2147
        return "<config.%s id=%s>" % (self.__class__.__name__, self.id)
 
2148
 
 
2149
 
 
2150
_NewlyCreatedOption = object()
 
2151
"""Was the option created during the MutableSection lifetime"""
 
2152
 
 
2153
 
 
2154
class MutableSection(Section):
 
2155
    """A section allowing changes and keeping track of the original values."""
 
2156
 
 
2157
    def __init__(self, section_id, options):
 
2158
        super(MutableSection, self).__init__(section_id, options)
 
2159
        self.orig = {}
 
2160
 
 
2161
    def set(self, name, value):
 
2162
        if name not in self.options:
 
2163
            # This is a new option
 
2164
            self.orig[name] = _NewlyCreatedOption
 
2165
        elif name not in self.orig:
 
2166
            self.orig[name] = self.get(name, None)
 
2167
        self.options[name] = value
 
2168
 
 
2169
    def remove(self, name):
 
2170
        if name not in self.orig:
 
2171
            self.orig[name] = self.get(name, None)
 
2172
        del self.options[name]
 
2173
 
 
2174
 
 
2175
class Store(object):
 
2176
    """Abstract interface to persistent storage for configuration options."""
 
2177
 
 
2178
    readonly_section_class = Section
 
2179
    mutable_section_class = MutableSection
 
2180
 
 
2181
    def is_loaded(self):
 
2182
        """Returns True if the Store has been loaded.
 
2183
 
 
2184
        This is used to implement lazy loading and ensure the persistent
 
2185
        storage is queried only when needed.
 
2186
        """
 
2187
        raise NotImplementedError(self.is_loaded)
 
2188
 
 
2189
    def load(self):
 
2190
        """Loads the Store from persistent storage."""
 
2191
        raise NotImplementedError(self.load)
 
2192
 
 
2193
    def _load_from_string(self, str_or_unicode):
 
2194
        """Create a store from a string in configobj syntax.
 
2195
 
 
2196
        :param str_or_unicode: A string representing the file content. This will
 
2197
            be encoded to suit store needs internally.
 
2198
 
 
2199
        This is for tests and should not be used in production unless a
 
2200
        convincing use case can be demonstrated :)
 
2201
        """
 
2202
        raise NotImplementedError(self._load_from_string)
 
2203
 
 
2204
    def unload(self):
 
2205
        """Unloads the Store.
 
2206
 
 
2207
        This should make is_loaded() return False. This is used when the caller
 
2208
        knows that the persistent storage has changed or may have change since
 
2209
        the last load.
 
2210
        """
 
2211
        raise NotImplementedError(self.unload)
 
2212
 
 
2213
    def save(self):
 
2214
        """Saves the Store to persistent storage."""
 
2215
        raise NotImplementedError(self.save)
 
2216
 
 
2217
    def external_url(self):
 
2218
        raise NotImplementedError(self.external_url)
 
2219
 
 
2220
    def get_sections(self):
 
2221
        """Returns an ordered iterable of existing sections.
 
2222
 
 
2223
        :returns: An iterable of (name, dict).
 
2224
        """
 
2225
        raise NotImplementedError(self.get_sections)
 
2226
 
 
2227
    def get_mutable_section(self, section_name=None):
 
2228
        """Returns the specified mutable section.
 
2229
 
 
2230
        :param section_name: The section identifier
 
2231
        """
 
2232
        raise NotImplementedError(self.get_mutable_section)
 
2233
 
 
2234
    def __repr__(self):
 
2235
        # Mostly for debugging use
 
2236
        return "<config.%s(%s)>" % (self.__class__.__name__,
 
2237
                                    self.external_url())
 
2238
 
 
2239
 
 
2240
class IniFileStore(Store):
 
2241
    """A config Store using ConfigObj for storage.
 
2242
 
 
2243
    :ivar transport: The transport object where the config file is located.
 
2244
 
 
2245
    :ivar file_name: The config file basename in the transport directory.
 
2246
 
 
2247
    :ivar _config_obj: Private member to hold the ConfigObj instance used to
 
2248
        serialize/deserialize the config file.
 
2249
    """
 
2250
 
 
2251
    def __init__(self, transport, file_name):
 
2252
        """A config Store using ConfigObj for storage.
 
2253
 
 
2254
        :param transport: The transport object where the config file is located.
 
2255
 
 
2256
        :param file_name: The config file basename in the transport directory.
 
2257
        """
 
2258
        super(IniFileStore, self).__init__()
 
2259
        self.transport = transport
 
2260
        self.file_name = file_name
 
2261
        self._config_obj = None
 
2262
 
 
2263
    def is_loaded(self):
 
2264
        return self._config_obj != None
 
2265
 
 
2266
    def unload(self):
 
2267
        self._config_obj = None
 
2268
 
 
2269
    def load(self):
 
2270
        """Load the store from the associated file."""
 
2271
        if self.is_loaded():
 
2272
            return
 
2273
        content = self.transport.get_bytes(self.file_name)
 
2274
        self._load_from_string(content)
 
2275
 
 
2276
    def _load_from_string(self, str_or_unicode):
 
2277
        """Create a config store from a string.
 
2278
 
 
2279
        :param str_or_unicode: A string representing the file content. This will
 
2280
            be utf-8 encoded internally.
 
2281
 
 
2282
        This is for tests and should not be used in production unless a
 
2283
        convincing use case can be demonstrated :)
 
2284
        """
 
2285
        if self.is_loaded():
 
2286
            raise AssertionError('Already loaded: %r' % (self._config_obj,))
 
2287
        co_input = StringIO(str_or_unicode.encode('utf-8'))
 
2288
        try:
 
2289
            # The config files are always stored utf8-encoded
 
2290
            self._config_obj = ConfigObj(co_input, encoding='utf-8')
 
2291
        except configobj.ConfigObjError, e:
 
2292
            self._config_obj = None
 
2293
            raise errors.ParseConfigError(e.errors, self.external_url())
 
2294
 
 
2295
    def save(self):
 
2296
        if not self.is_loaded():
 
2297
            # Nothing to save
 
2298
            return
 
2299
        out = StringIO()
 
2300
        self._config_obj.write(out)
 
2301
        self.transport.put_bytes(self.file_name, out.getvalue())
 
2302
 
 
2303
    def external_url(self):
 
2304
        # FIXME: external_url should really accepts an optional relpath
 
2305
        # parameter (bug #750169) :-/ -- vila 2011-04-04
 
2306
        # The following will do in the interim but maybe we don't want to
 
2307
        # expose a path here but rather a config ID and its associated
 
2308
        # object </hand wawe>.
 
2309
        return urlutils.join(self.transport.external_url(), self.file_name)
 
2310
 
 
2311
    def get_sections(self):
 
2312
        """Get the configobj section in the file order.
 
2313
 
 
2314
        :returns: An iterable of (name, dict).
 
2315
        """
 
2316
        # We need a loaded store
 
2317
        try:
 
2318
            self.load()
 
2319
        except errors.NoSuchFile:
 
2320
            # If the file doesn't exist, there is no sections
 
2321
            return
 
2322
        cobj = self._config_obj
 
2323
        if cobj.scalars:
 
2324
            yield self.readonly_section_class(None, cobj)
 
2325
        for section_name in cobj.sections:
 
2326
            yield self.readonly_section_class(section_name, cobj[section_name])
 
2327
 
 
2328
    def get_mutable_section(self, section_name=None):
 
2329
        # We need a loaded store
 
2330
        try:
 
2331
            self.load()
 
2332
        except errors.NoSuchFile:
 
2333
            # The file doesn't exist, let's pretend it was empty
 
2334
            self._load_from_string('')
 
2335
        if section_name is None:
 
2336
            section = self._config_obj
 
2337
        else:
 
2338
            section = self._config_obj.setdefault(section_name, {})
 
2339
        return self.mutable_section_class(section_name, section)
 
2340
 
 
2341
 
 
2342
# Note that LockableConfigObjStore inherits from ConfigObjStore because we need
 
2343
# unlockable stores for use with objects that can already ensure the locking
 
2344
# (think branches). If different stores (not based on ConfigObj) are created,
 
2345
# they may face the same issue.
 
2346
 
 
2347
 
 
2348
class LockableIniFileStore(IniFileStore):
 
2349
    """A ConfigObjStore using locks on save to ensure store integrity."""
 
2350
 
 
2351
    def __init__(self, transport, file_name, lock_dir_name=None):
 
2352
        """A config Store using ConfigObj for storage.
 
2353
 
 
2354
        :param transport: The transport object where the config file is located.
 
2355
 
 
2356
        :param file_name: The config file basename in the transport directory.
 
2357
        """
 
2358
        if lock_dir_name is None:
 
2359
            lock_dir_name = 'lock'
 
2360
        self.lock_dir_name = lock_dir_name
 
2361
        super(LockableIniFileStore, self).__init__(transport, file_name)
 
2362
        self._lock = lockdir.LockDir(self.transport, self.lock_dir_name)
 
2363
 
 
2364
    def lock_write(self, token=None):
 
2365
        """Takes a write lock in the directory containing the config file.
 
2366
 
 
2367
        If the directory doesn't exist it is created.
 
2368
        """
 
2369
        # FIXME: This doesn't check the ownership of the created directories as
 
2370
        # ensure_config_dir_exists does. It should if the transport is local
 
2371
        # -- vila 2011-04-06
 
2372
        self.transport.create_prefix()
 
2373
        return self._lock.lock_write(token)
 
2374
 
 
2375
    def unlock(self):
 
2376
        self._lock.unlock()
 
2377
 
 
2378
    def break_lock(self):
 
2379
        self._lock.break_lock()
 
2380
 
 
2381
    @needs_write_lock
 
2382
    def save(self):
 
2383
        # We need to be able to override the undecorated implementation
 
2384
        self.save_without_locking()
 
2385
 
 
2386
    def save_without_locking(self):
 
2387
        super(LockableIniFileStore, self).save()
 
2388
 
 
2389
 
 
2390
# FIXME: global, bazaar, shouldn't that be 'user' instead or even
 
2391
# 'user_defaults' as opposed to 'user_overrides', 'system_defaults'
 
2392
# (/etc/bzr/bazaar.conf) and 'system_overrides' ? -- vila 2011-04-05
 
2393
 
 
2394
# FIXME: Moreover, we shouldn't need classes for these stores either, factory
 
2395
# functions or a registry will make it easier and clearer for tests, focusing
 
2396
# on the relevant parts of the API that needs testing -- vila 20110503 (based
 
2397
# on a poolie's remark)
 
2398
class GlobalStore(LockableIniFileStore):
 
2399
 
 
2400
    def __init__(self, possible_transports=None):
 
2401
        t = transport.get_transport(config_dir(),
 
2402
                                    possible_transports=possible_transports)
 
2403
        super(GlobalStore, self).__init__(t, 'bazaar.conf')
 
2404
 
 
2405
 
 
2406
class LocationStore(LockableIniFileStore):
 
2407
 
 
2408
    def __init__(self, possible_transports=None):
 
2409
        t = transport.get_transport(config_dir(),
 
2410
                                    possible_transports=possible_transports)
 
2411
        super(LocationStore, self).__init__(t, 'locations.conf')
 
2412
 
 
2413
 
 
2414
class BranchStore(IniFileStore):
 
2415
 
 
2416
    def __init__(self, branch):
 
2417
        super(BranchStore, self).__init__(branch.control_transport,
 
2418
                                          'branch.conf')
 
2419
        self.branch = branch
 
2420
 
 
2421
    def lock_write(self, token=None):
 
2422
        return self.branch.lock_write(token)
 
2423
 
 
2424
    def unlock(self):
 
2425
        return self.branch.unlock()
 
2426
 
 
2427
    @needs_write_lock
 
2428
    def save(self):
 
2429
        # We need to be able to override the undecorated implementation
 
2430
        self.save_without_locking()
 
2431
 
 
2432
    def save_without_locking(self):
 
2433
        super(BranchStore, self).save()
 
2434
 
 
2435
 
 
2436
class SectionMatcher(object):
 
2437
    """Select sections into a given Store.
 
2438
 
 
2439
    This intended to be used to postpone getting an iterable of sections from a
 
2440
    store.
 
2441
    """
 
2442
 
 
2443
    def __init__(self, store):
 
2444
        self.store = store
 
2445
 
 
2446
    def get_sections(self):
 
2447
        # This is where we require loading the store so we can see all defined
 
2448
        # sections.
 
2449
        sections = self.store.get_sections()
 
2450
        # Walk the revisions in the order provided
 
2451
        for s in sections:
 
2452
            if self.match(s):
 
2453
                yield s
 
2454
 
 
2455
    def match(self, secion):
 
2456
        raise NotImplementedError(self.match)
 
2457
 
 
2458
 
 
2459
class LocationSection(Section):
 
2460
 
 
2461
    def __init__(self, section, length, extra_path):
 
2462
        super(LocationSection, self).__init__(section.id, section.options)
 
2463
        self.length = length
 
2464
        self.extra_path = extra_path
 
2465
 
 
2466
    def get(self, name, default=None):
 
2467
        value = super(LocationSection, self).get(name, default)
 
2468
        if value is not None:
 
2469
            policy_name = self.get(name + ':policy', None)
 
2470
            policy = _policy_value.get(policy_name, POLICY_NONE)
 
2471
            if policy == POLICY_APPENDPATH:
 
2472
                value = urlutils.join(value, self.extra_path)
 
2473
        return value
 
2474
 
 
2475
 
 
2476
class LocationMatcher(SectionMatcher):
 
2477
 
 
2478
    def __init__(self, store, location):
 
2479
        super(LocationMatcher, self).__init__(store)
 
2480
        if location.startswith('file://'):
 
2481
            location = urlutils.local_path_from_url(location)
 
2482
        self.location = location
 
2483
 
 
2484
    def _get_matching_sections(self):
 
2485
        """Get all sections matching ``location``."""
 
2486
        # We slightly diverge from LocalConfig here by allowing the no-name
 
2487
        # section as the most generic one and the lower priority.
 
2488
        no_name_section = None
 
2489
        sections = []
 
2490
        # Filter out the no_name_section so _iter_for_location_by_parts can be
 
2491
        # used (it assumes all sections have a name).
 
2492
        for section in self.store.get_sections():
 
2493
            if section.id is None:
 
2494
                no_name_section = section
 
2495
            else:
 
2496
                sections.append(section)
 
2497
        # Unfortunately _iter_for_location_by_parts deals with section names so
 
2498
        # we have to resync.
 
2499
        filtered_sections = _iter_for_location_by_parts(
 
2500
            [s.id for s in sections], self.location)
 
2501
        iter_sections = iter(sections)
 
2502
        matching_sections = []
 
2503
        if no_name_section is not None:
 
2504
            matching_sections.append(
 
2505
                LocationSection(no_name_section, 0, self.location))
 
2506
        for section_id, extra_path, length in filtered_sections:
 
2507
            # a section id is unique for a given store so it's safe to iterate
 
2508
            # again
 
2509
            section = iter_sections.next()
 
2510
            if section_id == section.id:
 
2511
                matching_sections.append(
 
2512
                    LocationSection(section, length, extra_path))
 
2513
        return matching_sections
 
2514
 
 
2515
    def get_sections(self):
 
2516
        # Override the default implementation as we want to change the order
 
2517
        matching_sections = self._get_matching_sections()
 
2518
        # We want the longest (aka more specific) locations first
 
2519
        sections = sorted(matching_sections,
 
2520
                          key=lambda section: (section.length, section.id),
 
2521
                          reverse=True)
 
2522
        # Sections mentioning 'ignore_parents' restrict the selection
 
2523
        for section in sections:
 
2524
            # FIXME: We really want to use as_bool below -- vila 2011-04-07
 
2525
            ignore = section.get('ignore_parents', None)
 
2526
            if ignore is not None:
 
2527
                ignore = ui.bool_from_string(ignore)
 
2528
            if ignore:
 
2529
                break
 
2530
            # Finally, we have a valid section
 
2531
            yield section
 
2532
 
 
2533
 
 
2534
class Stack(object):
 
2535
    """A stack of configurations where an option can be defined"""
 
2536
 
 
2537
    def __init__(self, sections_def, store=None, mutable_section_name=None):
 
2538
        """Creates a stack of sections with an optional store for changes.
 
2539
 
 
2540
        :param sections_def: A list of Section or callables that returns an
 
2541
            iterable of Section. This defines the Sections for the Stack and
 
2542
            can be called repeatedly if needed.
 
2543
 
 
2544
        :param store: The optional Store where modifications will be
 
2545
            recorded. If none is specified, no modifications can be done.
 
2546
 
 
2547
        :param mutable_section_name: The name of the MutableSection where
 
2548
            changes are recorded. This requires the ``store`` parameter to be
 
2549
            specified.
 
2550
        """
 
2551
        self.sections_def = sections_def
 
2552
        self.store = store
 
2553
        self.mutable_section_name = mutable_section_name
 
2554
 
 
2555
    def get(self, name):
 
2556
        """Return the *first* option value found in the sections.
 
2557
 
 
2558
        This is where we guarantee that sections coming from Store are loaded
 
2559
        lazily: the loading is delayed until we need to either check that an
 
2560
        option exists or get its value, which in turn may require to discover
 
2561
        in which sections it can be defined. Both of these (section and option
 
2562
        existence) require loading the store (even partially).
 
2563
        """
 
2564
        # FIXME: No caching of options nor sections yet -- vila 20110503
 
2565
        value = None
 
2566
        # Ensuring lazy loading is achieved by delaying section matching (which
 
2567
        # implies querying the persistent storage) until it can't be avoided
 
2568
        # anymore by using callables to describe (possibly empty) section
 
2569
        # lists.
 
2570
        for section_or_callable in self.sections_def:
 
2571
            # Each section can expand to multiple ones when a callable is used
 
2572
            if callable(section_or_callable):
 
2573
                sections = section_or_callable()
 
2574
            else:
 
2575
                sections = [section_or_callable]
 
2576
            for section in sections:
 
2577
                value = section.get(name)
 
2578
                if value is not None:
 
2579
                    break
 
2580
            if value is not None:
 
2581
                break
 
2582
        if value is None:
 
2583
            # If the option is registered, it may provide a default value
 
2584
            try:
 
2585
                opt = option_registry.get(name)
 
2586
            except KeyError:
 
2587
                # Not registered
 
2588
                opt = None
 
2589
            if opt is not None:
 
2590
                value = opt.get_default()
 
2591
        return value
 
2592
 
 
2593
    def _get_mutable_section(self):
 
2594
        """Get the MutableSection for the Stack.
 
2595
 
 
2596
        This is where we guarantee that the mutable section is lazily loaded:
 
2597
        this means we won't load the corresponding store before setting a value
 
2598
        or deleting an option. In practice the store will often be loaded but
 
2599
        this allows helps catching some programming errors.
 
2600
        """
 
2601
        section = self.store.get_mutable_section(self.mutable_section_name)
 
2602
        return section
 
2603
 
 
2604
    def set(self, name, value):
 
2605
        """Set a new value for the option."""
 
2606
        section = self._get_mutable_section()
 
2607
        section.set(name, value)
 
2608
 
 
2609
    def remove(self, name):
 
2610
        """Remove an existing option."""
 
2611
        section = self._get_mutable_section()
 
2612
        section.remove(name)
 
2613
 
 
2614
    def __repr__(self):
 
2615
        # Mostly for debugging use
 
2616
        return "<config.%s(%s)>" % (self.__class__.__name__, id(self))
 
2617
 
 
2618
 
 
2619
class _CompatibleStack(Stack):
 
2620
    """Place holder for compatibility with previous design.
 
2621
 
 
2622
    This is intended to ease the transition from the Config-based design to the
 
2623
    Stack-based design and should not be used nor relied upon by plugins.
 
2624
 
 
2625
    One assumption made here is that the daughter classes will all use Stores
 
2626
    derived from LockableIniFileStore).
 
2627
 
 
2628
    It implements set() by re-loading the store before applying the
 
2629
    modification and saving it.
 
2630
 
 
2631
    The long term plan being to implement a single write by store to save
 
2632
    all modifications, this class should not be used in the interim.
 
2633
    """
 
2634
 
 
2635
    def set(self, name, value):
 
2636
        # Force a reload
 
2637
        self.store.unload()
 
2638
        super(_CompatibleStack, self).set(name, value)
 
2639
        # Force a write to persistent storage
 
2640
        self.store.save()
 
2641
 
 
2642
 
 
2643
class GlobalStack(_CompatibleStack):
 
2644
 
 
2645
    def __init__(self):
 
2646
        # Get a GlobalStore
 
2647
        gstore = GlobalStore()
 
2648
        super(GlobalStack, self).__init__([gstore.get_sections], gstore)
 
2649
 
 
2650
 
 
2651
class LocationStack(_CompatibleStack):
 
2652
 
 
2653
    def __init__(self, location):
 
2654
        lstore = LocationStore()
 
2655
        matcher = LocationMatcher(lstore, location)
 
2656
        gstore = GlobalStore()
 
2657
        super(LocationStack, self).__init__(
 
2658
            [matcher.get_sections, gstore.get_sections], lstore)
 
2659
 
 
2660
class BranchStack(_CompatibleStack):
 
2661
 
 
2662
    def __init__(self, branch):
 
2663
        bstore = BranchStore(branch)
 
2664
        lstore = LocationStore()
 
2665
        matcher = LocationMatcher(lstore, branch.base)
 
2666
        gstore = GlobalStore()
 
2667
        super(BranchStack, self).__init__(
 
2668
            [matcher.get_sections, bstore.get_sections, gstore.get_sections],
 
2669
            bstore)
 
2670
        self.branch = branch
 
2671
 
 
2672
 
 
2673
class cmd_config(commands.Command):
 
2674
    __doc__ = """Display, set or remove a configuration option.
 
2675
 
 
2676
    Display the active value for a given option.
 
2677
 
 
2678
    If --all is specified, NAME is interpreted as a regular expression and all
 
2679
    matching options are displayed mentioning their scope. The active value
 
2680
    that bzr will take into account is the first one displayed for each option.
 
2681
 
 
2682
    If no NAME is given, --all .* is implied.
 
2683
 
 
2684
    Setting a value is achieved by using name=value without spaces. The value
 
2685
    is set in the most relevant scope and can be checked by displaying the
 
2686
    option again.
 
2687
    """
 
2688
 
 
2689
    takes_args = ['name?']
 
2690
 
 
2691
    takes_options = [
 
2692
        'directory',
 
2693
        # FIXME: This should be a registry option so that plugins can register
 
2694
        # their own config files (or not) -- vila 20101002
 
2695
        commands.Option('scope', help='Reduce the scope to the specified'
 
2696
                        ' configuration file',
 
2697
                        type=unicode),
 
2698
        commands.Option('all',
 
2699
            help='Display all the defined values for the matching options.',
 
2700
            ),
 
2701
        commands.Option('remove', help='Remove the option from'
 
2702
                        ' the configuration file'),
 
2703
        ]
 
2704
 
 
2705
    @commands.display_command
 
2706
    def run(self, name=None, all=False, directory=None, scope=None,
 
2707
            remove=False):
 
2708
        if directory is None:
 
2709
            directory = '.'
 
2710
        directory = urlutils.normalize_url(directory)
 
2711
        if remove and all:
 
2712
            raise errors.BzrError(
 
2713
                '--all and --remove are mutually exclusive.')
 
2714
        elif remove:
 
2715
            # Delete the option in the given scope
 
2716
            self._remove_config_option(name, directory, scope)
 
2717
        elif name is None:
 
2718
            # Defaults to all options
 
2719
            self._show_matching_options('.*', directory, scope)
 
2720
        else:
 
2721
            try:
 
2722
                name, value = name.split('=', 1)
 
2723
            except ValueError:
 
2724
                # Display the option(s) value(s)
 
2725
                if all:
 
2726
                    self._show_matching_options(name, directory, scope)
 
2727
                else:
 
2728
                    self._show_value(name, directory, scope)
 
2729
            else:
 
2730
                if all:
 
2731
                    raise errors.BzrError(
 
2732
                        'Only one option can be set.')
 
2733
                # Set the option value
 
2734
                self._set_config_option(name, value, directory, scope)
 
2735
 
 
2736
    def _get_configs(self, directory, scope=None):
 
2737
        """Iterate the configurations specified by ``directory`` and ``scope``.
 
2738
 
 
2739
        :param directory: Where the configurations are derived from.
 
2740
 
 
2741
        :param scope: A specific config to start from.
 
2742
        """
 
2743
        if scope is not None:
 
2744
            if scope == 'bazaar':
 
2745
                yield GlobalConfig()
 
2746
            elif scope == 'locations':
 
2747
                yield LocationConfig(directory)
 
2748
            elif scope == 'branch':
 
2749
                (_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
 
2750
                    directory)
 
2751
                yield br.get_config()
 
2752
        else:
 
2753
            try:
 
2754
                (_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
 
2755
                    directory)
 
2756
                yield br.get_config()
 
2757
            except errors.NotBranchError:
 
2758
                yield LocationConfig(directory)
 
2759
                yield GlobalConfig()
 
2760
 
 
2761
    def _show_value(self, name, directory, scope):
 
2762
        displayed = False
 
2763
        for c in self._get_configs(directory, scope):
 
2764
            if displayed:
 
2765
                break
 
2766
            for (oname, value, section, conf_id, parser) in c._get_options():
 
2767
                if name == oname:
 
2768
                    # Display only the first value and exit
 
2769
 
 
2770
                    # FIXME: We need to use get_user_option to take policies
 
2771
                    # into account and we need to make sure the option exists
 
2772
                    # too (hence the two for loops), this needs a better API
 
2773
                    # -- vila 20101117
 
2774
                    value = c.get_user_option(name)
 
2775
                    # Quote the value appropriately
 
2776
                    value = parser._quote(value)
 
2777
                    self.outf.write('%s\n' % (value,))
 
2778
                    displayed = True
 
2779
                    break
 
2780
        if not displayed:
 
2781
            raise errors.NoSuchConfigOption(name)
 
2782
 
 
2783
    def _show_matching_options(self, name, directory, scope):
 
2784
        name = lazy_regex.lazy_compile(name)
 
2785
        # We want any error in the regexp to be raised *now* so we need to
 
2786
        # avoid the delay introduced by the lazy regexp.  But, we still do
 
2787
        # want the nicer errors raised by lazy_regex.
 
2788
        name._compile_and_collapse()
 
2789
        cur_conf_id = None
 
2790
        cur_section = None
 
2791
        for c in self._get_configs(directory, scope):
 
2792
            for (oname, value, section, conf_id, parser) in c._get_options():
 
2793
                if name.search(oname):
 
2794
                    if cur_conf_id != conf_id:
 
2795
                        # Explain where the options are defined
 
2796
                        self.outf.write('%s:\n' % (conf_id,))
 
2797
                        cur_conf_id = conf_id
 
2798
                        cur_section = None
 
2799
                    if (section not in (None, 'DEFAULT')
 
2800
                        and cur_section != section):
 
2801
                        # Display the section if it's not the default (or only)
 
2802
                        # one.
 
2803
                        self.outf.write('  [%s]\n' % (section,))
 
2804
                        cur_section = section
 
2805
                    self.outf.write('  %s = %s\n' % (oname, value))
 
2806
 
 
2807
    def _set_config_option(self, name, value, directory, scope):
 
2808
        for conf in self._get_configs(directory, scope):
 
2809
            conf.set_user_option(name, value)
 
2810
            break
 
2811
        else:
 
2812
            raise errors.NoSuchConfig(scope)
 
2813
 
 
2814
    def _remove_config_option(self, name, directory, scope):
 
2815
        if name is None:
 
2816
            raise errors.BzrCommandError(
 
2817
                '--remove expects an option to remove.')
 
2818
        removed = False
 
2819
        for conf in self._get_configs(directory, scope):
 
2820
            for (section_name, section, conf_id) in conf._get_sections():
 
2821
                if scope is not None and conf_id != scope:
 
2822
                    # Not the right configuration file
 
2823
                    continue
 
2824
                if name in section:
 
2825
                    if conf_id != conf.config_id():
 
2826
                        conf = self._get_configs(directory, conf_id).next()
 
2827
                    # We use the first section in the first config where the
 
2828
                    # option is defined to remove it
 
2829
                    conf.remove_user_option(name, section_name)
 
2830
                    removed = True
 
2831
                    break
 
2832
            break
 
2833
        else:
 
2834
            raise errors.NoSuchConfig(scope)
 
2835
        if not removed:
 
2836
            raise errors.NoSuchConfigOption(name)
 
2837
 
 
2838
# Test registries
 
2839
#
 
2840
# We need adapters that can build a Store or a Stack in a test context. Test
 
2841
# classes, based on TestCaseWithTransport, can use the registry to parametrize
 
2842
# themselves. The builder will receive a test instance and should return a
 
2843
# ready-to-use store or stack.  Plugins that define new store/stacks can also
 
2844
# register themselves here to be tested against the tests defined in
 
2845
# bzrlib.tests.test_config. Note that the builder can be called multiple times
 
2846
# for the same tests.
 
2847
 
 
2848
# The registered object should be a callable receiving a test instance
 
2849
# parameter (inheriting from tests.TestCaseWithTransport) and returning a Store
 
2850
# object.
 
2851
test_store_builder_registry = registry.Registry()
 
2852
 
 
2853
# The registered object should be a callable receiving a test instance
 
2854
# parameter (inheriting from tests.TestCaseWithTransport) and returning a Stack
 
2855
# object.
 
2856
test_stack_builder_registry = registry.Registry()