15
15
# You should have received a copy of the GNU General Public License
16
16
# along with this program; if not, write to the Free Software
17
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19
19
"""Configuration that affects the behaviour of Bazaar.
146
146
class Config(object):
147
147
"""A configuration policy - what username, editor, gpg needs etc."""
150
super(Config, self).__init__()
152
149
def get_editor(self):
153
150
"""Get the users pop up editor."""
154
151
raise NotImplementedError
156
def get_change_editor(self, old_tree, new_tree):
157
from bzrlib import diff
158
cmd = self._get_change_editor()
161
return diff.DiffFromTool.from_string(cmd, old_tree, new_tree,
165
153
def get_mail_client(self):
166
154
"""Get a mail client to use"""
167
155
selected_client = self.get_user_option('mail_client')
186
174
"""Get a generic option - no special process, no default."""
187
175
return self._get_user_option(option_name)
189
def get_user_option_as_bool(self, option_name):
190
"""Get a generic option as a boolean - no special process, no default.
192
:return None if the option doesn't exist or its value can't be
193
interpreted as a boolean. Returns True or False otherwise.
195
s = self._get_user_option(option_name)
197
# The option doesn't exist
199
val = ui.bool_from_string(s)
201
# The value can't be interpreted as a boolean
202
trace.warning('Value "%s" is not a boolean for "%s"',
206
def get_user_option_as_list(self, option_name):
207
"""Get a generic option as a list - no special process, no default.
209
:return None if the option doesn't exist. Returns the value as a list
212
l = self._get_user_option(option_name)
213
if isinstance(l, (str, unicode)):
214
# A single value, most probably the user forgot the final ','
218
177
def gpg_signing_command(self):
219
178
"""What program should be used to sign signatures?"""
220
179
result = self._gpg_signing_command()
258
220
Something similar to 'Martin Pool <mbp@sourcefrog.net>'
260
$BZR_EMAIL can be set to override this, then
222
$BZR_EMAIL can be set to override this (as well as the
223
deprecated $BZREMAIL), then
261
224
the concrete policy type is checked, and finally
262
225
$EMAIL is examined.
263
If no username can be found, errors.NoWhoami exception is raised.
226
If none is found, a reasonable default is (hopefully)
265
229
TODO: Check it's reasonably well-formed.
277
241
return v.decode(osutils.get_user_encoding())
279
raise errors.NoWhoami()
281
def ensure_username(self):
282
"""Raise errors.NoWhoami if username is not set.
284
This method relies on the username() function raising the error.
243
name, email = _auto_user_id()
245
return '%s <%s>' % (name, email)
288
249
def signature_checking(self):
289
250
"""What is the current policy for signature checking?."""
337
def suppress_warning(self, warning):
338
"""Should the warning be suppressed or emitted.
340
:param warning: The name of the warning being tested.
342
:returns: True if the warning should be suppressed, False otherwise.
344
warnings = self.get_user_option_as_list('suppress_warnings')
345
if warnings is None or warning not in warnings:
351
299
class IniBasedConfig(Config):
352
300
"""A configuration policy that draws from ini files."""
354
def __init__(self, get_filename):
355
super(IniBasedConfig, self).__init__()
356
self._get_filename = get_filename
359
302
def _get_parser(self, file=None):
360
303
if self._parser is not None:
361
304
return self._parser
873
813
return osutils.pathjoin(config_dir(), 'ignore')
877
"""Return the directory name to store crash files.
879
This doesn't implicitly create it.
881
On Windows it's in the config directory; elsewhere it's /var/crash
882
which may be monitored by apport. It can be overridden by
817
"""Calculate automatic user identification.
819
Returns (realname, email).
821
Only used when none is set in the environment or the id file.
823
This previously used the FQDN as the default domain, but that can
824
be very slow on machines where DNS is broken. So now we simply
885
829
if sys.platform == 'win32':
886
return osutils.pathjoin(config_dir(), 'Crash')
888
# XXX: hardcoded in apport_python_hook.py; therefore here too -- mbp
890
return os.environ.get('APPORT_CRASH_DIR', '/var/crash')
894
# See http://standards.freedesktop.org/basedir-spec/latest/ar01s03.html
895
# Possibly this should be different on Windows?
896
e = os.environ.get('XDG_CACHE_DIR', None)
900
return os.path.expanduser('~/.cache')
830
name = win32utils.get_user_name_unicode()
832
raise errors.BzrError("Cannot autodetect user name.\n"
833
"Please, set your name with command like:\n"
834
'bzr whoami "Your Name <name@domain.com>"')
835
host = win32utils.get_host_name_unicode()
837
host = socket.gethostname()
838
return name, (name + '@' + host)
844
w = pwd.getpwuid(uid)
846
raise errors.BzrCommandError('Unable to determine your name. '
847
'Please use "bzr whoami" to set it.')
849
# we try utf-8 first, because on many variants (like Linux),
850
# /etc/passwd "should" be in utf-8, and because it's unlikely to give
851
# false positives. (many users will have their user encoding set to
852
# latin-1, which cannot raise UnicodeError.)
854
gecos = w.pw_gecos.decode('utf-8')
858
encoding = osutils.get_user_encoding()
859
gecos = w.pw_gecos.decode(encoding)
861
raise errors.BzrCommandError('Unable to determine your name. '
862
'Use "bzr whoami" to set it.')
864
username = w.pw_name.decode(encoding)
866
raise errors.BzrCommandError('Unable to determine your name. '
867
'Use "bzr whoami" to set it.')
869
comma = gecos.find(',')
873
realname = gecos[:comma]
880
user_encoding = osutils.get_user_encoding()
881
realname = username = getpass.getuser().decode(user_encoding)
882
except UnicodeDecodeError:
883
raise errors.BzrError("Can't decode username as %s." % \
886
return realname, (username + '@' + socket.gethostname())
903
889
def parse_username(username):
931
917
# XXX: Really needs a better name, as this is not part of the tree! -- mbp 20080507
933
919
def __init__(self, branch):
934
self._config = branch._get_config()
920
# XXX: Really this should be asking the branch for its configuration
921
# data, rather than relying on a Transport, so that it can work
922
# more cleanly with a RemoteBranch that has no transport.
923
self._config = TransportConfig(branch._transport, 'branch.conf')
935
924
self.branch = branch
937
926
def _get_parser(self, file=None):
1003
993
section[option_name] = value
1006
def get_credentials(self, scheme, host, port=None, user=None, path=None,
996
def get_credentials(self, scheme, host, port=None, user=None, path=None):
1008
997
"""Returns the matching credentials from authentication.conf file.
1010
999
:param scheme: protocol
1016
1005
:param user: login (optional)
1018
1007
:param path: the absolute path on the server (optional)
1020
:param realm: the http authentication realm (optional)
1022
1009
:return: A dict containing the matching credentials or None.
1024
1011
- name: the section name of the credentials in the
1025
1012
authentication.conf file,
1026
- user: can't be different from the provided user if any,
1027
- scheme: the server protocol,
1028
- host: the server address,
1029
- port: the server port (can be None),
1030
- path: the absolute server path (can be None),
1031
- realm: the http specific authentication realm (can be None),
1013
- user: can't de different from the provided user if any,
1032
1014
- password: the decoded password, could be None if the credential
1033
1015
defines only the user
1034
1016
- verify_certificates: https specific, True if the server
1075
1057
if a_user is None:
1076
1058
# Can't find a user
1078
# Prepare a credentials dictionary with additional keys
1079
# for the credential providers
1080
1060
credentials = dict(name=auth_def_name,
1087
1062
password=auth_def.get('password', None),
1088
1063
verify_certificates=a_verify_certificates)
1089
# Decode the password in the credentials (or get one)
1090
1064
self.decode_password(credentials,
1091
1065
auth_def.get('password_encoding', None))
1092
1066
if 'auth' in debug.debug_flags:
1093
1067
trace.mutter("Using authentication section: %r", auth_def_name)
1096
if credentials is None:
1097
# No credentials were found in authentication.conf, try the fallback
1098
# credentials stores.
1099
credentials = credential_store_registry.get_fallback_credentials(
1100
scheme, host, port, user, path, realm)
1102
1070
return credentials
1104
1072
def set_credentials(self, name, host, user, scheme=None, password=None,
1105
port=None, path=None, verify_certificates=None,
1073
port=None, path=None, verify_certificates=None):
1107
1074
"""Set authentication credentials for a host.
1109
1076
Any existing credentials with matching scheme, host, port and path
1133
1099
values['path'] = path
1134
1100
if verify_certificates is not None:
1135
1101
values['verify_certificates'] = str(verify_certificates)
1136
if realm is not None:
1137
values['realm'] = realm
1138
1102
config = self._get_config()
1139
1103
for_deletion = []
1140
1104
for section, existing_values in config.items():
1141
for key in ('scheme', 'host', 'port', 'path', 'realm'):
1105
for key in ('scheme', 'host', 'port', 'path'):
1142
1106
if existing_values.get(key) != values.get(key):
1146
1110
config.update({name: values})
1149
def get_user(self, scheme, host, port=None, realm=None, path=None,
1150
prompt=None, ask=False, default=None):
1113
def get_user(self, scheme, host, port=None,
1114
realm=None, path=None, prompt=None):
1151
1115
"""Get a user from authentication file.
1153
1117
:param scheme: protocol
1161
1125
:param path: the absolute path on the server (optional)
1163
:param ask: Ask the user if there is no explicitly configured username
1166
:param default: The username returned if none is defined (optional).
1168
1127
:return: The found user.
1170
1129
credentials = self.get_credentials(scheme, host, port, user=None,
1171
path=path, realm=realm)
1172
1131
if credentials is not None:
1173
1132
user = credentials['user']
1179
# Create a default prompt suitable for most cases
1180
prompt = scheme.upper() + ' %(host)s username'
1181
# Special handling for optional fields in the prompt
1182
if port is not None:
1183
prompt_host = '%s:%d' % (host, port)
1186
user = ui.ui_factory.get_username(prompt, host=prompt_host)
1191
1137
def get_password(self, scheme, host, user, port=None,
1207
1153
:return: The found password or the one entered by the user.
1209
credentials = self.get_credentials(scheme, host, port, user, path,
1155
credentials = self.get_credentials(scheme, host, port, user, path)
1211
1156
if credentials is not None:
1212
1157
password = credentials['password']
1213
1158
if password is not None and scheme is 'ssh':
1246
1191
A credential store provides access to credentials via the password_encoding
1247
1192
field in authentication.conf sections.
1249
Except for stores provided by bzr itself, most stores are expected to be
1194
Except for stores provided by bzr itself,most stores are expected to be
1250
1195
provided by plugins that will therefore use
1251
1196
register_lazy(password_encoding, module_name, member_name, help=help,
1252
fallback=fallback) to install themselves.
1254
A fallback credential store is one that is queried if no credentials can be
1255
found via authentication.conf.
1197
info=info) to install themselves.
1258
1200
def get_credential_store(self, encoding=None):
1264
def is_fallback(self, name):
1265
"""Check if the named credentials store should be used as fallback."""
1266
return self.get_info(name)
1268
def get_fallback_credentials(self, scheme, host, port=None, user=None,
1269
path=None, realm=None):
1270
"""Request credentials from all fallback credentials stores.
1272
The first credentials store that can provide credentials wins.
1275
for name in self.keys():
1276
if not self.is_fallback(name):
1278
cs = self.get_credential_store(name)
1279
credentials = cs.get_credentials(scheme, host, port, user,
1281
if credentials is not None:
1282
# We found some credentials
1286
def register(self, key, obj, help=None, override_existing=False,
1288
"""Register a new object to a name.
1290
:param key: This is the key to use to request the object later.
1291
:param obj: The object to register.
1292
:param help: Help text for this entry. This may be a string or
1293
a callable. If it is a callable, it should take two
1294
parameters (registry, key): this registry and the key that
1295
the help was registered under.
1296
:param override_existing: Raise KeyErorr if False and something has
1297
already been registered for that key. If True, ignore if there
1298
is an existing key (always register the new value).
1299
:param fallback: Whether this credential store should be
1302
return super(CredentialStoreRegistry,
1303
self).register(key, obj, help, info=fallback,
1304
override_existing=override_existing)
1306
def register_lazy(self, key, module_name, member_name,
1307
help=None, override_existing=False,
1309
"""Register a new credential store to be loaded on request.
1311
:param module_name: The python path to the module. Such as 'os.path'.
1312
:param member_name: The member of the module to return. If empty or
1313
None, get() will return the module itself.
1314
:param help: Help text for this entry. This may be a string or
1316
:param override_existing: If True, replace the existing object
1317
with the new one. If False, if there is already something
1318
registered with the same key, raise a KeyError
1319
:param fallback: Whether this credential store should be
1322
return super(CredentialStoreRegistry, self).register_lazy(
1323
key, module_name, member_name, help,
1324
info=fallback, override_existing=override_existing)
1327
1207
credential_store_registry = CredentialStoreRegistry()
1331
1211
"""An abstract class to implement storage for credentials"""
1333
1213
def decode_password(self, credentials):
1334
"""Returns a clear text password for the provided credentials."""
1214
"""Returns a password for the provided credentials in clear text."""
1335
1215
raise NotImplementedError(self.decode_password)
1337
def get_credentials(self, scheme, host, port=None, user=None, path=None,
1339
"""Return the matching credentials from this credential store.
1341
This method is only called on fallback credential stores.
1343
raise NotImplementedError(self.get_credentials)
1347
1218
class PlainTextCredentialStore(CredentialStore):
1348
__doc__ = """Plain text credential store for the authentication.conf file"""
1219
"""Plain text credential store for the authentication.conf file."""
1350
1221
def decode_password(self, credentials):
1351
1222
"""See CredentialStore.decode_password."""
1360
1231
class BzrDirConfig(object):
1362
def __init__(self, bzrdir):
1363
self._bzrdir = bzrdir
1364
self._config = bzrdir._get_config()
1233
def __init__(self, transport):
1234
self._config = TransportConfig(transport, 'control.conf')
1366
1236
def set_default_stack_on(self, value):
1367
1237
"""Set the default stacking location.
1438
1304
configobj.setdefault(section, {})[name] = value
1439
1305
self._set_configobj(configobj)
1441
def _get_config_file(self):
1307
def _get_configobj(self):
1443
return StringIO(self._transport.get_bytes(self._filename))
1309
return ConfigObj(self._transport.get(self._filename),
1444
1311
except errors.NoSuchFile:
1447
def _get_configobj(self):
1448
return ConfigObj(self._get_config_file(), encoding='utf-8')
1312
return ConfigObj(encoding='utf-8')
1450
1314
def _set_configobj(self, configobj):
1451
1315
out_file = StringIO()