~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/config.py

  • Committer: Vincent Ladeuil
  • Date: 2010-07-07 15:03:14 UTC
  • mto: (5355.1.1 integration)
  • mto: This revision was merged to the branch mainline in revision 5356.
  • Revision ID: v.ladeuil+lp@free.fr-20100707150314-7i5po3dwg8umiv8x
Fix remaining sphinx_conf references.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2007, 2008 Canonical Ltd
 
1
# Copyright (C) 2005-2010 Canonical Ltd
2
2
#   Authors: Robert Collins <robert.collins@canonical.com>
3
3
#            and others
4
4
#
153
153
        """Get the users pop up editor."""
154
154
        raise NotImplementedError
155
155
 
 
156
    def get_change_editor(self, old_tree, new_tree):
 
157
        from bzrlib import diff
 
158
        cmd = self._get_change_editor()
 
159
        if cmd is None:
 
160
            return None
 
161
        return diff.DiffFromTool.from_string(cmd, old_tree, new_tree,
 
162
                                             sys.stdout)
 
163
 
 
164
 
156
165
    def get_mail_client(self):
157
166
        """Get a mail client to use"""
158
167
        selected_client = self.get_user_option('mail_client')
181
190
        """Get a generic option as a boolean - no special process, no default.
182
191
 
183
192
        :return None if the option doesn't exist or its value can't be
184
 
            interpreted as a boolean. Returns True or False ortherwise.
 
193
            interpreted as a boolean. Returns True or False otherwise.
185
194
        """
186
195
        s = self._get_user_option(option_name)
187
 
        return ui.bool_from_string(s)
 
196
        if s is None:
 
197
            # The option doesn't exist
 
198
            return None
 
199
        val = ui.bool_from_string(s)
 
200
        if val is None:
 
201
            # The value can't be interpreted as a boolean
 
202
            trace.warning('Value "%s" is not a boolean for "%s"',
 
203
                          s, option_name)
 
204
        return val
 
205
 
 
206
    def get_user_option_as_list(self, option_name):
 
207
        """Get a generic option as a list - no special process, no default.
 
208
 
 
209
        :return None if the option doesn't exist. Returns the value as a list
 
210
            otherwise.
 
211
        """
 
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 ','
 
215
            l = [l]
 
216
        return l
188
217
 
189
218
    def gpg_signing_command(self):
190
219
        """What program should be used to sign signatures?"""
228
257
 
229
258
        Something similar to 'Martin Pool <mbp@sourcefrog.net>'
230
259
 
231
 
        $BZR_EMAIL can be set to override this (as well as the
232
 
        deprecated $BZREMAIL), then
 
260
        $BZR_EMAIL can be set to override this, then
233
261
        the concrete policy type is checked, and finally
234
262
        $EMAIL is examined.
235
 
        If none is found, a reasonable default is (hopefully)
236
 
        created.
 
263
        If no username can be found, errors.NoWhoami exception is raised.
237
264
 
238
265
        TODO: Check it's reasonably well-formed.
239
266
        """
249
276
        if v:
250
277
            return v.decode(osutils.get_user_encoding())
251
278
 
252
 
        name, email = _auto_user_id()
253
 
        if name:
254
 
            return '%s <%s>' % (name, email)
255
 
        else:
256
 
            return email
 
279
        raise errors.NoWhoami()
 
280
 
 
281
    def ensure_username(self):
 
282
        """Raise errors.NoWhoami if username is not set.
 
283
 
 
284
        This method relies on the username() function raising the error.
 
285
        """
 
286
        self.username()
257
287
 
258
288
    def signature_checking(self):
259
289
        """What is the current policy for signature checking?."""
304
334
                path = 'bzr'
305
335
            return path
306
336
 
 
337
    def suppress_warning(self, warning):
 
338
        """Should the warning be suppressed or emitted.
 
339
 
 
340
        :param warning: The name of the warning being tested.
 
341
 
 
342
        :returns: True if the warning should be suppressed, False otherwise.
 
