~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/errors.py

  • Committer: John Arbash Meinel
  • Date: 2008-10-30 00:55:00 UTC
  • mto: (3815.2.5 prepare-1.9)
  • mto: This revision was merged to the branch mainline in revision 3811.
  • Revision ID: john@arbash-meinel.com-20081030005500-r5cej1cxflqhs3io
Switch so that we are using a simple timestamp as the first action.

Show diffs side-by-side

added added

removed removed

Lines of Context:
81
81
        parameters.
82
82
 
83
83
        :param msg: If given, this is the literal complete text for the error,
84
 
        not subject to expansion.
 
84
           not subject to expansion. 'msg' is used instead of 'message' because
 
85
           python evolved and, in 2.6, forbids the use of 'message'.
85
86
        """
86
87
        StandardError.__init__(self)
87
88
        if msg is not None:
93
94
            for key, value in kwds.items():
94
95
                setattr(self, key, value)
95
96
 
96
 
    def __str__(self):
 
97
    def _format(self):
97
98
        s = getattr(self, '_preformatted_string', None)
98
99
        if s is not None:
99
 
            # contains a preformatted message; must be cast to plain str
100
 
            return str(s)
 
100
            # contains a preformatted message
 
101
            return s
101
102
        try:
102
103
            fmt = self._get_format_string()
103
104
            if fmt:
104
105
                d = dict(self.__dict__)
105
 
                # special case: python2.5 puts the 'message' attribute in a
106
 
                # slot, so it isn't seen in __dict__
107
 
                d['message'] = getattr(self, 'message', 'no message')
108
106
                s = fmt % d
109
107
                # __str__() should always return a 'str' object
110
108
                # never a 'unicode' object.
111
 
                if isinstance(s, unicode):
112
 
                    return s.encode('utf8')
113
109
                return s
114
110
        except (AttributeError, TypeError, NameError, ValueError, KeyError), e:
115
111
            return 'Unprintable exception %s: dict=%r, fmt=%r, error=%r' \
118
114
                   getattr(self, '_fmt', None),
119
115
                   e)
120
116
 
 
117
    def __unicode__(self):
 
118
        u = self._format()
 
119
        if isinstance(u, str):
 
120
            # Try decoding the str using the default encoding.
 
121
            u = unicode(u)
 
122
        elif not isinstance(u, unicode):
 
123
            # Try to make a unicode object from it, because __unicode__ must
 
124
            # return a unicode object.
 
125
            u = unicode(u)
 
126
        return u
 
127
 
 
128
    def __str__(self):
 
129
        s = self._format()
 
130
        if isinstance(s, unicode):
 
131
            s = s.encode('utf8')
 
132
        else:
 
133
            # __str__ must return a str.
 
134
            s = str(s)
 
135
        return s
 
136
 
121
137
    def _get_format_string(self):
122
138
        """Return format string for this exception or None"""
123
139
        fmt = getattr(self, '_fmt', None)
135
151
               getattr(self, '_fmt', None),
136
152
               )
137
153
 
 
154
    def __eq__(self, other):
 
155
        if self.__class__ != other.__class__:
 
156
            return NotImplemented
 
157
        return self.__dict__ == other.__dict__
 
158
 
138
159
 
139
160
class InternalBzrError(BzrError):
140
161
    """Base class for errors that are internal in nature.
181
202
 
182
203
 
183
204
class AlreadyBuilding(BzrError):
184
 
    
 
205
 
185
206
    _fmt = "The tree builder is already building a tree."
186
207
 
187
208
 
193
214
 
194
215
 
195
216
class BzrCheckError(InternalBzrError):
196
 
    
197
 
    _fmt = "Internal check failed: %(message)s"
198
 
 
199
 
    def __init__(self, message):
200
 
        BzrError.__init__(self)
201
 
        self.message = message
 
217
 
 
218
    _fmt = "Internal check failed: %(msg)s"
 
219
 
 
220
    def __init__(self, msg):
 
221
        BzrError.__init__(self)
 
222
        self.msg = msg
 
223
 
 
224
 
 
225
class DirstateCorrupt(BzrError):
 
