/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: Vincent Ladeuil
  • Date: 2011-05-18 08:47:16 UTC
  • mto: (5743.13.5 config-editor-option)
  • mto: This revision was merged to the branch mainline in revision 5944.
  • Revision ID: v.ladeuil+lp@free.fr-20110518084716-v4n5inw3vnadlqzr
Add documentation.

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