347
def suppress_warning(self, warning):
348
"""Should the warning be suppressed or emitted.
350
:param warning: The name of the warning being tested.
352
:returns: True if the warning should be suppressed, False otherwise.
354
warnings = self.get_user_option_as_list('suppress_warnings')
355
if warnings is None or warning not in warnings:
304
361
class IniBasedConfig(Config):
305
362
"""A configuration policy that draws from ini files."""
307
def _get_parser(self, file=None):
364
def __init__(self, get_filename=symbol_versioning.DEPRECATED_PARAMETER,
366
"""Base class for configuration files using an ini-like syntax.
368
:param file_name: The configuration file path.
370
super(IniBasedConfig, self).__init__()
371
self.file_name = file_name
372
if symbol_versioning.deprecated_passed(get_filename):
373
symbol_versioning.warn(
374
'IniBasedConfig.__init__(get_filename) was deprecated in 2.3.'
375
' Use file_name instead.',
378
if get_filename is not None:
379
self.file_name = get_filename()
381
self.file_name = file_name
386
def from_string(cls, str_or_unicode, file_name=None, save=False):
387
"""Create a config object from a string.
389
:param str_or_unicode: A string representing the file content. This will
392
:param file_name: The configuration file path.
394
:param _save: Whether the file should be saved upon creation.
396
conf = cls(file_name=file_name)
397
conf._create_from_string(str_or_unicode, save)
400
def _create_from_string(self, str_or_unicode, save):
401
self._content = StringIO(str_or_unicode.encode('utf-8'))
402
# Some tests use in-memory configs, some other always need the config
403
# file to exist on disk.
405
self._write_config_file()
407
def _get_parser(self, file=symbol_versioning.DEPRECATED_PARAMETER):
308
408
if self._parser is not None:
309
409
return self._parser
311
input = self._get_filename()
410
if symbol_versioning.deprecated_passed(file):
411
symbol_versioning.warn(
412
'IniBasedConfig._get_parser(file=xxx) was deprecated in 2.3.'
413
' Use IniBasedConfig(_content=xxx) instead.',
416
if self._content is not None:
417
co_input = self._content
418
elif self.file_name is None:
419
raise AssertionError('We have no content to create the config')
421
co_input = self.file_name
315
self._parser = ConfigObj(input, encoding='utf-8')
423
self._parser = ConfigObj(co_input, encoding='utf-8')
316
424
except configobj.ConfigObjError, e:
317
425
raise errors.ParseConfigError(e.errors, e.config.filename)
426
# Make sure self.reload() will use the right file name
427
self._parser.filename = self.file_name
318
428
return self._parser
431
"""Reload the config file from disk."""
432
if self.file_name is None:
433
raise AssertionError('We need a file name to reload the config')
434
if self._parser is not None:
435
self._parser.reload()
320
437
def _get_matching_sections(self):
321
438
"""Return an ordered list of (section_name, extra_path) pairs.
427
591
def _get_nickname(self):
428
592
return self.get_user_option('nickname')
431
class GlobalConfig(IniBasedConfig):
594
def remove_user_option(self, option_name, section_name=None):
595
"""Remove a user option and save the configuration file.
597
:param option_name: The option to be removed.
599
:param section_name: The section the option is defined in, default to
603
parser = self._get_parser()
604
if section_name is None:
607
section = parser[section_name]
609
del section[option_name]
611
raise errors.NoSuchConfigOption(option_name)
612
self._write_config_file()
614
def _write_config_file(self):
615
if self.file_name is None:
616
raise AssertionError('We cannot save, self.file_name is None')
617
conf_dir = os.path.dirname(self.file_name)
618
ensure_config_dir_exists(conf_dir)
619
atomic_file = atomicfile.AtomicFile(self.file_name)
620
self._get_parser().write(atomic_file)
623
osutils.copy_ownership_from_path(self.file_name)
626
class LockableConfig(IniBasedConfig):
627
"""A configuration needing explicit locking for access.
629
If several processes try to write the config file, the accesses need to be
632
Daughter classes should decorate all methods that update a config with the
633
``@needs_write_lock`` decorator (they call, directly or indirectly, the
634
``_write_config_file()`` method. These methods (typically ``set_option()``
635
and variants must reload the config file from disk before calling
636
``_write_config_file()``), this can be achieved by calling the
637
``self.reload()`` method. Note that the lock scope should cover both the
638
reading and the writing of the config file which is why the decorator can't
639
be applied to ``_write_config_file()`` only.
641
This should be enough to implement the following logic:
642
- lock for exclusive write access,
643
- reload the config file from disk,
647
This logic guarantees that a writer can update a value without erasing an
648
update made by another writer.
653
def __init__(self, file_name):
654
super(LockableConfig, self).__init__(file_name=file_name)
655
self.dir = osutils.dirname(osutils.safe_unicode(self.file_name))
656
self.transport = transport.get_transport(self.dir)
657
self._lock = lockdir.LockDir(self.transport, 'lock')
659
def _create_from_string(self, unicode_bytes, save):
660
super(LockableConfig, self)._create_from_string(unicode_bytes, False)
662
# We need to handle the saving here (as opposed to IniBasedConfig)
665
self._write_config_file()
668
def lock_write(self, token=None):
669
"""Takes a write lock in the directory containing the config file.
671
If the directory doesn't exist it is created.
673
ensure_config_dir_exists(self.dir)
674
return self._lock.lock_write(token)
679
def break_lock(self):
680
self._lock.break_lock()
683
def remove_user_option(self, option_name, section_name=None):
684
super(LockableConfig, self).remove_user_option(option_name,
687
def _write_config_file(self):
688
if self._lock is None or not self._lock.is_held:
689
# NB: if the following exception is raised it probably means a
690
# missing @needs_write_lock decorator on one of the callers.
691
raise errors.ObjectNotLocked(self)
692
super(LockableConfig, self)._write_config_file()
695
class GlobalConfig(LockableConfig):
432
696
"""The configuration that should be used for a specific location."""
699
super(GlobalConfig, self).__init__(file_name=config_filename())
705
def from_string(cls, str_or_unicode, save=False):
706
"""Create a config object from a string.
708
:param str_or_unicode: A string representing the file content. This
709
will be utf-8 encoded.
711
:param save: Whether the file should be saved upon creation.
714
conf._create_from_string(str_or_unicode, save)
434
717
def get_editor(self):
435
718
return self._get_user_option('editor')
438
super(GlobalConfig, self).__init__(config_filename)
440
721
def set_user_option(self, option, value):
441
722
"""Save option and its value in the configuration."""
442
# FIXME: RBC 20051029 This should refresh the parser and also take a
443
# file lock on bazaar.conf.
444
conf_dir = os.path.dirname(self._get_filename())
445
ensure_config_dir_exists(conf_dir)
446
if 'DEFAULT' not in self._get_parser():
447
self._get_parser()['DEFAULT'] = {}
448
self._get_parser()['DEFAULT'][option] = value
449
f = open(self._get_filename(), 'wb')
450
self._get_parser().write(f)
454
class LocationConfig(IniBasedConfig):
723
self._set_option(option, value, 'DEFAULT')
725
def get_aliases(self):
726
"""Return the aliases section."""
727
if 'ALIASES' in self._get_parser():
728
return self._get_parser()['ALIASES']
733
def set_alias(self, alias_name, alias_command):
734
"""Save the alias in the configuration."""
735
self._set_option(alias_name, alias_command, 'ALIASES')
738
def unset_alias(self, alias_name):
739
"""Unset an existing alias."""
741
aliases = self._get_parser().get('ALIASES')
742
if not aliases or alias_name not in aliases:
743
raise errors.NoSuchAlias(alias_name)
744
del aliases[alias_name]
745
self._write_config_file()
747
def _set_option(self, option, value, section):
749
self._get_parser().setdefault(section, {})[option] = value
750
self._write_config_file()
753
def _get_sections(self, name=None):
754
"""See IniBasedConfig._get_sections()."""
755
parser = self._get_parser()
756
# We don't give access to options defined outside of any section, we
757
# used the DEFAULT section by... default.
758
if name in (None, 'DEFAULT'):
759
# This could happen for an empty file where the DEFAULT section
760
# doesn't exist yet. So we force DEFAULT when yielding
762
if 'DEFAULT' not in parser:
763
parser['DEFAULT']= {}
764
yield (name, parser[name], self.config_id())
767
def remove_user_option(self, option_name, section_name=None):
768
if section_name is None:
769
# We need to force the default section.
770
section_name = 'DEFAULT'
771
# We need to avoid the LockableConfig implementation or we'll lock
773
super(LockableConfig, self).remove_user_option(option_name,
777
class LocationConfig(LockableConfig):
455
778
"""A configuration object that gives the policy for a location."""
457
780
def __init__(self, location):
458
name_generator = locations_config_filename
459
if (not os.path.exists(name_generator()) and
460
os.path.exists(branches_config_filename())):
461
if sys.platform == 'win32':
462
trace.warning('Please rename %s to %s'
463
% (branches_config_filename(),
464
locations_config_filename()))
466
trace.warning('Please rename ~/.bazaar/branches.conf'
467
' to ~/.bazaar/locations.conf')
468
name_generator = branches_config_filename
469
super(LocationConfig, self).__init__(name_generator)
781
super(LocationConfig, self).__init__(
782
file_name=locations_config_filename())
470
783
# local file locations are looked up by local path, rather than
471
784
# by file url. This is because the config file is a user
472
785
# file, and we would rather not expose the user to file urls.
794
1180
return osutils.pathjoin(config_dir(), 'ignore')
798
"""Calculate automatic user identification.
800
Returns (realname, email).
802
Only used when none is set in the environment or the id file.
804
This previously used the FQDN as the default domain, but that can
805
be very slow on machines where DNS is broken. So now we simply
1184
"""Return the directory name to store crash files.
1186
This doesn't implicitly create it.
1188
On Windows it's in the config directory; elsewhere it's /var/crash
1189
which may be monitored by apport. It can be overridden by
810
1192
if sys.platform == 'win32':
811
name = win32utils.get_user_name_unicode()
813
raise errors.BzrError("Cannot autodetect user name.\n"
814
"Please, set your name with command like:\n"
815
'bzr whoami "Your Name <name@domain.com>"')
816
host = win32utils.get_host_name_unicode()
818
host = socket.gethostname()
819
return name, (name + '@' + host)
824
w = pwd.getpwuid(uid)
826
# we try utf-8 first, because on many variants (like Linux),
827
# /etc/passwd "should" be in utf-8, and because it's unlikely to give
828
# false positives. (many users will have their user encoding set to
829
# latin-1, which cannot raise UnicodeError.)
831
gecos = w.pw_gecos.decode('utf-8')
835
gecos = w.pw_gecos.decode(bzrlib.user_encoding)
836
encoding = bzrlib.user_encoding
838
raise errors.BzrCommandError('Unable to determine your name. '
839
'Use "bzr whoami" to set it.')
841
username = w.pw_name.decode(encoding)
843
raise errors.BzrCommandError('Unable to determine your name. '
844
'Use "bzr whoami" to set it.')
846
comma = gecos.find(',')
850
realname = gecos[:comma]
857
realname = username = getpass.getuser().decode(bzrlib.user_encoding)
858
except UnicodeDecodeError:
859
raise errors.BzrError("Can't decode username as %s." % \
860
bzrlib.user_encoding)
862
return realname, (username + '@' + socket.gethostname())
1193
return osutils.pathjoin(config_dir(), 'Crash')
1195
# XXX: hardcoded in apport_python_hook.py; therefore here too -- mbp
1197
return os.environ.get('APPORT_CRASH_DIR', '/var/crash')
1200
def xdg_cache_dir():
1201
# See http://standards.freedesktop.org/basedir-spec/latest/ar01s03.html
1202
# Possibly this should be different on Windows?
1203
e = os.environ.get('XDG_CACHE_DIR', None)
1207
return os.path.expanduser('~/.cache')
1210
def parse_username(username):
1211
"""Parse e-mail username and return a (name, address) tuple."""
1212
match = re.match(r'(.*?)\s*<?([\w+.-]+@[\w+.-]+)>?', username)
1214
return (username, '')
1216
return (match.group(1), match.group(2))
865
1219
def extract_email_address(e):
866
1220
"""Return just the address part of an email string.
868
That is just the user@domain part, nothing else.
1222
That is just the user@domain part, nothing else.
869
1223
This part is required to contain only ascii characters.
870
1224
If it can't be extracted, raises an error.
872
1226
>>> extract_email_address('Jane Tester <jane@test.com>')
875
m = re.search(r'[\w+.-]+@[\w+.-]+', e)
1229
name, email = parse_username(e)
877
1231
raise errors.NoEmailInUsername(e)
881
1235
class TreeConfig(IniBasedConfig):
882
1236
"""Branch configuration data associated with its contents, not location"""
1238
# XXX: Really needs a better name, as this is not part of the tree! -- mbp 20080507
884
1240
def __init__(self, branch):
1241
self._config = branch._get_config()
885
1242
self.branch = branch
887
1244
def _get_parser(self, file=None):
888
1245
if file is not None:
889
1246
return IniBasedConfig._get_parser(file)
890
return self._get_config()
892
def _get_config(self):
894
obj = ConfigObj(self.branch.control_files.get('branch.conf'),
896
except errors.NoSuchFile:
897
obj = ConfigObj(encoding='utf=8')
1247
return self._config._get_configobj()
900
1249
def get_option(self, name, section=None, default=None):
901
1250
self.branch.lock_read()
903
obj = self._get_config()
905
if section is not None:
1252
return self._config.get_option(name, section, default)
911
1254
self.branch.unlock()
914
1256
def set_option(self, value, name, section=None):
915
1257
"""Set a per-branch configuration option"""
916
self.branch.lock_write()
918
cfg_obj = self._get_config()
923
obj = cfg_obj[section]
925
cfg_obj[section] = {}
926
obj = cfg_obj[section]
928
out_file = StringIO()
929
cfg_obj.write(out_file)
931
self.branch.control_files.put('branch.conf', out_file)
1258
# FIXME: We shouldn't need to lock explicitly here but rather rely on
1259
# higher levels providing the right lock -- vila 20101004
1260
self.branch.lock_write()
1262
self._config.set_option(value, name, section)
1264
self.branch.unlock()
1266
def remove_option(self, option_name, section_name=None):
1267
# FIXME: We shouldn't need to lock explicitly here but rather rely on
1268
# higher levels providing the right lock -- vila 20101004
1269
self.branch.lock_write()
1271
self._config.remove_option(option_name, section_name)
933
1273
self.branch.unlock()
1042
1397
if a_user is None:
1043
1398
# Can't find a user
1400
# Prepare a credentials dictionary with additional keys
1401
# for the credential providers
1045
1402
credentials = dict(name=auth_def_name,
1046
user=a_user, password=auth_def['password'],
1409
password=auth_def.get('password', None),
1047
1410
verify_certificates=a_verify_certificates)
1411
# Decode the password in the credentials (or get one)
1048
1412
self.decode_password(credentials,
1049
1413
auth_def.get('password_encoding', None))
1050
1414
if 'auth' in debug.debug_flags:
1051
1415
trace.mutter("Using authentication section: %r", auth_def_name)
1418
if credentials is None:
1419
# No credentials were found in authentication.conf, try the fallback
1420
# credentials stores.
1421
credentials = credential_store_registry.get_fallback_credentials(
1422
scheme, host, port, user, path, realm)
1054
1424
return credentials
1056
def get_user(self, scheme, host, port=None,
1057
realm=None, path=None, prompt=None):
1426
def set_credentials(self, name, host, user, scheme=None, password=None,
1427
port=None, path=None, verify_certificates=None,
1429
"""Set authentication credentials for a host.
1431
Any existing credentials with matching scheme, host, port and path
1432
will be deleted, regardless of name.
1434
:param name: An arbitrary name to describe this set of credentials.
1435
:param host: Name of the host that accepts these credentials.
1436
:param user: The username portion of these credentials.
1437
:param scheme: The URL scheme (e.g. ssh, http) the credentials apply
1439
:param password: Password portion of these credentials.
1440
:param port: The IP port on the host that these credentials apply to.
1441
:param path: A filesystem path on the host that these credentials
1443
:param verify_certificates: On https, verify server certificates if
1445
:param realm: The http authentication realm (optional).
1447
values = {'host': host, 'user': user}
1448
if password is not None:
1449
values['password'] = password
1450
if scheme is not None:
1451
values['scheme'] = scheme
1452
if port is not None:
1453
values['port'] = '%d' % port
1454
if path is not None:
1455
values['path'] = path
1456
if verify_certificates is not None:
1457
values['verify_certificates'] = str(verify_certificates)
1458
if realm is not None:
1459
values['realm'] = realm
1460
config = self._get_config()
1462
for section, existing_values in config.items():
1463
for key in ('scheme', 'host', 'port', 'path', 'realm'):
1464
if existing_values.get(key) != values.get(key):
1468
config.update({name: values})
1471
def get_user(self, scheme, host, port=None, realm=None, path=None,
1472
prompt=None, ask=False, default=None):
1058
1473
"""Get a user from authentication file.
1060
1475
:param scheme: protocol
1115
1554
return password
1117
1556
def decode_password(self, credentials, encoding):
1558
cs = credential_store_registry.get_credential_store(encoding)
1560
raise ValueError('%r is not a known password_encoding' % encoding)
1561
credentials['password'] = cs.decode_password(credentials)
1565
class CredentialStoreRegistry(registry.Registry):
1566
"""A class that registers credential stores.
1568
A credential store provides access to credentials via the password_encoding
1569
field in authentication.conf sections.
1571
Except for stores provided by bzr itself, most stores are expected to be
1572
provided by plugins that will therefore use
1573
register_lazy(password_encoding, module_name, member_name, help=help,
1574
fallback=fallback) to install themselves.
1576
A fallback credential store is one that is queried if no credentials can be
1577
found via authentication.conf.
1580
def get_credential_store(self, encoding=None):
1581
cs = self.get(encoding)
1586
def is_fallback(self, name):
1587
"""Check if the named credentials store should be used as fallback."""
1588
return self.get_info(name)
1590
def get_fallback_credentials(self, scheme, host, port=None, user=None,
1591
path=None, realm=None):
1592
"""Request credentials from all fallback credentials stores.
1594
The first credentials store that can provide credentials wins.
1597
for name in self.keys():
1598
if not self.is_fallback(name):
1600
cs = self.get_credential_store(name)
1601
credentials = cs.get_credentials(scheme, host, port, user,
1603
if credentials is not None:
1604
# We found some credentials
1608
def register(self, key, obj, help=None, override_existing=False,
1610
"""Register a new object to a name.
1612
:param key: This is the key to use to request the object later.
1613
:param obj: The object to register.
1614
:param help: Help text for this entry. This may be a string or
1615
a callable. If it is a callable, it should take two
1616
parameters (registry, key): this registry and the key that
1617
the help was registered under.
1618
:param override_existing: Raise KeyErorr if False and something has
1619
already been registered for that key. If True, ignore if there
1620
is an existing key (always register the new value).
1621
:param fallback: Whether this credential store should be
1624
return super(CredentialStoreRegistry,
1625
self).register(key, obj, help, info=fallback,
1626
override_existing=override_existing)
1628
def register_lazy(self, key, module_name, member_name,
1629
help=None, override_existing=False,
1631
"""Register a new credential store to be loaded on request.
1633
:param module_name: The python path to the module. Such as 'os.path'.
1634
:param member_name: The member of the module to return. If empty or
1635
None, get() will return the module itself.
1636
:param help: Help text for this entry. This may be a string or
1638
:param override_existing: If True, replace the existing object
1639
with the new one. If False, if there is already something
1640
registered with the same key, raise a KeyError
1641
:param fallback: Whether this credential store should be
1644
return super(CredentialStoreRegistry, self).register_lazy(
1645
key, module_name, member_name, help,
1646
info=fallback, override_existing=override_existing)
1649
credential_store_registry = CredentialStoreRegistry()
1652
class CredentialStore(object):
1653
"""An abstract class to implement storage for credentials"""
1655
def decode_password(self, credentials):
1656
"""Returns a clear text password for the provided credentials."""
1657
raise NotImplementedError(self.decode_password)
1659
def get_credentials(self, scheme, host, port=None, user=None, path=None,
1661
"""Return the matching credentials from this credential store.
1663
This method is only called on fallback credential stores.
1665
raise NotImplementedError(self.get_credentials)
1669
class PlainTextCredentialStore(CredentialStore):
1670
__doc__ = """Plain text credential store for the authentication.conf file"""
1672
def decode_password(self, credentials):
1673
"""See CredentialStore.decode_password."""
1674
return credentials['password']
1677
credential_store_registry.register('plain', PlainTextCredentialStore,
1678
help=PlainTextCredentialStore.__doc__)
1679
credential_store_registry.default_key = 'plain'
1682
class BzrDirConfig(object):
1684
def __init__(self, bzrdir):
1685
self._bzrdir = bzrdir
1686
self._config = bzrdir._get_config()
1688
def set_default_stack_on(self, value):
1689
"""Set the default stacking location.
1691
It may be set to a location, or None.
1693
This policy affects all branches contained by this bzrdir, except for
1694
those under repositories.
1696
if self._config is None:
1697
raise errors.BzrError("Cannot set configuration in %s" % self._bzrdir)
1699
self._config.set_option('', 'default_stack_on')
1701
self._config.set_option(value, 'default_stack_on')
1703
def get_default_stack_on(self):
1704
"""Return the default stacking location.
1706
This will either be a location, or None.
1708
This policy affects all branches contained by this bzrdir, except for
1709
those under repositories.
1711
if self._config is None:
1713
value = self._config.get_option('default_stack_on')
1719
class TransportConfig(object):
1720
"""A Config that reads/writes a config file on a Transport.
1722
It is a low-level object that considers config data to be name/value pairs
1723
that may be associated with a section. Assigning meaning to these values
1724
is done at higher levels like TreeConfig.
1727
def __init__(self, transport, filename):
1728
self._transport = transport
1729
self._filename = filename
1731
def get_option(self, name, section=None, default=None):
1732
"""Return the value associated with a named option.
1734
:param name: The name of the value
1735
:param section: The section the option is in (if any)
1736
:param default: The value to return if the value is not set
1737
:return: The value or default value
1739
configobj = self._get_configobj()
1741
section_obj = configobj
1744
section_obj = configobj[section]
1747
return section_obj.get(name, default)
1749
def set_option(self, value, name, section=None):
1750
"""Set the value associated with a named option.
1752
:param value: The value to set
1753
:param name: The name of the value to set
1754
:param section: The section the option is in (if any)
1756
configobj = self._get_configobj()
1758
configobj[name] = value
1760
configobj.setdefault(section, {})[name] = value
1761
self._set_configobj(configobj)
1763
def remove_option(self, option_name, section_name=None):
1764
configobj = self._get_configobj()
1765
if section_name is None:
1766
del configobj[option_name]
1768
del configobj[section_name][option_name]
1769
self._set_configobj(configobj)
1771
def _get_config_file(self):
1773
return StringIO(self._transport.get_bytes(self._filename))
1774
except errors.NoSuchFile:
1777
def _get_configobj(self):
1778
f = self._get_config_file()
1780
return ConfigObj(f, encoding='utf-8')
1784
def _set_configobj(self, configobj):
1785
out_file = StringIO()
1786
configobj.write(out_file)
1788
self._transport.put_file(self._filename, out_file)
1791
class cmd_config(commands.Command):
1792
__doc__ = """Display, set or remove a configuration option.
1794
Display the active value for a given option.
1796
If --all is specified, NAME is interpreted as a regular expression and all
1797
matching options are displayed mentioning their scope. The active value
1798
that bzr will take into account is the first one displayed for each option.
1800
If no NAME is given, --all .* is implied.
1802
Setting a value is achieved by using name=value without spaces. The value
1803
is set in the most relevant scope and can be checked by displaying the
1807
takes_args = ['name?']
1811
# FIXME: This should be a registry option so that plugins can register
1812
# their own config files (or not) -- vila 20101002
1813
commands.Option('scope', help='Reduce the scope to the specified'
1814
' configuration file',
1816
commands.Option('all',
1817
help='Display all the defined values for the matching options.',
1819
commands.Option('remove', help='Remove the option from'
1820
' the configuration file'),
1823
@commands.display_command
1824
def run(self, name=None, all=False, directory=None, scope=None,
1826
if directory is None:
1828
directory = urlutils.normalize_url(directory)
1830
raise errors.BzrError(
1831
'--all and --remove are mutually exclusive.')
1833
# Delete the option in the given scope
1834
self._remove_config_option(name, directory, scope)
1836
# Defaults to all options
1837
self._show_matching_options('.*', directory, scope)
1840
name, value = name.split('=', 1)
1842
# Display the option(s) value(s)
1844
self._show_matching_options(name, directory, scope)
1846
self._show_value(name, directory, scope)
1849
raise errors.BzrError(
1850
'Only one option can be set.')
1851
# Set the option value
1852
self._set_config_option(name, value, directory, scope)
1854
def _get_configs(self, directory, scope=None):
1855
"""Iterate the configurations specified by ``directory`` and ``scope``.
1857
:param directory: Where the configurations are derived from.
1859
:param scope: A specific config to start from.
1861
if scope is not None:
1862
if scope == 'bazaar':
1863
yield GlobalConfig()
1864
elif scope == 'locations':
1865
yield LocationConfig(directory)
1866
elif scope == 'branch':
1867
(_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
1869
yield br.get_config()
1872
(_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
1874
yield br.get_config()
1875
except errors.NotBranchError:
1876
yield LocationConfig(directory)
1877
yield GlobalConfig()
1879
def _show_value(self, name, directory, scope):
1881
for c in self._get_configs(directory, scope):
1884
for (oname, value, section, conf_id, parser) in c._get_options():
1886
# Display only the first value and exit
1888
# FIXME: We need to use get_user_option to take policies
1889
# into account and we need to make sure the option exists
1890
# too (hence the two for loops), this needs a better API
1892
value = c.get_user_option(name)
1893
# Quote the value appropriately
1894
value = parser._quote(value)
1895
self.outf.write('%s\n' % (value,))
1899
raise errors.NoSuchConfigOption(name)
1901
def _show_matching_options(self, name, directory, scope):
1902
name = re.compile(name)
1903
# We want any error in the regexp to be raised *now* so we need to
1904
# avoid the delay introduced by the lazy regexp.
1905
name._compile_and_collapse()
1908
for c in self._get_configs(directory, scope):
1909
for (oname, value, section, conf_id, parser) in c._get_options():
1910
if name.search(oname):
1911
if cur_conf_id != conf_id:
1912
# Explain where the options are defined
1913
self.outf.write('%s:\n' % (conf_id,))
1914
cur_conf_id = conf_id
1916
if (section not in (None, 'DEFAULT')
1917
and cur_section != section):
1918
# Display the section if it's not the default (or only)
1920
self.outf.write(' [%s]\n' % (section,))
1921
cur_section = section
1922
self.outf.write(' %s = %s\n' % (oname, value))
1924
def _set_config_option(self, name, value, directory, scope):
1925
for conf in self._get_configs(directory, scope):
1926
conf.set_user_option(name, value)
1929
raise errors.NoSuchConfig(scope)
1931
def _remove_config_option(self, name, directory, scope):
1933
raise errors.BzrCommandError(
1934
'--remove expects an option to remove.')
1936
for conf in self._get_configs(directory, scope):
1937
for (section_name, section, conf_id) in conf._get_sections():
1938
if scope is not None and conf_id != scope:
1939
# Not the right configuration file
1942
if conf_id != conf.config_id():
1943
conf = self._get_configs(directory, conf_id).next()
1944
# We use the first section in the first config where the
1945
# option is defined to remove it
1946
conf.remove_user_option(name, section_name)
1951
raise errors.NoSuchConfig(scope)
1953
raise errors.NoSuchConfigOption(name)