~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/config.py

  • Committer: Robert Collins
  • Date: 2007-04-19 02:27:44 UTC
  • mto: This revision was merged to the branch mainline in revision 2426.
  • Revision ID: robertc@robertcollins.net-20070419022744-pfdqz42kp1wizh43
``make docs`` now creates a man page at ``man1/bzr.1`` fixing bug 107388.
(Robert Collins)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2007, 2008 Canonical Ltd
 
1
# Copyright (C) 2005, 2007 Canonical Ltd
2
2
#   Authors: Robert Collins <robert.collins@canonical.com>
3
3
#            and others
4
4
#
14
14
#
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
18
18
 
19
19
"""Configuration that affects the behaviour of Bazaar.
20
20
 
37
37
[/home/robertc/source]
38
38
recurse=False|True(default)
39
39
email= as above
40
 
check_signatures= as above
 
40
check_signatures= as above 
41
41
create_signatures= as above.
42
42
 
43
43
explanation of options
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 
49
49
                   present.
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
70
70
import errno
71
71
from fnmatch import fnmatch
72
72
import re
73
 
from cStringIO import StringIO
 
73
from StringIO import StringIO
74
74
 
75
75
import bzrlib
76
76
from bzrlib import (
77
 
    debug,
78
77
    errors,
79
 
    mail_client,
80
78
    osutils,
81
 
    registry,
82
79
    symbol_versioning,
83
 
    trace,
84
 
    ui,
85
80
    urlutils,
86
81
    win32utils,
87
82
    )
88
 
from bzrlib.util.configobj import configobj
 
83
import bzrlib.util.configobj.configobj as configobj
89
84
""")
90
85
 
 
86
from bzrlib.trace import mutter, warning
 
87
 
91
88
 
92
89
CHECK_IF_POSSIBLE=0
93
90
CHECK_ALWAYS=1
122
119
STORE_BRANCH = 3
123
120
STORE_GLOBAL = 4
124
121
 
125
 
_ConfigObj = None
126
 
def ConfigObj(*args, **kwargs):
127
 
    global _ConfigObj
128
 
    if _ConfigObj is None:
129
 
        class ConfigObj(configobj.ConfigObj):
130
 
 
131
 
            def get_bool(self, section, key):
132
 
                return self[section].as_bool(key)
133
 
 
134
 
            def get_value(self, section, name):
135
 
                # Try [] for the old DEFAULT section.
136
 
                if section == "DEFAULT":
137
 
                    try:
138
 
                        return self[name]
139
 
                    except KeyError:
140
 
                        pass
141
 
                return self[section][name]
142
 
        _ConfigObj = ConfigObj
143
 
    return _ConfigObj(*args, **kwargs)
 
122
 
 
123
class ConfigObj(configobj.ConfigObj):
 
124
 
 
125
    def get_bool(self, section, key):
 
126
        return self[section].as_bool(key)
 
127
 
 
128
    def get_value(self, section, name):
 
129
        # Try [] for the old DEFAULT section.
 
130
        if section == "DEFAULT":
 
131
            try:
 
132
                return self[name]
 
133
            except KeyError:
 
134
                pass
 
135
        return self[section][name]
144
136
 
145
137
 
146
138
class Config(object):
147
139
    """A configuration policy - what username, editor, gpg needs etc."""
148
140
 
149
 
    def __init__(self):
150
 
        super(Config, self).__init__()
151
 
 
152
141
    def get_editor(self):
153
142
        """Get the users pop up editor."""
154
143
        raise NotImplementedError
155
144
 
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
 
 
165
 
    def get_mail_client(self):
166
 
        """Get a mail client to use"""
167
 
        selected_client = self.get_user_option('mail_client')
168
 
        _registry = mail_client.mail_client_registry
169
 
        try:
170
 
            mail_client_class = _registry.get(selected_client)
171
 
        except KeyError:
172
 
            raise errors.UnknownMailClient(selected_client)
173
 
        return mail_client_class(self)
174
 
 
175
145
    def _get_signature_checking(self):
176
146
        """Template method to override signature checking policy."""
177
147
 
186
156
        """Get a generic option - no special process, no default."""
187
157
        return self._get_user_option(option_name)
188
158
 
189
 
    def get_user_option_as_bool(self, option_name):
190
 
        """Get a generic option as a boolean - no special process, no default.
191
 
 
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.
194
 
        """
195
 
        s = self._get_user_option(option_name)
196
 
        return ui.bool_from_string(s)
197
 
 
198
 
    def get_user_option_as_list(self, option_name):
199
 
        """Get a generic option as a list - no special process, no default.
200
 
 
201
 
        :return None if the option doesn't exist. Returns the value as a list
202
 
            otherwise.
203
 
        """
204
 
        l = self._get_user_option(option_name)
205
 
        if isinstance(l, (str, unicode)):
206
 
            # A single value, most probably the user forgot the final ','
207
 
            l = [l]
208
 
        return l
209
 
 
210
159
    def gpg_signing_command(self):
211
160
        """What program should be used to sign signatures?"""
212
161
        result = self._gpg_signing_command()
229
178
        """See log_format()."""
230
179
        return None
231
180
 
 
181
    def __init__(self):
 
182
        super(Config, self).__init__()
 
183
 
232
184
    def post_commit(self):
233
185
        """An ordered list of python functions to call.
234
186
 
246
198
 
247
199
    def username(self):
248
200
        """Return email-style username.
249
 
 
 
201
    
250
202
        Something similar to 'Martin Pool <mbp@sourcefrog.net>'
251
 
 
 
203
        
252
204
        $BZR_EMAIL can be set to override this (as well as the
253
205
        deprecated $BZREMAIL), then
