~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/config.py

  • Committer: Robert Collins
  • Date: 2010-05-06 23:54:05 UTC
  • mto: This revision was merged to the branch mainline in revision 5223.
  • Revision ID: robertc@robertcollins.net-20100506235405-wii4elupfhzl3jvy
Add __str__ to the new helper classes.

Show diffs side-by-side

added added

removed removed

Lines of Context:
74
74
 
75
75
import bzrlib
76
76
from bzrlib import (
77
 
    atomicfile,
78
77
    debug,
79
78
    errors,
80
79
    mail_client,
258
257
 
259
258
        Something similar to 'Martin Pool <mbp@sourcefrog.net>'
260
259
 
261
 
        $BZR_EMAIL can be set to override this, then
 
260
        $BZR_EMAIL can be set to override this (as well as the
 
261
        deprecated $BZREMAIL), then
262
262
        the concrete policy type is checked, and finally
263
263
        $EMAIL is examined.
264
 
        If no username can be found, errors.NoWhoami exception is raised.
 
264
        If none is found, a reasonable default is (hopefully)
 
265
        created.
265
266
 
266
267
        TODO: Check it's reasonably well-formed.
267
268
        """
277
278
        if v:
278
279
            return v.decode(osutils.get_user_encoding())
279
280
 
280
 
        raise errors.NoWhoami()
281
 
 
282
 
    def ensure_username(self):
283
 
        """Raise errors.NoWhoami if username is not set.
284
 
 
285
 
        This method relies on the username() function raising the error.
286
 
        """
287
 
        self.username()
 
281
        name, email = _auto_user_id()
 
282
        if name:
 
283
            return '%s <%s>' % (name, email)
 
284
        else:
 
285
            return email
288
286
 
289
287
    def signature_checking(self):
290
288
        """What is the current policy for signature checking?."""
478
476
    def _get_nickname(self):
479
477
        return self.get_user_option('nickname')
480
478
 
481
 
    def _write_config_file(self):
482
 
        atomic_file = atomicfile.AtomicFile(self._get_filename())
483
 
        self._get_parser().write(atomic_file)
484
 
        atomic_file.commit()
485
 
        atomic_file.close()
486
 
 
487
479
 
488
480
class GlobalConfig(IniBasedConfig):
489
481
    """The configuration that should be used for a specific location."""
525
517
        self._get_parser().setdefault(section, {})[option] = value
526
518
        self._write_config_file()
527
519
 
 
520
    def _write_config_file(self):
 
521
        path = self._get_filename()
 
522
        f = open(path, 'wb')
 
523
        osutils.copy_ownership_from_path(path)
 
524
        self._get_parser().write(f)
 
525
        f.close()
 
526
 
528
527
 
529
528
class LocationConfig(IniBasedConfig):
530
529
    """A configuration object that gives the policy for a location."""
664
663
        self._get_parser()[location][option]=value
665
664
        # the allowed values of store match the config policies
666
665
        self._set_option_policy(location, option, store)
667
 
        self._write_config_file()
 
666
        self._get_parser().write(file(self._get_filename(), 'wb'))
668
667
 
669
668
 
670
669
class BranchConfig(Config):
842
841
                                  ' or HOME set')
843
842
        return osutils.pathjoin(base, 'bazaar', '2.0')
844
843
    else:
 
844
        # cygwin, linux, and darwin all have a $HOME directory
845
845
        if base is None:
846
846
            base = os.path.expanduser("~")
847
847
        return osutils.pathjoin(base, ".bazaar")
899
899
        return os.path.expanduser('~/.cache')
900
900
 
901
901
 
 
902
def _auto_user_id():
 
903
    """Calculate automatic user identification.
 
904
 
 
905
    Returns (realname, email).
 
906
 
 
907
    Only used when none is set in the environment or the id file.
 
908
 
 
909
    This previously used the FQDN as the default domain, but that can
 
910
    be very slow on machines where DNS is broken.  So now we simply
 
911
    use the hostname.
 
912
    """
 
913
    import socket
 
914
 
 
915
    if sys.platform == 'win32':
 
916
        name = win32utils.get_user_name_unicode()
 
917
        if name is None:
 
918
            raise errors.BzrError("Cannot autodetect user name.\n"
 
919
                                  "Please, set your name with command like:\n"
 
920
                                  'bzr whoami "Your Name <name@domain.com>"')
 
921
        host = win32utils.get_host_name_unicode()
 
922
        if host is None:
 
923
            host = socket.gethostname()
 
924
        return name, (name + '@' + host)
 
925
 
 
926
    try:
 
927
        import pwd
 
928
        uid = os.getuid()
 
929
        try:
 
930
            w = pwd.getpwuid(uid)
 
931
        except KeyError:
 
932
            raise errors.BzrCommandError('Unable to determine your name.  '
 
933
                'Please use "bzr whoami" to set it.')
 
934
 
 
935
        # we try utf-8 first, because on many variants (like Linux),
 
936
        # /etc/passwd "should" be in utf-8, and because it's unlikely to give
 
937
        # false positives.  (many users will have their user encoding set to
 
938
        # latin-1, which cannot raise UnicodeError.)
 
939
        try:
 
940
            gecos = w.pw_gecos.decode('utf-8')
 
941
            encoding = 'utf-8'
 
942
        except UnicodeError:
 
943
            try:
 
944
                encoding = osutils.get_user_encoding()
 
945
                gecos = w.pw_gecos.decode(encoding)
 
946
            except UnicodeError:
 
947
                raise errors.BzrCommandError('Unable to determine your name.  '
 
948
                   'Use "bzr whoami" to set it.')
 
949
        try:
 
950
            username = w.pw_name.decode(encoding)
 
951
        except UnicodeError:
 
952
            raise errors.BzrCommandError('Unable to determine your name.  '
 
953
                'Use "bzr whoami" to set it.')
 
954
 
 
955
        comma = gecos.find(',')
 
956
        if comma == -1:
 
957
            realname = gecos
 
958
        else:
 
959
            realname = gecos[:comma]
 
960
        if not realname:
 
961
            realname = username
 
962
 
 
963
    except ImportError:
 
964
        import getpass
 
965
        try:
 
966
            user_encoding = osutils.get_user_encoding()
 
967
            realname = username = getpass.getuser().decode(user_encoding)
 
968
        except UnicodeDecodeError:
 
969
            raise errors.BzrError("Can't decode username as %s." % \
 
970
                    user_encoding)
 
971
 
 
972
    return realname, (username + '@' + socket.gethostname())
 
973
 
 
974
 
902
975
def parse_username(username):
903
976
    """Parse e-mail username and return a (name, address) tuple."""
904
977
    match = re.match(r'(.*?)\s*<?([\w+.-]+@[\w+.-]+)>?', username)
990
1063
        """Save the config file, only tests should use it for now."""
991
1064
        conf_dir = os.path.dirname(self._filename)
992
1065
        ensure_config_dir_exists(conf_dir)
993
 
        f = file(self._filename, 'wb')
994
 
        try:
995
 
            self._get_config().write(f)
996
 
        finally:
997
 
            f.close()
 
1066
        self._get_config().write(file(self._filename, 'wb'))
998
1067
 
999
1068
    def _set_option(self, section_name, option_name, value):
1000
1069
        """Set an authentication configuration option"""
1448
1517
            return StringIO()
1449
1518
 
1450
1519
    def _get_configobj(self):
1451
 
        f = self._get_config_file()
1452
 
        try:
1453
 
            return ConfigObj(f, encoding='utf-8')
1454
 
        finally:
1455
 
            f.close()
 
1520
        return ConfigObj(self._get_config_file(), encoding='utf-8')
1456
1521
 
1457
1522
    def _set_configobj(self, configobj):
1458
1523
        out_file = StringIO()