~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/errors.py

  • Committer: Andrew Bennetts
  • Date: 2011-07-11 02:06:18 UTC
  • mfrom: (6018 +trunk)
  • mto: This revision was merged to the branch mainline in revision 6020.
  • Revision ID: andrew.bennetts@canonical.com-20110711020618-gcjgoeb5azwjrnu6
Merge lp:bzr/2.4.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2013, 2016 Canonical Ltd
 
1
# Copyright (C) 2005-2011 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
17
17
"""Exceptions for bzr, and reporting of them.
18
18
"""
19
19
 
20
 
from __future__ import absolute_import
 
20
from bzrlib import (
 
21
    osutils,
 
22
    symbol_versioning,
 
23
    )
 
24
from bzrlib.patches import (
 
25
    MalformedHunkHeader,
 
26
    MalformedLine,
 
27
    MalformedPatchHeader,
 
28
    PatchConflict,
 
29
    PatchSyntax,
 
30
    )
 
31
 
21
32
 
22
33
# TODO: is there any value in providing the .args field used by standard
23
34
# python exceptions?   A list of values with no names seems less useful
95
106
                # __str__() should always return a 'str' object
96
107
                # never a 'unicode' object.
97
108
                return s
98
 
        except Exception, e:
99
 
            pass # just bind to 'e' for formatting below
100
 
        else:
101
 
            e = None
102
 
        return 'Unprintable exception %s: dict=%r, fmt=%r, error=%r' \
103
 
            % (self.__class__.__name__,
104
 
               self.__dict__,
105
 
               getattr(self, '_fmt', None),
106
 
               e)
 
109
        except (AttributeError, TypeError, NameError, ValueError, KeyError), e:
 
110
            return 'Unprintable exception %s: dict=%r, fmt=%r, error=%r' \
 
111
                % (self.__class__.__name__,
 
112
                   self.__dict__,
 
113
                   getattr(self, '_fmt', None),
 
114
                   e)
107
115
 
108
116
    def __unicode__(self):
109
117
        u = self._format()
132
140
        """Return format string for this exception or None"""
133
141
        fmt = getattr(self, '_fmt', None)
134
142
        if fmt is not None:
135
 
            from bzrlib.i18n import gettext
136
 
            return gettext(unicode(fmt)) # _fmt strings should be ascii
 
143
            return fmt
 
144
        fmt = getattr(self, '__doc__', None)
 
145
        if fmt is not None:
 
146
            symbol_versioning.warn("%s uses its docstring as a format, "
 
147
                    "it should use _fmt instead" % self.__class__.__name__,
 
148
                    DeprecationWarning)
 
149
            return fmt
 
150
        return 'Unprintable exception %s: dict=%r, fmt=%r' \
 
151
            % (self.__class__.__name__,
 
152
               self.__dict__,
 
153
               getattr(self, '_fmt', None),
 
154
               )
137
155
 
138
156
    def __eq__(self, other):
139
157
        if self.__class__ is not other.__class__:
152
170
    internal_error = True
153
171
 
154
172
 
 
173
class BzrNewError(BzrError):
 
174
    """Deprecated error base class."""
 
175
    # base classes should override the docstring with their human-
 
176
    # readable explanation
 
177
 
 
178
    def __init__(self, *args, **kwds):
 
179
        # XXX: Use the underlying BzrError to always generate the args
 
180
        # attribute if it doesn't exist.  We can't use super here, because
 
181
        # exceptions are old-style classes in python2.4 (but new in 2.5).
 
182
        # --bmc, 20060426
 
183
        symbol_versioning.warn('BzrNewError was deprecated in bzr 0.13; '
 
184
             'please convert %s to use BzrError instead'
 
185
             % self.__class__.__name__,
 
186
             DeprecationWarning,
 
187
             stacklevel=2)
 
188
        BzrError.__init__(self, *args)
 
189
        for key, value in kwds.items():
 
190
            setattr(self, key, value)
 
191
 
 
192
    def __str__(self):
 
193
        try:
 
194
            # __str__() should always return a 'str' object
 
195
            # never a 'unicode' object.
 
196
            s = self.__doc__ % self.__dict__
 
197
            if isinstance(s, unicode):
 
198
                return s.encode('utf8')
 
199
            return s
 
200
        except (TypeError, NameError, ValueError, KeyError), e:
 
201
            return 'Unprintable exception %s(%r): %r' \
 
202
                % (self.__class__.__name__,
 
203
                   self.__dict__, e)
 