343
        """
 
344
        warnings = self.get_user_option_as_list('suppress_warnings')
 
345
        if warnings is None or warning not in warnings:
 
346
            return False
 
347
        else:
 
348
            return True
 
349
 
307
350
 
308
351
class IniBasedConfig(Config):
309
352
    """A configuration policy that draws from ini files."""
346
389
        """Return the policy for the given (section, option_name) pair."""
347
390
        return POLICY_NONE
348
391
 
 
392
    def _get_change_editor(self):
 
393
        return self.get_user_option('change_editor')
 
394
 
349
395
    def _get_signature_checking(self):
350
396
        """See Config._get_signature_checking."""
351
397
        policy = self._get_user_option('check_signatures')
431
477
    def _get_nickname(self):
432
478
        return self.get_user_option('nickname')
433
479
 
 
480
    def _write_config_file(self):
 
481
        f = file(self._get_filename(), "wb")
 
482
        try:
 
483
            osutils.copy_ownership_from_path(f.name)
 
484
            self._get_parser().write(f)
 
485
        finally:
 
486
            f.close()
 
487
 
434
488
 
435
489
class GlobalConfig(IniBasedConfig):
436
490
    """The configuration that should be used for a specific location."""
472
526
        self._get_parser().setdefault(section, {})[option] = value
473
527
        self._write_config_file()
474
528
 
475
 
    def _write_config_file(self):
476
 
        f = open(self._get_filename(), 'wb')
477
 
        self._get_parser().write(f)
478
 
        f.close()
479
 
 
480
529
 
481
530
class LocationConfig(IniBasedConfig):
482
531
    """A configuration object that gives the policy for a location."""
616
665
        self._get_parser()[location][option]=value
617
666
        # the allowed values of store match the config policies
618
667
        self._set_option_policy(location, option, store)
619
 
        self._get_parser().write(file(self._get_filename(), 'wb'))
 
668
        self._write_config_file()
620
669
 
621
670
 
622
671
class BranchConfig(Config):
679
728
 
680
729
        return self._get_best_value('_get_user_id')
681
730
 
 
731
    def _get_change_editor(self):
 
732
        return self._get_best_value('_get_change_editor')
 
733
 
682
734
    def _get_signature_checking(self):
683
735
        """See Config._get_signature_checking."""
684
736
        return self._get_best_value('_get_signature_checking')
770
822
            os.mkdir(parent_dir)
771
823
        trace.mutter('creating config directory: %r', path)
772
824
        os.mkdir(path)
 
825
        osutils.copy_ownership_from_path(path)
773
826
 
774
827
 
775
828
def config_dir():
790
843
                                  ' or HOME set')
791
844
        return osutils.pathjoin(base, 'bazaar', '2.0')
792
845
    else:
793
 
        # cygwin, linux, and darwin all have a $HOME directory
794
846
        if base is None:
795
847
            base = os.path.expanduser("~")
796
848
        return osutils.pathjoin(base, ".bazaar")
821
873
    return osutils.pathjoin(config_dir(), 'ignore')
822
874
 
823
875
 
824
 
def _auto_user_id():
825
 
    """Calculate automatic user identification.
826
 
 
827
 
    Returns (realname, email).
828
 
 
829
 
    Only used when none is set in the environment or the id file.
830
 
 
831
 
    This previously used the FQDN as the default domain, but that can
832
 
    be very slow on machines where DNS is broken.  So now we simply
833
 
    use the hostname.
 
876
def crash_dir():
 
877
    """Return the directory name to store crash files.
 
878
 
 
879
    This doesn't implicitly create it.
 
880
 
 
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
 
883
    $APPORT_CRASH_DIR.
834
884
    """
835
 
    import socket
836
 
 
837
885
    if sys.platform == 'win32':
838
 
        name = win32utils.get_user_name_unicode()
839
 
        if name is None:
840
 
            raise errors.BzrError("Cannot autodetect user name.\n"
841
 
                                  "Please, set your name with command like:\n"
842
 
                                  'bzr whoami "Your Name <name@domain.com>"')
843
 
        host = win32utils.get_host_name_unicode()
844
 
        if host is None:
845
 
            host = socket.gethostname()
846
 
        return name, (name + '@' + host)
847
 
 
848
 
    try:
849
 
        import pwd
850
 
        uid = os.getuid()
851
 
        try:
852
 
            w = pwd.getpwuid(uid)
853
 
        except KeyError:
854
 
            raise errors.BzrCommandError('Unable to determine your name.  '
855
 
                'Please use "bzr whoami" to set it.')
856
 
 
857
 
        # we try utf-8 first, because on many variants (like Linux),
858
 
        # /etc/passwd "should" be in utf-8, and because it's unlikely to give
859
 
        # false positives.  (many users will have their user encoding set to
860
 
        # latin-1, which cannot raise UnicodeError.)
861
 
        try:
862
 
            gecos = w.pw_gecos.decode('utf-8')
863
 
            encoding = 'utf-8'
864
 
        except UnicodeError:
865
 
            try:
866
 
                encoding = osutils.get_user_encoding()
867
 
                gecos = w.pw_gecos.decode(encoding)
868
 
            except UnicodeError:
869
 
                raise errors.BzrCommandError('Unable to determine your name.  '
870
 
                   'Use "bzr whoami" to set it.')
871
 
        try:
872
 
            username = w.pw_name.decode(encoding)
873
 
        except UnicodeError:
874
 
            raise errors.BzrCommandError('Unable to determine your name.  '
875
 
                'Use "bzr whoami" to set it.')
876
 
 
877
 
        comma = gecos.find(',')
878
 
        if comma == -1:
879
 
            realname = gecos
880
 
        else:
881
 
            realname = gecos[:comma]
882
 
        if not realname:
883
 
            realname = username
884
 
 
885
 
    except ImportError:
886
 
        import getpass
887
 
        try:
888
 
            user_encoding = osutils.get_user_encoding()
889
 
            realname = username = getpass.getuser().decode(user_encoding)
890
 
        except UnicodeDecodeError:
891
 
            raise errors.BzrError("Can't decode username as %s." % \
892
 
                    user_encoding)
893
 
 
894
 
    return realname, (username + '@' + socket.gethostname())
 
886
        return osutils.pathjoin(config_dir(), 'Crash')
 
887
    else:
 
888
        # XXX: hardcoded in apport_python_hook.py; therefore here too -- mbp
 
889
        # 2010-01-31
 
890
        return os.environ.get('APPORT_CRASH_DIR', '/var/crash')
 
891
 
 
892
 
 
893
def xdg_cache_dir():
 
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)
 
897
    if e:
 
898
        return e
 
899
    else:
 
900
        return os.path.expanduser('~/.cache')
895
901
 
896
902
 
897
903
def parse_username(username):
985
991
        """Save the config file, only tests should use it for now."""
986
992
        conf_dir = os.path.dirname(self._filename)
987
993
        ensure_config_dir_exists(conf_dir)
988
 
        self._get_config().write(file(self._filename, 'wb'))
 
994
        f = file(self._filename, 'wb')
 
995
        try:
 
996
            self._get_config().write(f)
 
997
        finally:
 
998
            f.close()
989
999
 
990
1000
    def _set_option(self, section_name, option_name, value):
991
1001
        """Set an authentication configuration option"""
1339
1349
 
1340
1350
 
1341
1351
class PlainTextCredentialStore(CredentialStore):
1342
 
    """Plain text credential store for the authentication.conf file."""
 
1352
    __doc__ = """Plain text credential store for the authentication.conf file"""
1343
1353
 
1344
1354
    def decode_password(self, credentials):
1345
1355
        """See CredentialStore.decode_password."""
1434
1444
 
1435
1445
    def _get_config_file(self):
1436
1446
        try:
1437
 
            return self._transport.get(self._filename)
 
1447
            return StringIO(self._transport.get_bytes(self._filename))
1438
1448
        except errors.NoSuchFile:
1439
1449
            return StringIO()
1440
1450
 
1441
1451
    def _get_configobj(self):
1442
 
        return ConfigObj(self._get_config_file(), encoding='utf-8')
 
1452
        f = self._get_config_file()
 
1453
        try:
 
1454
            return ConfigObj(f, encoding='utf-8')
 
1455
        finally:
 
1456
            f.close()
1443
1457
 
1444
1458
    def _set_configobj(self, configobj):
1445
1459
        out_file = StringIO()