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.
45
45
editor - this option sets the pop up editor to use during commits.
46
46
email - this option sets the user id bzr will use when committing.
47
47
check_signatures - this option controls whether bzr will require good gpg
48
signatures, ignore them, or check them if they are
48
signatures, ignore them, or check them if they are
50
create_signatures - this option controls whether bzr will always create
50
create_signatures - this option controls whether bzr will always create
51
51
gpg signatures, never create them, or create them if the
52
52
branch is configured to require them.
53
53
log_format - this option sets the default log format. Possible values are
147
146
class Config(object):
148
147
"""A configuration policy - what username, editor, gpg needs etc."""
151
super(Config, self).__init__()
153
149
def get_editor(self):
154
150
"""Get the users pop up editor."""
155
151
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
153
def get_mail_client(self):
167
154
"""Get a mail client to use"""
168
155
selected_client = self.get_user_option('mail_client')
187
174
"""Get a generic option - no special process, no default."""
188
175
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
177
def gpg_signing_command(self):
220
178
"""What program should be used to sign signatures?"""
221
179
result = self._gpg_signing_command()
256
217
def username(self):
257
218
"""Return email-style username.
259
220
Something similar to 'Martin Pool <mbp@sourcefrog.net>'
261
$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
262
224
the concrete policy type is checked, and finally
263
225
$EMAIL is examined.
264
If no username can be found, errors.NoWhoami exception is raised.
226
If none is found, a reasonable default is (hopefully)
266
229
TODO: Check it's reasonably well-formed.
268
231
v = os.environ.get('BZR_EMAIL')
278
241
return v.decode(osutils.get_user_encoding())
280
raise errors.NoWhoami()
282
def ensure_username(self):
283
"""Raise errors.NoWhoami if username is not set.
285
This method relies on the username() function raising the error.
243
name, email = _auto_user_id()
245
return '%s <%s>' % (name, email)
289
249
def signature_checking(self):
290
250
"""What is the current policy for signature checking?."""
338
def suppress_warning(self, warning):
339
"""Should the warning be suppressed or emitted.
341
:param warning: The name of the warning being tested.
343
:returns: True if the warning should be suppressed, False otherwise.
345
warnings = self.get_user_option_as_list('suppress_warnings')
346
if warnings is None or warning not in warnings:
352
299
class IniBasedConfig(Config):
353
300
"""A configuration policy that draws from ini files."""
355
def __init__(self, get_filename):
356
super(IniBasedConfig, self).__init__()
357
self._get_filename = get_filename
360
302
def _get_parser(self, file=None):
361
303
if self._parser is not None:
362
304
return self._parser
771
709
trace.warning('Value "%s" is masked by "%s" from'
772
710
' branch.conf', value, mask_value)
774
713
def _gpg_signing_command(self):
775
714
"""See Config.gpg_signing_command."""
776
715
return self._get_safe_value('_gpg_signing_command')
778
717
def __init__(self, branch):
779
718
super(BranchConfig, self).__init__()
780
719
self._location_config = None
781
720
self._branch_data_config = None
782
721
self._global_config = None
783
722
self.branch = branch
784
self.option_sources = (self._get_location_config,
723
self.option_sources = (self._get_location_config,
785
724
self._get_branch_data_config,
786
725
self._get_global_config)
874
813
return osutils.pathjoin(config_dir(), 'ignore')
878
"""Return the directory name to store crash files.
880
This doesn't implicitly create it.
882
On Windows it's in the config directory; elsewhere it's /var/crash
883
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
886
829
if sys.platform == 'win32':
887
return osutils.pathjoin(config_dir(), 'Crash')
889
# XXX: hardcoded in apport_python_hook.py; therefore here too -- mbp
891
return os.environ.get('APPORT_CRASH_DIR', '/var/crash')
895
# See http://standards.freedesktop.org/basedir-spec/latest/ar01s03.html
896
# Possibly this should be different on Windows?
897
e = os.environ.get('XDG_CACHE_DIR', None)
901
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())
904
889
def parse_username(username):
932
917
# XXX: Really needs a better name, as this is not part of the tree! -- mbp 20080507
934
919
def __init__(self, branch):
935
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')
936
924
self.branch = branch
938
926
def _get_parser(self, file=None):
992
981
"""Save the config file, only tests should use it for now."""
993
982
conf_dir = os.path.dirname(self._filename)
994
983
ensure_config_dir_exists(conf_dir)
995
f = file(self._filename, 'wb')
997
self._get_config().write(f)
984
self._get_config().write(file(self._filename, 'wb'))
1001
986
def _set_option(self, section_name, option_name, value):
1002
987
"""Set an authentication configuration option"""
1008
993
section[option_name] = value
1011
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):
1013
997
"""Returns the matching credentials from authentication.conf file.
1015
999
:param scheme: protocol
1021
1005
:param user: login (optional)
1023
1007
:param path: the absolute path on the server (optional)
1025
:param realm: the http authentication realm (optional)
1027
1009
:return: A dict containing the matching credentials or None.
1029
1011
- name: the section name of the credentials in the
1030
1012
authentication.conf file,
1031
- user: can't be different from the provided user if any,
1032
- scheme: the server protocol,
1033
- host: the server address,
1034
- port: the server port (can be None),
1035
- path: the absolute server path (can be None),
1036
- realm: the http specific authentication realm (can be None),
1013
- user: can't de different from the provided user if any,
1037
1014
- password: the decoded password, could be None if the credential
1038
1015
defines only the user
1039
1016
- verify_certificates: https specific, True if the server
1080
1057
if a_user is None:
1081
1058
# Can't find a user
1083
# Prepare a credentials dictionary with additional keys
1084
# for the credential providers
1085
1060
credentials = dict(name=auth_def_name,
1092
1062
password=auth_def.get('password', None),
1093
1063
verify_certificates=a_verify_certificates)
1094
# Decode the password in the credentials (or get one)
1095
1064
self.decode_password(credentials,
1096
1065
auth_def.get('password_encoding', None))
1097
1066
if 'auth' in debug.debug_flags:
1098
1067
trace.mutter("Using authentication section: %r", auth_def_name)
1101
if credentials is None:
1102
# No credentials were found in authentication.conf, try the fallback
1103
# credentials stores.
1104
credentials = credential_store_registry.get_fallback_credentials(
1105
scheme, host, port, user, path, realm)
1107
1070
return credentials
1109
1072
def set_credentials(self, name, host, user, scheme=None, password=None,
1110
port=None, path=None, verify_certificates=None,
1073
port=None, path=None, verify_certificates=None):
1112
1074
"""Set authentication credentials for a host.
1114
1076
Any existing credentials with matching scheme, host, port and path
1138
1099
values['path'] = path
1139
1100
if verify_certificates is not None:
1140
1101
values['verify_certificates'] = str(verify_certificates)
1141
if realm is not None:
1142
values['realm'] = realm
1143
1102
config = self._get_config()
1144
1103
for_deletion = []
1145
1104
for section, existing_values in config.items():
1146
for key in ('scheme', 'host', 'port', 'path', 'realm'):
1105
for key in ('scheme', 'host', 'port', 'path'):
1147
1106
if existing_values.get(key) != values.get(key):
1151
1110
config.update({name: values})
1154
def get_user(self, scheme, host, port=None, realm=None, path=None,
1155
prompt=None, ask=False, default=None):
1113
def get_user(self, scheme, host, port=None,
1114
realm=None, path=None, prompt=None):
1156
1115
"""Get a user from authentication file.
1158
1117
:param scheme: protocol
1166
1125
:param path: the absolute path on the server (optional)
1168
:param ask: Ask the user if there is no explicitly configured username
1171
:param default: The username returned if none is defined (optional).
1173
1127
:return: The found user.
1175
1129
credentials = self.get_credentials(scheme, host, port, user=None,
1176
path=path, realm=realm)
1177
1131
if credentials is not None:
1178
1132
user = credentials['user']
1184
# Create a default prompt suitable for most cases
1185
prompt = scheme.upper() + ' %(host)s username'
1186
# Special handling for optional fields in the prompt
1187
if port is not None:
1188
prompt_host = '%s:%d' % (host, port)
1191
user = ui.ui_factory.get_username(prompt, host=prompt_host)
1196
1137
def get_password(self, scheme, host, user, port=None,
1212
1153
:return: The found password or the one entered by the user.
1214
credentials = self.get_credentials(scheme, host, port, user, path,
1155
credentials = self.get_credentials(scheme, host, port, user, path)
1216
1156
if credentials is not None:
1217
1157
password = credentials['password']
1218
1158
if password is not None and scheme is 'ssh':
1251
1191
A credential store provides access to credentials via the password_encoding
1252
1192
field in authentication.conf sections.
1254
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
1255
1195
provided by plugins that will therefore use
1256
1196
register_lazy(password_encoding, module_name, member_name, help=help,
1257
fallback=fallback) to install themselves.
1259
A fallback credential store is one that is queried if no credentials can be
1260
found via authentication.conf.
1197
info=info) to install themselves.
1263
1200
def get_credential_store(self, encoding=None):
1269
def is_fallback(self, name):
1270
"""Check if the named credentials store should be used as fallback."""
1271
return self.get_info(name)
1273
def get_fallback_credentials(self, scheme, host, port=None, user=None,
1274
path=None, realm=None):
1275
"""Request credentials from all fallback credentials stores.
1277
The first credentials store that can provide credentials wins.
1280
for name in self.keys():
1281
if not self.is_fallback(name):
1283
cs = self.get_credential_store(name)
1284
credentials = cs.get_credentials(scheme, host, port, user,
1286
if credentials is not None:
1287
# We found some credentials
1291
def register(self, key, obj, help=None, override_existing=False,
1293
"""Register a new object to a name.
1295
:param key: This is the key to use to request the object later.
1296
:param obj: The object to register.
1297
:param help: Help text for this entry. This may be a string or
1298
a callable. If it is a callable, it should take two
1299
parameters (registry, key): this registry and the key that
1300
the help was registered under.
1301
:param override_existing: Raise KeyErorr if False and something has
1302
already been registered for that key. If True, ignore if there
1303
is an existing key (always register the new value).
1304
:param fallback: Whether this credential store should be
1307
return super(CredentialStoreRegistry,
1308
self).register(key, obj, help, info=fallback,
1309
override_existing=override_existing)
1311
def register_lazy(self, key, module_name, member_name,
1312
help=None, override_existing=False,
1314
"""Register a new credential store to be loaded on request.
1316
:param module_name: The python path to the module. Such as 'os.path'.
1317
:param member_name: The member of the module to return. If empty or
1318
None, get() will return the module itself.
1319
:param help: Help text for this entry. This may be a string or
1321
:param override_existing: If True, replace the existing object
1322
with the new one. If False, if there is already something
1323
registered with the same key, raise a KeyError
1324
:param fallback: Whether this credential store should be
1327
return super(CredentialStoreRegistry, self).register_lazy(
1328
key, module_name, member_name, help,
1329
info=fallback, override_existing=override_existing)
1332
1207
credential_store_registry = CredentialStoreRegistry()
1336
1211
"""An abstract class to implement storage for credentials"""
1338
1213
def decode_password(self, credentials):
1339
"""Returns a clear text password for the provided credentials."""
1214
"""Returns a password for the provided credentials in clear text."""
1340
1215
raise NotImplementedError(self.decode_password)
1342
def get_credentials(self, scheme, host, port=None, user=None, path=None,
1344
"""Return the matching credentials from this credential store.
1346
This method is only called on fallback credential stores.
1348
raise NotImplementedError(self.get_credentials)
1352
1218
class PlainTextCredentialStore(CredentialStore):
1353
__doc__ = """Plain text credential store for the authentication.conf file"""
1219
"""Plain text credential store for the authentication.conf file."""
1355
1221
def decode_password(self, credentials):
1356
1222
"""See CredentialStore.decode_password."""
1365
1231
class BzrDirConfig(object):
1367
def __init__(self, bzrdir):
1368
self._bzrdir = bzrdir
1369
self._config = bzrdir._get_config()
1233
def __init__(self, transport):
1234
self._config = TransportConfig(transport, 'control.conf')
1371
1236
def set_default_stack_on(self, value):
1372
1237
"""Set the default stacking location.
1443
1304
configobj.setdefault(section, {})[name] = value
1444
1305
self._set_configobj(configobj)
1446
def _get_config_file(self):
1307
def _get_configobj(self):
1448
return StringIO(self._transport.get_bytes(self._filename))
1309
return ConfigObj(self._transport.get(self._filename),
1449
1311
except errors.NoSuchFile:
1452
def _get_configobj(self):
1453
f = self._get_config_file()
1455
return ConfigObj(f, encoding='utf-8')
1312
return ConfigObj(encoding='utf-8')
1459
1314
def _set_configobj(self, configobj):
1460
1315
out_file = StringIO()