204
 
 
205
 
155
206
class AlreadyBuilding(BzrError):
156
207
 
157
208
    _fmt = "The tree builder is already building a tree."
570
621
 
571
622
    _fmt = 'Unsupported protocol for url "%(path)s"%(extra)s'
572
623
 
573
 
    def __init__(self, url, extra=""):
 
624
    def __init__(self, url, extra):
574
625
        PathError.__init__(self, url, extra=extra)
575
626
 
576
627
 
700
751
       self.path = urlutils.unescape_for_display(branch.base, 'ascii')
701
752
 
702
753
 
703
 
class AlreadyControlDirError(PathError):
704
 
 
705
 
    _fmt = 'A control directory already exists: "%(path)s".'
706
 
 
707
 
 
708
754
class AlreadyBranchError(PathError):
709
755
 
710
756
    _fmt = 'Already a branch: "%(path)s".'
711
757
 
712
758
 
713
 
class InvalidBranchName(PathError):
714
 
 
715
 
    _fmt = "Invalid branch name: %(name)s"
716
 
 
717
 
    def __init__(self, name):
718
 
        BzrError.__init__(self)
719
 
        self.name = name
720
 
 
721
 
 
722
 
class ParentBranchExists(AlreadyBranchError):
723
 
 
724
 
    _fmt = 'Parent branch already exists: "%(path)s".'
725
 
 
726
 
 
727
759
class BranchExistsWithoutWorkingTree(PathError):
728
760
 
729
761
    _fmt = 'Directory contains a branch, but no working tree \
758
790
        self.path = bzrdir.transport.clone('..').base
759
791
 
760
792
 
 
793
class FileInWrongBranch(BzrError):
 
794
 
 
795
    _fmt = 'File "%(path)s" is not in branch %(branch_base)s.'
 
796
 
 
797
    # use PathNotChild instead
 
798
    @symbol_versioning.deprecated_method(symbol_versioning.deprecated_in((2, 3, 0)))
 
799
    def __init__(self, branch, path):
 
800
        BzrError.__init__(self)
 
801
        self.branch = branch
 
802
        self.branch_base = branch.base
 
803
        self.path = path
 
804
 
 
805
 
761
806
class UnsupportedFormatError(BzrError):
762
807
 
763
808
    _fmt = "Unsupported branch format: %(format)s\nPlease run 'bzr upgrade'"
782
827
        self.bzrdir = bzrdir_format
783
828
 
784
829
 
785
 
class ParseFormatError(BzrError):
786
 
 
787
 
    _fmt = "Parse error on line %(lineno)d of %(format)s format: %(line)s"
788
 
 
789
 
    def __init__(self, format, lineno, line, text):
790
 
        BzrError.__init__(self)
791
 
        self.format = format
792
 
        self.lineno = lineno
793
 
        self.line = line
794
 
        self.text = text
795
 
 
796
 
 
797
830
class IncompatibleRepositories(BzrError):
798
831
    """Report an error that two repositories are not compatible.
799
832
 
1188
1221
            self.extra = ''
1189
1222
 
1190
1223
 
 
1224
class HistoryMissing(BzrError):
 
1225
 
 
1226
    _fmt = "%(branch)s is missing %(object_type)s {%(object_id)s}"
 
1227
 
 
1228
 
1191
1229
class AppendRevisionsOnlyViolation(BzrError):
1192
1230
 
1193
1231
    _fmt = ('Operation denied because it would change the main history,'
1258
1296
            not_ancestor_id=not_ancestor_id)
1259
1297
 
1260
1298
 
 
1299
class AmbiguousBase(BzrError):
 
1300
 
 
1301
    def __init__(self, bases):
 
1302
        symbol_versioning.warn("BzrError AmbiguousBase has been deprecated "
 
1303
            "as of bzrlib 0.8.", DeprecationWarning, stacklevel=2)
 
1304
        msg = ("The correct base is unclear, because %s are all equally close"
 
1305
                % ", ".join(bases))
 
1306
        BzrError.__init__(self, msg)
 
1307
        self.bases = bases
 
1308
 
 
1309
 
1261
1310
class NoCommits(BranchError):
1262
1311
 
1263
1312
    _fmt = "Branch %(branch)s has no commits."
1523
1572
            problem we can raise the original error (value from sys.exc_info())
1524
1573
        """
1525
1574
        BzrError.__init__(self)
1526
 
        self.context = context
1527
1575
        self.reload_occurred = reload_occurred