226
 
 
227
    _fmt = "The dirstate file (%(state)s) appears to be corrupt: %(msg)s"
 
228
 
 
229
    def __init__(self, state, msg):
 
230
        BzrError.__init__(self)
 
231
        self.state = state
 
232
        self.msg = msg
202
233
 
203
234
 
204
235
class DisabledMethod(InternalBzrError):
366
397
    # are not intended to be caught anyway.  UI code need not subclass
367
398
    # BzrCommandError, and non-UI code should not throw a subclass of
368
399
    # BzrCommandError.  ADHB 20051211
369
 
    def __init__(self, msg):
370
 
        # Object.__str__() must return a real string
371
 
        # returning a Unicode string is a python error.
372
 
        if isinstance(msg, unicode):
373
 
            self.msg = msg.encode('utf8')
374
 
        else:
375
 
            self.msg = msg
376
 
 
377
 
    def __str__(self):
378
 
        return self.msg
379
400
 
380
401
 
381
402
class NotWriteLocked(BzrError):
562
583
        PathError.__init__(self, base, reason)
563
584
 
564
585
 
 
586
class InvalidRebaseURLs(PathError):
 
587
 
 
588
    _fmt = "URLs differ by more than path: %(from_)r and %(to)r"
 
589
 
 
590
    def __init__(self, from_, to):
 
591
        self.from_ = from_
 
592
        self.to = to
 
593
        PathError.__init__(self, from_, 'URLs differ by more than path.')
 
594
 
 
595
 
565
596
class UnavailableRepresentation(InternalBzrError):
566
597
 