254
206
        the concrete policy type is checked, and finally
255
207
        $EMAIL is examined.
256
208
        If none is found, a reasonable default is (hopefully)
257
209
        created.
258
 
 
 
210
    
259
211
        TODO: Check it's reasonably well-formed.
260
212
        """
261
213
        v = os.environ.get('BZR_EMAIL')
262
214
        if v:
263
 
            return v.decode(osutils.get_user_encoding())
264
 
 
 
215
            return v.decode(bzrlib.user_encoding)
 
216
        v = os.environ.get('BZREMAIL')
 
217
        if v:
 
218
            warning('BZREMAIL is deprecated in favor of BZR_EMAIL. Please update your configuration.')
 
219
            return v.decode(bzrlib.user_encoding)
 
220
    
265
221
        v = self._get_user_id()
266
222
        if v:
267
223
            return v
268
 
 
 
224
        
269
225
        v = os.environ.get('EMAIL')
270
226
        if v:
271
 
            return v.decode(osutils.get_user_encoding())
 
227
            return v.decode(bzrlib.user_encoding)
272
228
 
273
229
        name, email = _auto_user_id()
274
230
        if name:
296
252
        if policy is None:
297
253
            policy = self._get_signature_checking()
298
254
            if policy is not None:
299
 
                trace.warning("Please use create_signatures,"
300
 
                              " not check_signatures to set signing policy.")
 
255
                warning("Please use create_signatures, not check_signatures "
 
256
                        "to set signing policy.")
301
257
            if policy == CHECK_ALWAYS:
302
258
                return True
303
259
        elif policy == SIGN_ALWAYS:
316
272
    def _get_nickname(self):
317
273
        return None
318
274
 
319
 
    def get_bzr_remote_path(self):
320
 
        try:
321
 
            return os.environ['BZR_REMOTE_PATH']
322
 
        except KeyError:
323
 
            path = self.get_user_option("bzr_remote_path")
324
 
            if path is None:
325
 
                path = 'bzr'
326
 
            return path
327
 
 
328
 
    def suppress_warning(self, warning):
329
 
        """Should the warning be suppressed or emitted.
330
 
 
331
 
        :param warning: The name of the warning being tested.
332
 
 
333
 
        :returns: True if the warning should be suppressed, False otherwise.
334
 
        """
335
 
        warnings = self.get_user_option_as_list('suppress_warnings')
336
 
        if warnings is None or warning not in warnings:
337
 
            return False
338
 
        else:
339
 
            return True
340
 
 
341
275
 
342
276
class IniBasedConfig(Config):
343
277
    """A configuration policy that draws from ini files."""
344
278
 
345
 
    def __init__(self, get_filename):
346
 
        super(IniBasedConfig, self).__init__()
347
 
        self._get_filename = get_filename
348
 
        self._parser = None
349
 
 
350
279
    def _get_parser(self, file=None):
351
280
        if self._parser is not None:
352
281
            return self._parser
380
309
        """Return the policy for the given (section, option_name) pair."""
381
310
        return POLICY_NONE
382
311
 
383
 
    def _get_change_editor(self):
384
 
        return self.get_user_option('change_editor')
385
 
 
386
312
    def _get_signature_checking(self):
387
313
        """See Config._get_signature_checking."""
388
314
        policy = self._get_user_option('check_signatures')
432
358
        """See Config.log_format."""
433
359
        return self._get_user_option('log_format')
434
360
 
 
361
    def __init__(self, get_filename):
 
362
        super(IniBasedConfig, self).__init__()
 
363
        self._get_filename = get_filename
 
364
        self._parser = None
 
365
        
435
366
    def _post_commit(self):
436
367
        """See Config.post_commit."""
437
368
        return self._get_user_option('post_commit')
460
391
 
461
392
    def _get_alias(self, value):
462
393
        try:
463
 
            return self._get_parser().get_value("ALIASES",
 
394
            return self._get_parser().get_value("ALIASES", 
464
395
                                                value)
465
396
        except KeyError:
466
397
            pass
480
411
 
481
412
    def set_user_option(self, option, value):
482
413
        """Save option and its value in the configuration."""
483
 
        self._set_option(option, value, 'DEFAULT')
484
 
 
485
 
    def get_aliases(self):
486
 
        """Return the aliases section."""
487
 
        if 'ALIASES' in self._get_parser():
488
 
            return self._get_parser()['ALIASES']
489
 
        else:
490
 
            return {}
491
 
 
492
 
    def set_alias(self, alias_name, alias_command):
493
 
        """Save the alias in the configuration."""
494
 
        self._set_option(alias_name, alias_command, 'ALIASES')
495
 
 
496
 
    def unset_alias(self, alias_name):
497
 
        """Unset an existing alias."""
498
 
        aliases = self._get_parser().get('ALIASES')
499
 
        if not aliases or alias_name not in aliases:
500
 
            raise errors.NoSuchAlias(alias_name)
501
 
        del aliases[alias_name]
502
 
        self._write_config_file()
503
 
 
504
 
    def _set_option(self, option, value, section):
505
414
        # FIXME: RBC 20051029 This should refresh the parser and also take a
506
415
        # file lock on bazaar.conf.
507
416
        conf_dir = os.path.dirname(self._get_filename())
508
417
        ensure_config_dir_exists(conf_dir)
509
 
        self._get_parser().setdefault(section, {})[option] = value
510
 
        self._write_config_file()
511
 
 
512
 
    def _write_config_file(self):
 
418
        if 'DEFAULT' not in self._get_parser():
 
419
            self._get_parser()['DEFAULT'] = {}
 
420
        self._get_parser()['DEFAULT'][option] = value
513
421
        f = open(self._get_filename(), 'wb')
514
422
        self._get_parser().write(f)
515
423
        f.close()
520
428
 
521
429
    def __init__(self, location):
522
430
        name_generator = locations_config_filename
523
 
        if (not os.path.exists(name_generator()) and
 
431
        if (not os.path.exists(name_generator()) and 
524
432
                os.path.exists(branches_config_filename())):
525
433
            if sys.platform == 'win32':
526
 
                trace.warning('Please rename %s to %s'
527
 
                              % (branches_config_filename(),
528
 
                                 locations_config_filename()))
 
434
                warning('Please rename %s to %s' 
 
435
                         % (branches_config_filename(),
 
436
                            locations_config_filename()))
529
437
            else:
530
 
                trace.warning('Please rename ~/.bazaar/branches.conf'
531
 
                              ' to ~/.bazaar/locations.conf')
 
438
                warning('Please rename ~/.bazaar/branches.conf'
 
439
                        ' to ~/.bazaar/locations.conf')
532
440
            name_generator = branches_config_filename
533
441
        super(LocationConfig, self).__init__(name_generator)
534
442
        # local file locations are looked up by local path, rather than
633
541
 
634
542
    def set_user_option(self, option, value, store=STORE_LOCATION):
635
543
        """Save option and its value in the configuration."""
636
 
        if store not in [STORE_LOCATION,
 
544
        assert store in [STORE_LOCATION,
637
545
                         STORE_LOCATION_NORECURSE,
638
 
                         STORE_LOCATION_APPENDPATH]:
639
 
            raise ValueError('bad storage policy %r for %r' %
640
 
                (store, option))
 
546
                         STORE_LOCATION_APPENDPATH], 'bad storage policy'
641
547
        # FIXME: RBC 20051029 This should refresh the parser and also take a
642
548
        # file lock on locations.conf.
643
549
        conf_dir = os.path.dirname(self._get_filename())
688
594
 
689
595
    def _get_safe_value(self, option_name):
690
596
        """This variant of get_best_value never returns untrusted values.
