127
def ConfigObj(*args, **kwargs):
129
if _ConfigObj is None:
130
class ConfigObj(configobj.ConfigObj):
132
def get_bool(self, section, key):
133
return self[section].as_bool(key)
135
def get_value(self, section, name):
136
# Try [] for the old DEFAULT section.
137
if section == "DEFAULT":
142
return self[section][name]
143
_ConfigObj = ConfigObj
144
return _ConfigObj(*args, **kwargs)
125
class ConfigObj(configobj.ConfigObj):
127
def get_bool(self, section, key):
128
return self[section].as_bool(key)
130
def get_value(self, section, name):
131
# Try [] for the old DEFAULT section.
132
if section == "DEFAULT":
137
return self[section][name]
147
140
class Config(object):
148
141
"""A configuration policy - what username, editor, gpg needs etc."""
151
super(Config, self).__init__()
153
143
def get_editor(self):
154
144
"""Get the users pop up editor."""
155
145
raise NotImplementedError
157
def get_change_editor(self, old_tree, new_tree):
158
from bzrlib import diff
159
cmd = self._get_change_editor()
162
return diff.DiffFromTool.from_string(cmd, old_tree, new_tree,
166
147
def get_mail_client(self):
167
148
"""Get a mail client to use"""
168
149
selected_client = self.get_user_option('mail_client')
169
_registry = mail_client.mail_client_registry
171
mail_client_class = _registry.get(selected_client)
151
mail_client_class = {
152
None: mail_client.DefaultMail,
154
'emacsclient': mail_client.EmacsMail,
155
'evolution': mail_client.Evolution,
156
'kmail': mail_client.KMail,
157
'mutt': mail_client.Mutt,
158
'thunderbird': mail_client.Thunderbird,
160
'default': mail_client.DefaultMail,
161
'editor': mail_client.Editor,
162
'mapi': mail_client.MAPIClient,
163
'xdg-email': mail_client.XDGEmail,
173
166
raise errors.UnknownMailClient(selected_client)
174
167
return mail_client_class(self)
187
180
"""Get a generic option - no special process, no default."""
188
181
return self._get_user_option(option_name)
190
def get_user_option_as_bool(self, option_name):
191
"""Get a generic option as a boolean - no special process, no default.
193
:return None if the option doesn't exist or its value can't be
194
interpreted as a boolean. Returns True or False otherwise.
196
s = self._get_user_option(option_name)
198
# The option doesn't exist
200
val = ui.bool_from_string(s)
202
# The value can't be interpreted as a boolean
203
trace.warning('Value "%s" is not a boolean for "%s"',
207
def get_user_option_as_list(self, option_name):
208
"""Get a generic option as a list - no special process, no default.
210
:return None if the option doesn't exist. Returns the value as a list
213
l = self._get_user_option(option_name)
214
if isinstance(l, (str, unicode)):
215
# A single value, most probably the user forgot the final ','
219
183
def gpg_signing_command(self):
220
184
"""What program should be used to sign signatures?"""
221
185
result = self._gpg_signing_command()
497
441
def set_user_option(self, option, value):
498
442
"""Save option and its value in the configuration."""
499
self._set_option(option, value, 'DEFAULT')
501
def get_aliases(self):
502
"""Return the aliases section."""
503
if 'ALIASES' in self._get_parser():
504
return self._get_parser()['ALIASES']
508
def set_alias(self, alias_name, alias_command):
509
"""Save the alias in the configuration."""
510
self._set_option(alias_name, alias_command, 'ALIASES')
512
def unset_alias(self, alias_name):
513
"""Unset an existing alias."""
514
aliases = self._get_parser().get('ALIASES')
515
if not aliases or alias_name not in aliases:
516
raise errors.NoSuchAlias(alias_name)
517
del aliases[alias_name]
518
self._write_config_file()
520
def _set_option(self, option, value, section):
521
443
# FIXME: RBC 20051029 This should refresh the parser and also take a
522
444
# file lock on bazaar.conf.
523
445
conf_dir = os.path.dirname(self._get_filename())
524
446
ensure_config_dir_exists(conf_dir)
525
self._get_parser().setdefault(section, {})[option] = value
526
self._write_config_file()
447
if 'DEFAULT' not in self._get_parser():
448
self._get_parser()['DEFAULT'] = {}
449
self._get_parser()['DEFAULT'][option] = value
450
f = open(self._get_filename(), 'wb')
451
self._get_parser().write(f)
529
455
class LocationConfig(IniBasedConfig):
872
794
return osutils.pathjoin(config_dir(), 'ignore')
876
"""Return the directory name to store crash files.
878
This doesn't implicitly create it.
880
On Windows it's in the config directory; elsewhere it's /var/crash
881
which may be monitored by apport. It can be overridden by
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
884
810
if sys.platform == 'win32':
885
return osutils.pathjoin(config_dir(), 'Crash')
887
# XXX: hardcoded in apport_python_hook.py; therefore here too -- mbp
889
return os.environ.get('APPORT_CRASH_DIR', '/var/crash')
893
# See http://standards.freedesktop.org/basedir-spec/latest/ar01s03.html
894
# Possibly this should be different on Windows?
895
e = os.environ.get('XDG_CACHE_DIR', None)
899
return os.path.expanduser('~/.cache')
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())
902
865
def parse_username(username):
1078
1026
if a_user is None:
1079
1027
# Can't find a user
1081
# Prepare a credentials dictionary with additional keys
1082
# for the credential providers
1083
1029
credentials = dict(name=auth_def_name,
1090
password=auth_def.get('password', None),
1030
user=a_user, password=auth_def['password'],
1091
1031
verify_certificates=a_verify_certificates)
1092
# Decode the password in the credentials (or get one)
1093
1032
self.decode_password(credentials,
1094
1033
auth_def.get('password_encoding', None))
1095
1034
if 'auth' in debug.debug_flags:
1096
1035
trace.mutter("Using authentication section: %r", auth_def_name)
1099
if credentials is None:
1100
# No credentials were found in authentication.conf, try the fallback
1101
# credentials stores.
1102
credentials = credential_store_registry.get_fallback_credentials(
1103
scheme, host, port, user, path, realm)
1105
1038
return credentials
1107
def set_credentials(self, name, host, user, scheme=None, password=None,
1108
port=None, path=None, verify_certificates=None,
1110
"""Set authentication credentials for a host.
1112
Any existing credentials with matching scheme, host, port and path
1113
will be deleted, regardless of name.
1115
:param name: An arbitrary name to describe this set of credentials.
1116
:param host: Name of the host that accepts these credentials.
1117
:param user: The username portion of these credentials.
1118
:param scheme: The URL scheme (e.g. ssh, http) the credentials apply
1120
:param password: Password portion of these credentials.
1121
:param port: The IP port on the host that these credentials apply to.
1122
:param path: A filesystem path on the host that these credentials
1124
:param verify_certificates: On https, verify server certificates if
1126
:param realm: The http authentication realm (optional).
1128
values = {'host': host, 'user': user}
1129
if password is not None:
1130
values['password'] = password
1131
if scheme is not None:
1132
values['scheme'] = scheme
1133
if port is not None:
1134
values['port'] = '%d' % port
1135
if path is not None:
1136
values['path'] = path
1137
if verify_certificates is not None:
1138
values['verify_certificates'] = str(verify_certificates)
1139
if realm is not None:
1140
values['realm'] = realm
1141
config = self._get_config()
1143
for section, existing_values in config.items():
1144
for key in ('scheme', 'host', 'port', 'path', 'realm'):
1145
if existing_values.get(key) != values.get(key):
1149
config.update({name: values})
1152
def get_user(self, scheme, host, port=None, realm=None, path=None,
1153
prompt=None, ask=False, default=None):
1040
def get_user(self, scheme, host, port=None,
1041
realm=None, path=None, prompt=None):
1154
1042
"""Get a user from authentication file.
1156
1044
:param scheme: protocol
1235
1099
return password
1237
1101
def decode_password(self, credentials, encoding):
1239
cs = credential_store_registry.get_credential_store(encoding)
1241
raise ValueError('%r is not a known password_encoding' % encoding)
1242
credentials['password'] = cs.decode_password(credentials)
1246
class CredentialStoreRegistry(registry.Registry):
1247
"""A class that registers credential stores.
1249
A credential store provides access to credentials via the password_encoding
1250
field in authentication.conf sections.
1252
Except for stores provided by bzr itself, most stores are expected to be
1253
provided by plugins that will therefore use
1254
register_lazy(password_encoding, module_name, member_name, help=help,
1255
fallback=fallback) to install themselves.
1257
A fallback credential store is one that is queried if no credentials can be
1258
found via authentication.conf.
1261
def get_credential_store(self, encoding=None):
1262
cs = self.get(encoding)
1267
def is_fallback(self, name):
1268
"""Check if the named credentials store should be used as fallback."""
1269
return self.get_info(name)
1271
def get_fallback_credentials(self, scheme, host, port=None, user=None,
1272
path=None, realm=None):
1273
"""Request credentials from all fallback credentials stores.
1275
The first credentials store that can provide credentials wins.
1278
for name in self.keys():
1279
if not self.is_fallback(name):
1281
cs = self.get_credential_store(name)
1282
credentials = cs.get_credentials(scheme, host, port, user,
1284
if credentials is not None:
1285
# We found some credentials
1289
def register(self, key, obj, help=None, override_existing=False,
1291
"""Register a new object to a name.
1293
:param key: This is the key to use to request the object later.
1294
:param obj: The object to register.
1295
:param help: Help text for this entry. This may be a string or
1296
a callable. If it is a callable, it should take two
1297
parameters (registry, key): this registry and the key that
1298
the help was registered under.
1299
:param override_existing: Raise KeyErorr if False and something has
1300
already been registered for that key. If True, ignore if there
1301
is an existing key (always register the new value).
1302
:param fallback: Whether this credential store should be
1305
return super(CredentialStoreRegistry,
1306
self).register(key, obj, help, info=fallback,
1307
override_existing=override_existing)
1309
def register_lazy(self, key, module_name, member_name,
1310
help=None, override_existing=False,
1312
"""Register a new credential store to be loaded on request.
1314
:param module_name: The python path to the module. Such as 'os.path'.
1315
:param member_name: The member of the module to return. If empty or
1316
None, get() will return the module itself.
1317
:param help: Help text for this entry. This may be a string or
1319
:param override_existing: If True, replace the existing object
1320
with the new one. If False, if there is already something
1321
registered with the same key, raise a KeyError
1322
:param fallback: Whether this credential store should be
1325
return super(CredentialStoreRegistry, self).register_lazy(
1326
key, module_name, member_name, help,
1327
info=fallback, override_existing=override_existing)
1330
credential_store_registry = CredentialStoreRegistry()
1333
class CredentialStore(object):
1334
"""An abstract class to implement storage for credentials"""
1336
def decode_password(self, credentials):
1337
"""Returns a clear text password for the provided credentials."""
1338
raise NotImplementedError(self.decode_password)
1340
def get_credentials(self, scheme, host, port=None, user=None, path=None,
1342
"""Return the matching credentials from this credential store.
1344
This method is only called on fallback credential stores.
1346
raise NotImplementedError(self.get_credentials)
1350
class PlainTextCredentialStore(CredentialStore):
1351
__doc__ = """Plain text credential store for the authentication.conf file"""
1353
def decode_password(self, credentials):
1354
"""See CredentialStore.decode_password."""
1355
return credentials['password']
1358
credential_store_registry.register('plain', PlainTextCredentialStore,
1359
help=PlainTextCredentialStore.__doc__)
1360
credential_store_registry.default_key = 'plain'
1363
class BzrDirConfig(object):
1365
def __init__(self, bzrdir):
1366
self._bzrdir = bzrdir
1367
self._config = bzrdir._get_config()
1369
def set_default_stack_on(self, value):
1370
"""Set the default stacking location.
1372
It may be set to a location, or None.
1374
This policy affects all branches contained by this bzrdir, except for
1375
those under repositories.
1377
if self._config is None:
1378
raise errors.BzrError("Cannot set configuration in %s" % self._bzrdir)
1380
self._config.set_option('', 'default_stack_on')
1382
self._config.set_option(value, 'default_stack_on')
1384
def get_default_stack_on(self):
1385
"""Return the default stacking location.
1387
This will either be a location, or None.
1389
This policy affects all branches contained by this bzrdir, except for
1390
those under repositories.
1392
if self._config is None:
1394
value = self._config.get_option('default_stack_on')
1400
1105
class TransportConfig(object):