567
598
    _fmt = ("The encoding '%(wanted)s' is not available for key %(key)s which "
751
782
 
752
783
class IncompatibleRepositories(BzrError):
753
784
 
754
 
    _fmt = "Repository %(target)s is not compatible with repository"\
755
 
        " %(source)s"
 
785
    _fmt = "%(target)s\n" \
 
786
            "is not compatible with\n" \
 
787
            "%(source)s\n" \
 
788
            "%(details)s"
756
789
 
757
 
    def __init__(self, source, target):
758
 
        BzrError.__init__(self, target=target, source=source)
 
790
    def __init__(self, source, target, details=None):
 
791
        if details is None:
 
792
            details = "(no details)"
 
793
        BzrError.__init__(self, target=target, source=source, details=details)
759
794
 
760
795
 
761
796
class IncompatibleRevision(BzrError):
848
883
        BzrError.__init__(self, filename=filename, kind=kind)
849
884
 
850
885
 
 
886
class BadFilenameEncoding(BzrError):
 
887
 
 
888
    _fmt = ('Filename %(filename)r is not valid in your current filesystem'
 
889
            ' encoding %(fs_encoding)s')
 
890
 
 
891
    def __init__(self, filename, fs_encoding):
 
892
        BzrError.__init__(self)
 
893
        self.filename = filename
 
894
        self.fs_encoding = fs_encoding
 
895
 
 
896
 
851
897
class ForbiddenControlFileError(BzrError):
852
898
 
853
899
    _fmt = 'Cannot operate on "%(filename)s" because it is a control file'
1262
1308
 
1263
1309
class WeaveError(BzrError):
1264
1310
 
1265
 
    _fmt = "Error in processing weave: %(message)s"
 
1311
    _fmt = "Error in processing weave: %(msg)s"
1266
1312
 
1267
 
    def __init__(self, message=None):
 
1313
    def __init__(self, msg=None):
1268
1314
        BzrError.__init__(self)
1269
 
        self.message = message
 
1315
        self.msg = msg
1270
1316
 
1271
1317
 
1272
1318
class WeaveRevisionAlreadyPresent(WeaveError):
1378
1424
        self.how = how
1379
1425
 
1380
1426
 
 
1427
class SHA1KnitCorrupt(KnitCorrupt):
 
1428
 
 
1429
    _fmt = ("Knit %(filename)s corrupt: sha-1 of reconstructed text does not "
 
1430
        "match expected sha-1. key %(key)s expected sha %(expected)s actual "
 
1431
        "sha %(actual)s")
 
1432
 
 
1433
    def __init__(self, filename, actual, expected, key, content):
 
1434
        KnitError.__init__(self)
 
1435
        self.filename = filename
 
1436
        self.actual = actual
 
1437
        self.expected = expected
 
1438
        self.key = key
 
1439
        self.content = content
 
1440
 
 
1441
 
1381
1442
class KnitDataStreamIncompatible(KnitError):
1382
1443
    # Not raised anymore, as we can convert data streams.  In future we may
1383
1444
    # need it again for more exotic cases, so we're keeping it around for now.
1625
1686
        if filename is None:
1626
1687
            filename = ""
1627
1688
        message = "Error(s) parsing config file %s:\n%s" % \
1628
 
            (filename, ('\n'.join(e.message for e in errors)))
 
1689
            (filename, ('\n'.join(e.msg for e in errors)))
1629
1690
        BzrError.__init__(self, message)
1630
1691
 
1631
1692
 
1816
1877
    _fmt = "Could not move %(from_path)s%(operator)s %(to_path)s%(extra)s"
1817
1878
 
1818
1879
    def __init__(self, from_path='', to_path='', extra=None):
 
1880
        from bzrlib.osutils import splitpath
1819
1881
        BzrError.__init__(self)
1820
1882
        if extra:
1821
1883
            self.extra = ': ' + str(extra)
1825
1887
        has_from = len(from_path) > 0
1826
1888
        has_to = len(to_path) > 0
1827
1889
        if has_from:
1828
 
            self.from_path = osutils.splitpath(from_path)[-1]
 
1890
            self.from_path = splitpath(from_path)[-1]
1829
1891
        else:
1830
1892
            self.from_path = ''
1831
1893
 
1832
1894
        if has_to:
1833
 
            self.to_path = osutils.splitpath(to_path)[-1]
 
1895
            self.to_path = splitpath(to_path)[-1]
1834
1896
        else:
1835
1897
            self.to_path = ''
1836
1898
 
2347
2409
        self.patch_type = patch_type
2348
2410
 
2349
2411
 
 
2412
class TargetNotBranch(BzrError):
 
2413
    """A merge directive's target branch is required, but isn't a branch"""
 
2414
 
 
2415
    _fmt = ("Your branch does not have all of the revisions required in "
 
2416
            "order to merge this merge directive and the target "
 
2417
            "location specified in the merge directive is not a branch: "
 
2418
            "%(location)s.")
 
2419
 
 
2420
    def __init__(self, location):
 
2421
        BzrError.__init__(self)
 
2422
        self.location = location
 
2423
 
 
2424
 
2350
2425
class UnsupportedInventoryKind(BzrError):
2351
2426
    
2352
2427
    _fmt = """Unsupported entry kind %(kind)s"""
2395
2470
class TagsNotSupported(BzrError):
2396
2471
 
2397
2472
    _fmt = ("Tags not supported by %(branch)s;"
2398
 
            " you may be able to use bzr upgrade --dirstate-tags.")
 
2473
            " you may be able to use bzr upgrade.")
2399
2474
 
2400
2475
    def __init__(self, branch):
2401
2476
        self.branch = branch
2447
2522
 
2448
2523
 
2449
2524
class ErrorFromSmartServer(BzrError):
 
2525
    """An error was received from a smart server.
 
2526
 
 
2527
    :seealso: UnknownErrorFromSmartServer
 
2528
    """
2450
2529
 
2451
2530
    _fmt = "Error received from smart server: %(error_tuple)r"
2452
2531
 
2461
2540
        self.error_args = error_tuple[1:]
2462
2541
 
2463
2542
 
 
2543
class UnknownErrorFromSmartServer(BzrError):
 
2544
    """An ErrorFromSmartServer could not be translated into a typical bzrlib
 
2545
    error.
 
2546
 
 
2547
    This is distinct from ErrorFromSmartServer so that it is possible to
 
2548
    distinguish between the following two cases:
 
2549
      - ErrorFromSmartServer was uncaught.  This is logic error in the client
 
2550
        and so should provoke a traceback to the user.
 
2551
      - ErrorFromSmartServer was caught but its error_tuple could not be
 
2552
        translated.  This is probably because the server sent us garbage, and
 
2553
        should not provoke a traceback.
 
2554
    """
 