691
 
 
 
597
        
692
598
        It does not return values from the branch data, because the branch may
693
599
        not be controlled by the user.
694
600
 
703
609
 
704
610
    def _get_user_id(self):
705
611
        """Return the full user id for the branch.
706
 
 
707
 
        e.g. "John Hacker <jhacker@example.com>"
 
612
    
 
613
        e.g. "John Hacker <jhacker@foo.org>"
708
614
        This is looked up in the email controlfile for the branch.
709
615
        """
710
616
        try:
711
 
            return (self.branch._transport.get_bytes("email")
712
 
                    .decode(osutils.get_user_encoding())
 
617
            return (self.branch.control_files.get_utf8("email") 
 
618
                    .read()
 
619
                    .decode(bzrlib.user_encoding)
713
620
                    .rstrip("\r\n"))
714
621
        except errors.NoSuchFile, e:
715
622
            pass
716
 
 
 
623
        
717
624
        return self._get_best_value('_get_user_id')
718
625
 
719
 
    def _get_change_editor(self):
720
 
        return self._get_best_value('_get_change_editor')
721
 
 
722
626
    def _get_signature_checking(self):
723
627
        """See Config._get_signature_checking."""
724
628
        return self._get_best_value('_get_signature_checking')
735
639
                return value
736
640
        return None
737
641
 
738
 
    def set_user_option(self, name, value, store=STORE_BRANCH,
739
 
        warn_masked=False):
 
642
    def set_user_option(self, name, value, store=STORE_BRANCH):
740
643
        if store == STORE_BRANCH:
741
644
            self._get_branch_data_config().set_option(value, name)
742
645
        elif store == STORE_GLOBAL:
743
646
            self._get_global_config().set_user_option(name, value)
744
647
        else:
745
648
            self._get_location_config().set_user_option(name, value, store)
746
 
        if not warn_masked:
747
 
            return
748
 
        if store in (STORE_GLOBAL, STORE_BRANCH):
749
 
            mask_value = self._get_location_config().get_user_option(name)
750
 
            if mask_value is not None:
751
 
                trace.warning('Value "%s" is masked by "%s" from'
752
 
                              ' locations.conf', value, mask_value)
753
 
            else:
754
 
                if store == STORE_GLOBAL:
755
 
                    branch_config = self._get_branch_data_config()
756
 
                    mask_value = branch_config.get_user_option(name)
757
 
                    if mask_value is not None:
758
 
                        trace.warning('Value "%s" is masked by "%s" from'
759
 
                                      ' branch.conf', value, mask_value)
760
649
 
761
650
    def _gpg_signing_command(self):
762
651
        """See Config.gpg_signing_command."""
763
652
        return self._get_safe_value('_gpg_signing_command')
764
 
 
 
653
        
765
654
    def __init__(self, branch):
766
655
        super(BranchConfig, self).__init__()
767
656
        self._location_config = None
768
657
        self._branch_data_config = None
769
658
        self._global_config = None
770
659
        self.branch = branch
771
 
        self.option_sources = (self._get_location_config,
 
660
        self.option_sources = (self._get_location_config, 
772
661
                               self._get_branch_data_config,
773
662
                               self._get_global_config)
774
663
 
806
695
        if sys.platform == 'win32':
807
696
            parent_dir = os.path.dirname(path)
808
697
            if not os.path.isdir(parent_dir):
809
 
                trace.mutter('creating config parent directory: %r', parent_dir)
 
698
                mutter('creating config parent directory: %r', parent_dir)
810
699
            os.mkdir(parent_dir)
811
 
        trace.mutter('creating config directory: %r', path)
 
700
        mutter('creating config directory: %r', path)
812
701
        os.mkdir(path)
813
702
 
814
703
 
816
705
    """Return per-user configuration directory.
817
706
 
818
707
    By default this is ~/.bazaar/
819
 
 
 
708
    
820
709
    TODO: Global option --config-dir to override this.
821
710
    """
822
711
    base = os.environ.get('BZR_HOME', None)
826
715
        if base is None:
827
716
            base = os.environ.get('HOME', None)
828
717
        if base is None:
829
 
            raise errors.BzrError('You must have one of BZR_HOME, APPDATA,'
830
 
                                  ' or HOME set')
 
718
            raise errors.BzrError('You must have one of BZR_HOME, APPDATA, or HOME set')
831
719
        return osutils.pathjoin(base, 'bazaar', '2.0')
832
720
    else:
833
721
        # cygwin, linux, and darwin all have a $HOME directory
851
739
    return osutils.pathjoin(config_dir(), 'locations.conf')
852
740
 
853
741
 
854
 
def authentication_config_filename():
855
 
    """Return per-user authentication ini file filename."""
856
 
    return osutils.pathjoin(config_dir(), 'authentication.conf')
857
 
 
858
 
 
859
742
def user_ignore_config_filename():
860
743
    """Return the user default ignore filename"""
861
744
    return osutils.pathjoin(config_dir(), 'ignore')
862
745
 
863
746
 
864
 
def crash_dir():
865
 
    """Return the directory name to store crash files.
866
 
 
867
 
    This doesn't implicitly create it.
868
 
 
869
 
    On Windows it's in the config directory; elsewhere in the XDG cache directory.
870
 
    """
871
 
    if sys.platform == 'win32':
872
 
        return osutils.pathjoin(config_dir(), 'Crash')
873
 
    else:
874
 
        return osutils.pathjoin(xdg_cache_dir(), 'crash')
875
 
 
876
 
 
877
 
def xdg_cache_dir():
878
 
    # See http://standards.freedesktop.org/basedir-spec/latest/ar01s03.html
879
 
    # Possibly this should be different on Windows?
880
 
    e = os.environ.get('XDG_CACHE_DIR', None)
881
 
    if e:
882
 
        return e
883
 
    else:
884
 
        return os.path.expanduser('~/.cache')
885
 
 
886
 
 
887
747
def _auto_user_id():
888
748
    """Calculate automatic user identification.
889
749
 
911
771
    try:
912
772
        import pwd
913
773
        uid = os.getuid()
914
 
        try:
915
 
            w = pwd.getpwuid(uid)
916
 
        except KeyError:
917
 
            raise errors.BzrCommandError('Unable to determine your name.  '
918
 
                'Please use "bzr whoami" to set it.')
 
774
        w = pwd.getpwuid(uid)
919
775
 
920
776
        # we try utf-8 first, because on many variants (like Linux),
921
777
        # /etc/passwd "should" be in utf-8, and because it's unlikely to give
926
782
            encoding = 'utf-8'
927
783
        except UnicodeError:
928
784
            try:
929
 
                encoding = osutils.get_user_encoding()
930
 
                gecos = w.pw_gecos.decode(encoding)
 
785
                gecos = w.pw_gecos.decode(bzrlib.user_encoding)
 
786
                encoding = bzrlib.user_encoding
931
787
            except UnicodeError:
932
788
                raise errors.BzrCommandError('Unable to determine your name.  '
933
789
                   'Use "bzr whoami" to set it.')
948
804
    except ImportError:
949
805
        import getpass
950
806
        try:
951
 
            user_encoding = osutils.get_user_encoding()
952
 
            realname = username = getpass.getuser().decode(user_encoding)
 
807
            realname = username = getpass.getuser().decode(bzrlib.user_encoding)
953
808
        except UnicodeDecodeError:
954
809
            raise errors.BzrError("Can't decode username as %s." % \
955
 
                    user_encoding)
 
810
                    bzrlib.user_encoding)
956
811
 
957
812
    return realname, (username + '@' + socket.gethostname())
958
813
 
959
814
 
960
 
def parse_username(username):
961
 
    """Parse e-mail username and return a (name, address) tuple."""
962
 
    match = re.match(r'(.*?)\s*<?([\w+.-]+@[\w+.-]+)>?', username)
963
 
    if match is None:
964
 
        return (username, '')
965
 
    else:
966
 
        return (match.group(1), match.group(2))
967
 
 
968
 
 
969
815
def extract_email_address(e):
970
816
    """Return just the address part of an email string.
971
 
 
972
 
    That is just the user@domain part, nothing else.
 
817
    
 
818
    That is just the user@domain part, nothing else. 
973
819
    This part is required to contain only ascii characters.
974
820
    If it can't be extracted, raises an error.
975
 
 
 
821
    
976
822
    >>> extract_email_address('Jane Tester <jane@test.com>')
977
823
    "jane@test.com"
978
824
    """
979
 
    name, email = parse_username(e)
980
 
    if not email:
 
825
    m = re.search(r'[\w+.-]+@[\w+.-]+', e)
 
826
    if not m:
981
827
        raise errors.NoEmailInUsername(e)
982
 
    return email
 
828
    return m.group(0)
983
829
 
984
830
 
985
831
class TreeConfig(IniBasedConfig):
986
832
    """Branch configuration data associated with its contents, not location"""
987
 
 
988
 
    # XXX: Really needs a better name, as this is not part of the tree! -- mbp 20080507
989
 
 
990
833
    def __init__(self, branch):
991
 
        self._config = branch._get_config()
992
834
        self.branch = branch
993
835
 
994
836
    def _get_parser(self, file=None):
995
837
        if file is not None:
996
838
            return IniBasedConfig._get_parser(file)
997
 
        return self._config._get_configobj()
 
839
        return self._get_config()
 
840
 
 
841
    def _get_config(self):
 
842
        try:
 
843
            obj = ConfigObj(self.branch.control_files.get('branch.conf'), 
 
844
                            encoding='utf-8')
 
845
        except errors.NoSuchFile:
 
846
            obj = ConfigObj(encoding='utf=8')
 
847
        return obj
998
848
 
999
849
    def get_option(self, name, section=None, default=None):
1000
850
        self.branch.lock_read()
1001
851
        try:
1002
 
            return self._config.get_option(name, section, default)
 
852
            obj = self._get_config()
 
853
            try:
 
854
                if section is not None:
 
855
                    obj[section]
 
856
                result = obj[name]
 
857
            except KeyError:
 
858
                result = default
1003
859
        finally:
1004
860
            self.branch.unlock()
 
861
        return result
1005
862
 
1006
863
    def set_option(self, value, name, section=None):
1007
864
        """Set a per-branch configuration option"""
1008
865
        self.branch.lock_write()
1009
866
        try:
1010
 
            self._config.set_option(value, name, section)
 
867
            cfg_obj = self._get_config()
 
868
            if section is None:
 
869
                obj = cfg_obj
 
870
            else:
 
871
                try:
 
872
                    obj = cfg_obj[section]
 
873
                except KeyError:
 
874
                    cfg_obj[section] = {}
 
875
                    obj = cfg_obj[section]
 
876
            obj[name] = value
 
877
            out_file = StringIO()
 
878
            cfg_obj.write(out_file)
 
879
            out_file.seek(0)
 
880
            self.branch.control_files.put('branch.conf', out_file)
1011
881
        finally:
1012
882
            self.branch.unlock()
1013
 
 
1014
 
 
1015
 
class AuthenticationConfig(object):
1016
 
    """The authentication configuration file based on a ini file.
1017
 
 
1018
 
    Implements the authentication.conf file described in
1019
 
    doc/developers/authentication-ring.txt.
1020
 
    """
1021
 
 
1022
 
    def __init__(self, _file=None):
1023
 
        self._config = None # The ConfigObj
1024
 
        if _file is None:
1025
 
            self._filename = authentication_config_filename()
1026
 
            self._input = self._filename = authentication_config_filename()
1027
 
        else:
1028
 
            # Tests can provide a string as _file
1029
 
            self._filename = None
1030
 
            self._input = _file
1031
 
 
1032
 
    def _get_config(self):
1033
 
        if self._config is not None:
1034
 
            return self._config
1035
 
        try:
1036
 
            # FIXME: Should we validate something here ? Includes: empty
1037
 
            # sections are useless, at least one of
1038
 
            # user/password/password_encoding should be defined, etc.
1039
 
 
1040
 
            # Note: the encoding below declares that the file itself is utf-8
1041
 
            # encoded, but the values in the ConfigObj are always Unicode.
1042
 
            self._config = ConfigObj(self._input, encoding='utf-8')
1043
 
        except configobj.ConfigObjError, e:
1044
 
            raise errors.ParseConfigError(e.errors, e.config.filename)
1045
 
        return self._config
1046
 
 
1047
 
    def _save(self):
1048
 
        """Save the config file, only tests should use it for now."""
1049
 
        conf_dir = os.path.dirname(self._filename)
1050
 
        ensure_config_dir_exists(conf_dir)
1051
 
        self._get_config().write(file(self._filename, 'wb'))
1052
 
 
1053
 
    def _set_option(self, section_name, option_name, value):
1054
 
        """Set an authentication configuration option"""
1055
 
        conf = self._get_config()
1056
 
        section = conf.get(section_name)
1057
 
        if section is None:
1058
 
            conf[section] = {}
1059
 
            section = conf[section]
1060
 
        section[option_name] = value
1061
 
        self._save()
1062
 
 
1063
 
    def get_credentials(self, scheme, host, port=None, user=None, path=None, 
1064
 
                        realm=None):
1065
 
        """Returns the matching credentials from authentication.conf file.
1066
 
 
1067
 
        :param scheme: protocol
1068
 
 
1069
 
        :param host: the server address
1070
 
 
1071
 
        :param port: the associated port (optional)
1072
 
 
1073
 
        :param user: login (optional)
1074
 
 
1075
 
        :param path: the absolute path on the server (optional)
1076
 
        
1077
 
        :param realm: the http authentication realm (optional)
1078
 
 
1079
 
        :return: A dict containing the matching credentials or None.
1080
 
           This includes:
1081
 
           - name: the section name of the credentials in the
1082
 
             authentication.conf file,
1083
 
           - user: can't be different from the provided user if any,
1084
 
           - scheme: the server protocol,
1085
 
           - host: the server address,
1086
 
           - port: the server port (can be None),
1087
 
           - path: the absolute server path (can be None),
1088
 
           - realm: the http specific authentication realm (can be None),
1089
 
           - password: the decoded password, could be None if the credential
1090
 
             defines only the user
1091
 
           - verify_certificates: https specific, True if the server
1092
 
             certificate should be verified, False otherwise.
1093
 
        """
1094
 
        credentials = None
1095
 
        for auth_def_name, auth_def in self._get_config().items():
1096
 
            if type(auth_def) is not configobj.Section:
1097
 
                raise ValueError("%s defined outside a section" % auth_def_name)
1098
 
 
1099
 
            a_scheme, a_host, a_user, a_path = map(
1100
 
                auth_def.get, ['scheme', 'host', 'user', 'path'])
1101
 
 
1102
 
            try:
1103
 
                a_port = auth_def.as_int('port')
1104
 
            except KeyError:
1105
 
                a_port = None
1106
 
            except ValueError:
1107
 
                raise ValueError("'port' not numeric in %s" % auth_def_name)
1108
 
            try:
1109
 
                a_verify_certificates = auth_def.as_bool('verify_certificates')
1110
 
            except KeyError:
1111
 
                a_verify_certificates = True
1112
 
            except ValueError:
1113
 
                raise ValueError(
1114
 
                    "'verify_certificates' not boolean in %s" % auth_def_name)
1115
 
 
1116
 
            # Attempt matching
1117
 
            if a_scheme is not None and scheme != a_scheme:
1118
 
                continue
1119
 
            if a_host is not None:
1120
 
                if not (host == a_host
1121
 
                        or (a_host.startswith('.') and host.endswith(a_host))):
1122
 
                    continue
1123
 
            if a_port is not None and port != a_port:
1124
 
                continue
1125
 
            if (a_path is not None and path is not None
1126
 
                and not path.startswith(a_path)):
1127
 
                continue
1128
 
            if (a_user is not None and user is not None
1129
 
                and a_user != user):
1130
 
                # Never contradict the caller about the user to be used
1131
 
                continue
1132
 
            if a_user is None:
1133
 
                # Can't find a user
1134
 
                continue
1135
 
            # Prepare a credentials dictionary with additional keys
1136
 
            # for the credential providers
1137
 
            credentials = dict(name=auth_def_name,
1138
 
                               user=a_user,
1139
 
                               scheme=a_scheme,
1140
 
                               host=host,
1141
 
                               port=port,
1142
 
                               path=path,
1143
 
                               realm=realm,
1144
 
                               password=auth_def.get('password', None),
1145
 
                               verify_certificates=a_verify_certificates)
1146
 
            # Decode the password in the credentials (or get one)
1147
 
            self.decode_password(credentials,
1148
 
                                 auth_def.get('password_encoding', None))
1149
 
            if 'auth' in debug.debug_flags:
1150
 
                trace.mutter("Using authentication section: %r", auth_def_name)
1151
 
            break
1152
 
 
1153
 
        if credentials is None:
1154
 
            # No credentials were found in authentication.conf, try the fallback
1155
 
            # credentials stores.
1156
 
            credentials = credential_store_registry.get_fallback_credentials(
1157
 
                scheme, host, port, user, path, realm)
1158
 
 
1159
 
        return credentials
1160
 
 
1161
 
    def set_credentials(self, name, host, user, scheme=None, password=None,
1162
 
                        port=None, path=None, verify_certificates=None,
1163
 
                        realm=None):
1164
 
        """Set authentication credentials for a host.
1165
 
 
1166
 
        Any existing credentials with matching scheme, host, port and path
1167
 
        will be deleted, regardless of name.
1168
 
 
1169
 
        :param name: An arbitrary name to describe this set of credentials.
1170
 
        :param host: Name of the host that accepts these credentials.
1171
 
        :param user: The username portion of these credentials.
1172
 
        :param scheme: The URL scheme (e.g. ssh, http) the credentials apply
1173
 
            to.
1174
 
        :param password: Password portion of these credentials.
1175
 
        :param port: The IP port on the host that these credentials apply to.
1176
 
        :param path: A filesystem path on the host that these credentials
1177
 
            apply to.
1178
 
        :param verify_certificates: On https, verify server certificates if
1179
 
            True.
1180
 
        :param realm: The http authentication realm (optional).
1181
 
        """
1182
 
        values = {'host': host, 'user': user}
1183
 
        if password is not None:
1184
 
            values['password'] = password
1185
 
        if scheme is not None:
1186
 
            values['scheme'] = scheme
1187
 
        if port is not None:
1188
 
            values['port'] = '%d' % port
1189
 
        if path is not None:
1190
 
            values['path'] = path
1191
 
        if verify_certificates is not None:
1192
 
            values['verify_certificates'] = str(verify_certificates)
1193
 
        if realm is not None:
1194
 
            values['realm'] = realm
1195
 
        config = self._get_config()
1196
 
        for_deletion = []
1197
 
        for section, existing_values in config.items():
1198
 
            for key in ('scheme', 'host', 'port', 'path', 'realm'):
1199
 
                if existing_values.get(key) != values.get(key):
1200
 
                    break
1201
 
            else:
1202
 
                del config[section]
1203
 
        config.update({name: values})
1204
 
        self._save()
1205
 
 
1206
 
    def get_user(self, scheme, host, port=None, realm=None, path=None,
1207
 
                 prompt=None, ask=False, default=None):
1208
 
        """Get a user from authentication file.
1209
 
 
1210
 
        :param scheme: protocol
1211
 
 
1212
 
        :param host: the server address
1213
 
 
1214
 
        :param port: the associated port (optional)
1215
 
 
1216
 
        :param realm: the realm sent by the server (optional)
1217
 
 
1218
 
        :param path: the absolute path on the server (optional)
1219
 
 
1220
 
        :param ask: Ask the user if there is no explicitly configured username 
1221
 
                    (optional)
1222
 
 
1223
 
        :param default: The username returned if none is defined (optional).
1224
 
 
1225
 
        :return: The found user.
1226
 
        """
1227
 
        credentials = self.get_credentials(scheme, host, port, user=None,
1228
 
                                           path=path, realm=realm)
1229
 
        if credentials is not None:
1230
 
            user = credentials['user']
1231
 
        else:
1232
 
            user = None
1233
 
        if user is None:
1234
 
            if ask:
1235
 
                if prompt is None:
1236
 
                    # Create a default prompt suitable for most cases
1237
 
                    prompt = scheme.upper() + ' %(host)s username'
1238
 
                # Special handling for optional fields in the prompt
1239
 
                if port is not None:
1240
 
                    prompt_host = '%s:%d' % (host, port)
1241
 
                else:
1242
 
                    prompt_host = host
1243
 
                user = ui.ui_factory.get_username(prompt, host=prompt_host)
1244
 
            else:
1245
 
                user = default
1246
 
        return user
1247
 
 
1248
 
    def get_password(self, scheme, host, user, port=None,
1249
 
                     realm=None, path=None, prompt=None):
1250
 
        """Get a password from authentication file or prompt the user for one.
1251
 
 
1252
 
        :param scheme: protocol
1253
 
 
1254
 
        :param host: the server address
1255
 
 
1256
 
        :param port: the associated port (optional)
1257
 
 
1258
 
        :param user: login
1259
 
 
1260
 
        :param realm: the realm sent by the server (optional)
1261
 
 
1262
 
        :param path: the absolute path on the server (optional)
1263
 
 
1264
 
        :return: The found password or the one entered by the user.
1265
 
        """
1266
 
        credentials = self.get_credentials(scheme, host, port, user, path,
1267
 
                                           realm)
1268
 
        if credentials is not None:
1269
 
            password = credentials['password']
1270
 
            if password is not None and scheme is 'ssh':
1271
 
                trace.warning('password ignored in section [%s],'
1272
 
                              ' use an ssh agent instead'
1273
 
                              % credentials['name'])
1274
 
                password = None
1275
 
        else:
1276
 
            password = None
1277
 
        # Prompt user only if we could't find a password
1278
 
        if password is None:
1279
 
            if prompt is None:
1280
 
                # Create a default prompt suitable for most cases
1281
 
                prompt = '%s' % scheme.upper() + ' %(user)s@%(host)s password'
1282
 
            # Special handling for optional fields in the prompt
1283
 
            if port is not None:
1284
 
                prompt_host = '%s:%d' % (host, port)
1285
 
            else:
1286
 
                prompt_host = host
1287
 
            password = ui.ui_factory.get_password(prompt,
1288
 
                                                  host=prompt_host, user=user)
1289
 
        return password
1290
 
 
1291
 
    def decode_password(self, credentials, encoding):
1292
 
        try:
1293
 
            cs = credential_store_registry.get_credential_store(encoding)
1294
 
        except KeyError:
1295
 
            raise ValueError('%r is not a known password_encoding' % encoding)
1296
 
        credentials['password'] = cs.decode_password(credentials)
1297
 
        return credentials
1298
 
 
1299
 
 
1300
 
class CredentialStoreRegistry(registry.Registry):
1301
 
    """A class that registers credential stores.
1302
 
 
1303
 
    A credential store provides access to credentials via the password_encoding
1304
 
    field in authentication.conf sections.
1305
 
 
1306
 
    Except for stores provided by bzr itself, most stores are expected to be
1307
 
    provided by plugins that will therefore use
1308
 
    register_lazy(password_encoding, module_name, member_name, help=help,
1309
 
    fallback=fallback) to install themselves.
1310
 
 
1311
 
    A fallback credential store is one that is queried if no credentials can be
1312
 
    found via authentication.conf.
1313
 
    """
1314
 
 
1315
 
    def get_credential_store(self, encoding=None):
1316
 
        cs = self.get(encoding)
1317
 
        if callable(cs):
1318
 
            cs = cs()
1319
 
        return cs
1320
 
 
1321
 
    def is_fallback(self, name):
1322
 
        """Check if the named credentials store should be used as fallback."""
1323
 
        return self.get_info(name)
1324
 
 
1325
 
    def get_fallback_credentials(self, scheme, host, port=None, user=None,
1326
 
                                 path=None, realm=None):
1327
 
        """Request credentials from all fallback credentials stores.
1328
 
 
1329
 
        The first credentials store that can provide credentials wins.
1330
 
        """
1331
 
        credentials = None
1332
 
        for name in self.keys():
1333
 
            if not self.is_fallback(name):
1334
 
                continue
1335
 
            cs = self.get_credential_store(name)
1336
 
            credentials = cs.get_credentials(scheme, host, port, user,
1337
 
                                             path, realm)
1338
 
            if credentials is not None:
1339
 
                # We found some credentials
1340
 
                break
1341
 
        return credentials
1342
 
 
1343
 
    def register(self, key, obj, help=None, override_existing=False,
1344
 
                 fallback=False):
1345
 
        """Register a new object to a name.
1346
 
 
1347
 
        :param key: This is the key to use to request the object later.
1348
 
        :param obj: The object to register.
1349
 
        :param help: Help text for this entry. This may be a string or
1350
 
                a callable. If it is a callable, it should take two
1351
 
                parameters (registry, key): this registry and the key that
1352
 
                the help was registered under.
1353
 
        :param override_existing: Raise KeyErorr if False and something has
1354
 
                already been registered for that key. If True, ignore if there
1355
 
                is an existing key (always register the new value).
1356
 
        :param fallback: Whether this credential store should be 
1357
 
                used as fallback.
1358
 
        """
1359
 
        return super(CredentialStoreRegistry,
1360
 
                     self).register(key, obj, help, info=fallback,
1361
 
                                    override_existing=override_existing)
1362
 
 
1363
 
    def register_lazy(self, key, module_name, member_name,
1364
 
                      help=None, override_existing=False,
1365
 
                      fallback=False):
1366
 
        """Register a new credential store to be loaded on request.
1367
 
 
1368
 
        :param module_name: The python path to the module. Such as 'os.path'.
1369
 
        :param member_name: The member of the module to return.  If empty or
1370
 
                None, get() will return the module itself.
1371
 
        :param help: Help text for this entry. This may be a string or
1372
 
                a callable.
1373
 
        :param override_existing: If True, replace the existing object
1374
 
                with the new one. If False, if there is already something
1375
 
                registered with the same key, raise a KeyError
1376
 
        :param fallback: Whether this credential store should be 
1377
 
                used as fallback.
1378
 
        """
1379
 
        return super(CredentialStoreRegistry, self).register_lazy(
1380
 
            key, module_name, member_name, help,
1381
 
            info=fallback, override_existing=override_existing)
1382
 
 
1383
 
 
1384
 
credential_store_registry = CredentialStoreRegistry()
1385
 
 
1386
 
 
1387
 
class CredentialStore(object):
1388
 
    """An abstract class to implement storage for credentials"""
1389
 
 
1390
 
    def decode_password(self, credentials):
1391
 
        """Returns a clear text password for the provided credentials."""
1392
 
        raise NotImplementedError(self.decode_password)
1393
 
 
1394
 
    def get_credentials(self, scheme, host, port=None, user=None, path=None,
1395
 
                        realm=None):
1396
 
        """Return the matching credentials from this credential store.
1397
 
 
1398
 
        This method is only called on fallback credential stores.
1399
 
        """
1400
 
        raise NotImplementedError(self.get_credentials)
1401
 
 
1402
 
 
1403
 
 
1404
 
class PlainTextCredentialStore(CredentialStore):
1405
 
    """Plain text credential store for the authentication.conf file."""
1406
 
 
1407
 
    def decode_password(self, credentials):
1408
 
        """See CredentialStore.decode_password."""
1409
 
        return credentials['password']
1410
 
 
1411
 
 
1412
 
credential_store_registry.register('plain', PlainTextCredentialStore,
1413
 
                                   help=PlainTextCredentialStore.__doc__)
1414
 
credential_store_registry.default_key = 'plain'
1415
 
 
1416
 
 
1417
 
class BzrDirConfig(object):
1418
 
 
1419
 
    def __init__(self, bzrdir):
1420
 
        self._bzrdir = bzrdir
1421
 
        self._config = bzrdir._get_config()
1422
 
 
1423
 
    def set_default_stack_on(self, value):
1424
 
        """Set the default stacking location.
1425
 
 
1426
 
        It may be set to a location, or None.
1427
 
 
1428
 
        This policy affects all branches contained by this bzrdir, except for
1429
 
        those under repositories.
1430
 
        """
1431
 
        if self._config is None:
1432
 
            raise errors.BzrError("Cannot set configuration in %s" % self._bzrdir)
1433
 
        if value is None:
1434
 
            self._config.set_option('', 'default_stack_on')
1435
 
        else:
1436
 
            self._config.set_option(value, 'default_stack_on')
1437
 
 
1438
 
    def get_default_stack_on(self):
1439
 
        """Return the default stacking location.
1440
 
 
1441
 
        This will either be a location, or None.
1442
 
 
1443
 
        This policy affects all branches contained by this bzrdir, except for
1444
 
        those under repositories.
1445
 
        """
1446
 
        if self._config is None:
1447
 
            return None
1448
 
        value = self._config.get_option('default_stack_on')
1449
 
        if value == '':
1450
 
            value = None
1451
 
        return value
1452
 
 
1453
 
 
1454
 
class TransportConfig(object):
1455
 
    """A Config that reads/writes a config file on a Transport.
1456
 
 
1457
 
    It is a low-level object that considers config data to be name/value pairs
1458
 
    that may be associated with a section.  Assigning meaning to the these
1459
 
    values is done at higher levels like TreeConfig.
1460
 
    """
1461
 
 
1462
 
    def __init__(self, transport, filename):
1463
 
        self._transport = transport
1464
 
        self._filename = filename
1465
 
 
1466
 
    def get_option(self, name, section=None, default=None):
1467
 
        """Return the value associated with a named option.
1468
 
 
1469
 
        :param name: The name of the value
1470
 
        :param section: The section the option is in (if any)
1471
 
        :param default: The value to return if the value is not set
1472
 
        :return: The value or default value
1473
 
        """
1474
 
        configobj = self._get_configobj()
1475
 
        if section is None:
1476
 
            section_obj = configobj
1477
 
        else:
1478
 
            try:
1479
 
                section_obj = configobj[section]
1480
 
            except KeyError:
1481
 
                return default
1482
 
        return section_obj.get(name, default)
1483
 
 
1484
 
    def set_option(self, value, name, section=None):
1485
 
        """Set the value associated with a named option.
1486
 
 
1487
 
        :param value: The value to set
1488
 
        :param name: The name of the value to set
1489
 
        :param section: The section the option is in (if any)
1490
 
        """
1491
 
        configobj = self._get_configobj()
1492
 
        if section is None:
1493
 
            configobj[name] = value
1494
 
        else:
1495
 
            configobj.setdefault(section, {})[name] = value
1496
 
        self._set_configobj(configobj)
1497
 
 
1498
 
    def _get_config_file(self):
1499
 
        try:
1500
 
            return StringIO(self._transport.get_bytes(self._filename))
1501
 
        except errors.NoSuchFile:
1502
 
            return StringIO()
1503
 
 
1504
 
    def _get_configobj(self):
1505
 
        return ConfigObj(self._get_config_file(), encoding='utf-8')
1506
 
 
1507
 
    def _set_configobj(self, configobj):
1508
 
        out_file = StringIO()
1509
 
        configobj.write(out_file)
1510
 
        out_file.seek(0)
1511
 
        self._transport.put_file(self._filename, out_file)