1528
1576
        self.exc_info = exc_info
1529
1577
        self.orig_error = exc_info[1]
1611
1659
 
1612
1660
    def __init__(self, exc_info):
1613
1661
        import traceback
1614
 
        # GZ 2010-08-10: Cycle with exc_tb/exc_info affects at least one test
1615
1662
        self.exc_type, self.exc_value, self.exc_tb = exc_info
1616
1663
        self.exc_info = exc_info
1617
1664
        traceback_strings = traceback.format_exception(
1656
1703
    _fmt = "Connection closed: %(msg)s %(orig_error)s"
1657
1704
 
1658
1705
 
1659
 
class ConnectionTimeout(ConnectionError):
1660
 
 
1661
 
    _fmt = "Connection Timeout: %(msg)s%(orig_error)s"
1662
 
 
1663
 
 
1664
1706
class InvalidRange(TransportError):
1665
1707
 
1666
1708
    _fmt = "Invalid range access in %(path)s at %(offset)s: %(msg)s"
1695
1737
        InvalidHttpResponse.__init__(self, path, msg)
1696
1738
 
1697
1739
 
1698
 
class HttpBoundaryMissing(InvalidHttpResponse):
1699
 
    """A multipart response ends with no boundary marker.
1700
 
 
1701
 
    This is a special case caused by buggy proxies, described in
1702
 
    <https://bugs.launchpad.net/bzr/+bug/198646>.
1703
 
    """
1704
 
 
1705
 
    _fmt = "HTTP MIME Boundary missing for %(path)s: %(msg)s"
1706
 
 
1707
 
    def __init__(self, path, msg):
1708
 
        InvalidHttpResponse.__init__(self, path, msg)
1709
 
 
1710
 
 
1711
1740
class InvalidHttpContentType(InvalidHttpResponse):
1712
1741
 
1713
1742
    _fmt = 'Invalid http Content-type "%(ctype)s" for %(path)s: %(msg)s'
1760
1789
        self.errors = '\n'.join(e.msg for e in errors)
1761
1790
 
1762
1791
 
1763
 
class ConfigOptionValueError(BzrError):
1764
 
 
1765
 
    _fmt = ('Bad value "%(value)s" for option "%(name)s".\n'
1766
 
            'See ``bzr help %(name)s``')
1767
 
 
1768
 
    def __init__(self, name, value):
1769
 
        BzrError.__init__(self, name=name, value=value)
1770
 
 
1771
 
 
1772
1792
class NoEmailInUsername(BzrError):
1773
1793
 
1774
1794
    _fmt = "%(username)r does not seem to contain a reasonable email address"
1931
1951
        self.prefix = prefix
1932
1952
 
1933
1953
 
1934
 
class MalformedTransform(InternalBzrError):
 
1954
class MalformedTransform(BzrError):
1935
1955
 
1936
1956
    _fmt = "Tree transform is malformed %(conflicts)r"
1937
1957
 
2031
2051
        BzrMoveFailedError.__init__(self, from_path, to_path, extra)
2032
2052
 
2033
2053
 
 
2054
class BzrRemoveChangedFilesError(BzrError):
 
2055
    """Used when user is trying to remove changed files."""
 
2056
 
 
2057
    _fmt = ("Can't safely remove modified or unknown files:\n"
 
2058
        "%(changes_as_text)s"
 
2059
        "Use --keep to not delete them, or --force to delete them regardless.")
 
2060
 
 
2061
    def __init__(self, tree_delta):
 
2062
        symbol_versioning.warn(symbol_versioning.deprecated_in((2, 3, 0)) %
 
2063
            "BzrRemoveChangedFilesError", DeprecationWarning, stacklevel=2)
 
2064
        BzrError.__init__(self)
 
2065
        self.changes_as_text = tree_delta.get_changes_as_text()
 
2066
        #self.paths_as_string = '\n'.join(changed_files)
 
2067
        #self.paths_as_string = '\n'.join([quotefn(p) for p in changed_files])
 
2068
 
 
2069
 
2034
2070
class BzrBadParameterNotString(BzrBadParameter):
2035
2071
 
2036
2072
    _fmt = "Parameter %(param)s is not a string or unicode string."
2292
2328
    """
2293
2329
 
2294
2330
 
2295
 
class GhostTagsNotSupported(BzrError):
2296
 
 
2297
 
    _fmt = "Ghost tags not supported by format %(format)r."
2298
 
 
2299
 
    def __init__(self, format):
2300
 
        self.format = format
2301
 
 
2302
 
 
2303
2331
class BinaryFile(BzrError):
2304
2332
 
2305
2333
    _fmt = "File is binary but should be text."
2735
2763
    _fmt = "Container has multiple records with the same name: %(name)s"
2736
2764
 
2737
2765
    def __init__(self, name):
2738
 
        self.name = name.decode("utf-8")
 
2766
        self.name = name
2739
2767
 
2740
2768
 
2741
2769
class NoDestinationAddress(InternalBzrError):
2769
2797
    _fmt = "No mail-to address (--mail-to) or output (-o) specified."
2770
2798
 
2771
2799
 
 
2800
class UnknownMailClient(BzrError):
 
2801
 
 
2802
    _fmt = "Unknown mail client: %(mail_client)s"
 
2803
 
 
2804
    def __init__(self, mail_client):
 
2805
        BzrError.__init__(self, mail_client=mail_client)
 
2806
 
 
2807
 
2772
2808
class MailClientNotFound(BzrError):
2773
2809
 
2774
2810
    _fmt = "Unable to find mail client with the following names:"\
2885
2921
        BzrError.__init__(self, tree=tree, display_url=display_url, more=more)
2886
2922
 
2887
2923
 
2888
 
class StoringUncommittedNotSupported(BzrError):
2889
 
 
2890
 
    _fmt = ('Branch "%(display_url)s" does not support storing uncommitted'
2891
 
            ' changes.')
2892
 
 
2893
 
    def __init__(self, branch):
2894
 
        import bzrlib.urlutils as urlutils
2895
 
        user_url = getattr(branch, "user_url", None)
2896
 
        if user_url is None:
2897
 
            display_url = str(branch)
2898
 
        else:
2899
 
            display_url = urlutils.unescape_for_display(user_url, 'ascii')
2900
 
        BzrError.__init__(self, branch=branch, display_url=display_url)
2901
 
 
2902
 
 
2903
2924
class ShelvedChanges(UncommittedChanges):
2904
2925
 
2905
2926
    _fmt = ('Working tree "%(display_url)s" has shelved changes'
2977
2998
        from bzrlib.osutils import get_user_encoding
2978
2999
        self.path = path
2979
3000
        self.kind = kind
2980
 
        self.user_encoding = get_user_encoding()
 
3001
        self.user_encoding = osutils.get_user_encoding()
2981
3002
 
2982
3003
 
2983
3004
class NoSuchConfig(BzrError):
3044
3065
        BzrError.__init__(self, unknowns_str=", ".join(unknowns))
3045
3066
 
3046
3067
 
 
3068
class HookFailed(BzrError):
 
3069
    """Raised when a pre_change_branch_tip hook function fails anything other
 
3070
    than TipChangeRejected.
 
3071
 
 
3072
    Note that this exception is no longer raised, and the import is only left
 
3073
    to be nice to code which might catch it in a plugin.
 
3074
    """
 
3075
 
 
3076
    _fmt = ("Hook '%(hook_name)s' during %(hook_stage)s failed:\n"
 
3077
            "%(traceback_text)s%(exc_value)s")
 
3078
 
 
3079
    def __init__(self, hook_stage, hook_name, exc_info, warn=True):
 
3080
        if warn:
 
3081
            symbol_versioning.warn("BzrError HookFailed has been deprecated "
 
3082
                "as of bzrlib 2.1.", DeprecationWarning, stacklevel=2)
 
3083
        import traceback
 
3084
        self.hook_stage = hook_stage
 
3085
        self.hook_name = hook_name
 
3086
        self.exc_info = exc_info
 
3087
        self.exc_type = exc_info[0]
 
3088
        self.exc_value = exc_info[1]
 
3089
        self.exc_tb = exc_info[2]
 
3090
        self.traceback_text = ''.join(traceback.format_tb(self.exc_tb))
 
3091
 
 
3092
 
3047
3093
class TipChangeRejected(BzrError):
3048
3094
    """A pre_change_branch_tip hook function may raise this to cleanly and
3049
3095
    explicitly abort a change to a branch tip.
3242
3288
 
3243
3289
class ExpandingUnknownOption(BzrError):
3244
3290
 
3245
 
    _fmt = 'Option "%(name)s" is not defined while expanding "%(string)s".'
 
3291
    _fmt = 'Option %(name)s is not defined while expanding "%(string)s".'
3246
3292
 
3247
3293
    def __init__(self, name, string):
3248
3294
        self.name = name
3249
3295
        self.string = string
3250
3296
 
3251
3297
 
3252
 
class IllegalOptionName(BzrError):
3253
 
 
3254
 
    _fmt = 'Option "%(name)s" is not allowed.'
3255
 
 
3256
 
    def __init__(self, name):
3257
 
        self.name = name
3258
 
 
3259
 
 
3260
3298
class NoCompatibleInter(BzrError):
3261
3299
 
3262
3300
    _fmt = ('No compatible object available for operations from %(source)r '
3265
3303
    def __init__(self, source, target):
3266
3304
        self.source = source
3267
3305
        self.target = target
3268
 
 
3269
 
 
3270
 
class HpssVfsRequestNotAllowed(BzrError):
3271
 
 
3272
 
    _fmt = ("VFS requests over the smart server are not allowed. Encountered: "
3273
 
            "%(method)s, %(arguments)s.")
3274
 
 
3275
 
    def __init__(self, method, arguments):
3276
 
        self.method = method
3277
 
        self.arguments = arguments
3278
 
 
3279
 
 
3280
 
class UnsupportedKindChange(BzrError):
3281
 
 
3282
 
    _fmt = ("Kind change from %(from_kind)s to %(to_kind)s for "
3283
 
            "%(path)s not supported by format %(format)r")
3284
 
 
3285
 
    def __init__(self, path, from_kind, to_kind, format):
3286
 
        self.path = path
3287
 
        self.from_kind = from_kind
3288
 
        self.to_kind = to_kind
3289
 
        self.format = format
3290
 
 
3291
 
 
3292
 
class MissingFeature(BzrError):
3293
 
 
3294
 
    _fmt = ("Missing feature %(feature)s not provided by this "
3295
 
            "version of Bazaar or any plugin.")
3296
 
 
3297
 
    def __init__(self, feature):
3298
 
        self.feature = feature
3299
 
 
3300
 
 
3301
 
class PatchSyntax(BzrError):
3302
 
    """Base class for patch syntax errors."""
3303
 
 
3304
 
 
3305
 
class BinaryFiles(BzrError):
3306
 
 
3307
 
    _fmt = 'Binary files section encountered.'
3308
 
 
3309
 
    def __init__(self, orig_name, mod_name):
3310
 
        self.orig_name = orig_name
3311
 
        self.mod_name = mod_name
3312
 
 
3313
 
 
3314
 
class MalformedPatchHeader(PatchSyntax):
3315
 
 
3316
 
    _fmt = "Malformed patch header.  %(desc)s\n%(line)r"
3317
 
 
3318
 
    def __init__(self, desc, line):
3319
 
        self.desc = desc
3320
 
        self.line = line
3321
 
 
3322
 
 
3323
 
class MalformedHunkHeader(PatchSyntax):
3324
 
 
3325
 
    _fmt = "Malformed hunk header.  %(desc)s\n%(line)r"
3326
 
 
3327
 
    def __init__(self, desc, line):
3328
 
        self.desc = desc
3329
 
        self.line = line
3330
 
 
3331
 
 
3332
 
class MalformedLine(PatchSyntax):
3333
 
 
3334
 
    _fmt = "Malformed line.  %(desc)s\n%(line)r"
3335
 
 
3336
 
    def __init__(self, desc, line):
3337
 
        self.desc = desc
3338
 
        self.line = line
3339
 
 
3340
 
 
3341
 
class PatchConflict(BzrError):
3342
 
 
3343
 
    _fmt = ('Text contents mismatch at line %(line_no)d.  Original has '
3344
 
            '"%(orig_line)s", but patch says it should be "%(patch_line)s"')
3345
 
 
3346
 
    def __init__(self, line_no, orig_line, patch_line):
3347
 
        self.line_no = line_no
3348
 
        self.orig_line = orig_line.rstrip('\n')
3349
 
        self.patch_line = patch_line.rstrip('\n')
3350
 
 
3351
 
 
3352
 
class FeatureAlreadyRegistered(BzrError):
3353
 
 
3354
 
    _fmt = 'The feature %(feature)s has already been registered.'
3355
 
 
3356
 
    def __init__(self, feature):
3357
 
        self.feature = feature
3358
 
 
3359
 
 
3360
 
class ChangesAlreadyStored(BzrCommandError):
3361
 
 
3362
 
    _fmt = ('Cannot store uncommitted changes because this branch already'
3363
 
            ' stores uncommitted changes.')