2555
 
 
2556
    _fmt = "Server sent an unexpected error: %(error_tuple)r"
 
2557
 
 
2558
    internal_error = False
 
2559
 
 
2560
    def __init__(self, error_from_smart_server):
 
2561
        """Constructor.
 
2562
 
 
2563
        :param error_from_smart_server: An ErrorFromSmartServer instance.
 
2564
        """
 
2565
        self.error_from_smart_server = error_from_smart_server
 
2566
        self.error_tuple = error_from_smart_server.error_tuple
 
2567
        
 
2568
 
2464
2569
class ContainerError(BzrError):
2465
2570
    """Base class of container errors."""
2466
2571
 
2718
2823
            'user encoding %(user_encoding)s')
2719
2824
 
2720
2825
    def __init__(self, path, kind):
 
2826
        from bzrlib.osutils import get_user_encoding
2721
2827
        self.path = path
2722
2828
        self.kind = kind
2723
2829
        self.user_encoding = osutils.get_user_encoding()
2731
2837
        BzrError.__init__(self, alias_name=alias_name)
2732
2838
 
2733
2839
 
 
2840
class DirectoryLookupFailure(BzrError):
 
2841
    """Base type for lookup errors."""
 
2842
 
 
2843
    pass
 
2844
 
 
2845
 
 
2846
class InvalidLocationAlias(DirectoryLookupFailure):
 
2847
 
 
2848
    _fmt = '"%(alias_name)s" is not a valid location alias.'
 
2849
 
 
2850
    def __init__(self, alias_name):
 
2851
        DirectoryLookupFailure.__init__(self, alias_name=alias_name)
 
2852
 
 
2853
 
 
2854
class UnsetLocationAlias(DirectoryLookupFailure):
 
2855
 
 
2856
    _fmt = 'No %(alias_name)s location assigned.'
 
2857
 
 
2858
    def __init__(self, alias_name):
 
2859
        DirectoryLookupFailure.__init__(self, alias_name=alias_name[1:])
 
2860
 
 
2861
 
2734
2862
class CannotBindAddress(BzrError):
2735
2863
 
2736
2864
    _fmt = 'Cannot bind address "%(host)s:%(port)i": %(orig_error)s.'
2738
2866
    def __init__(self, host, port, orig_error):
2739
2867
        BzrError.__init__(self, host=host, port=port,
2740
2868
            orig_error=orig_error[1])
 
2869
 
 
2870
 
 
2871
class UnknownRules(BzrError):
 
2872
 
 
2873
    _fmt = ('Unknown rules detected: %(unknowns_str)s.')
 
2874
 
 
2875
    def __init__(self, unknowns):
 
2876
        BzrError.__init__(self, unknowns_str=", ".join(unknowns))
 
2877
 
 
2878
 
 
2879
class HookFailed(BzrError):
 
2880
    """Raised when a pre_change_branch_tip hook function fails anything other
 
2881
    than TipChangeRejected.
 
2882
    """
 
2883
 
 
2884
    _fmt = ("Hook '%(hook_name)s' during %(hook_stage)s failed:\n"
 
2885
            "%(traceback_text)s%(exc_value)s")
 
2886
 
 
2887
    def __init__(self, hook_stage, hook_name, exc_info):
 
2888
        import traceback
 
2889
        self.hook_stage = hook_stage
 
2890
        self.hook_name = hook_name
 
2891
        self.exc_info = exc_info
 
2892
        self.exc_type = exc_info[0]
 
2893
        self.exc_value = exc_info[1]
 
2894
        self.exc_tb = exc_info[2]
 
2895
        self.traceback_text = ''.join(traceback.format_tb(self.exc_tb))
 
2896
 
 
2897
 
 
2898
class TipChangeRejected(BzrError):
 
2899
    """A pre_change_branch_tip hook function may raise this to cleanly and
 
2900
    explicitly abort a change to a branch tip.
 
2901
    """
 
2902
    
 
2903
    _fmt = u"Tip change rejected: %(msg)s"
 
2904
 
 
2905
    def __init__(self, msg):
 
2906
        self.msg = msg
 
2907