~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/errors.py

  • Committer: Martin Pool
  • Date: 2005-05-17 06:56:16 UTC
  • Revision ID: mbp@sourcefrog.net-20050517065616-6f23381d6184a8aa
- add space for un-merged patches

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# (C) 2005 Canonical
 
1
#! /usr/bin/env python
 
2
# -*- coding: UTF-8 -*-
2
3
 
3
4
# This program is free software; you can redistribute it and/or modify
4
5
# it under the terms of the GNU General Public License as published by
14
15
# along with this program; if not, write to the Free Software
15
16
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
17
 
17
 
"""Exceptions for bzr, and reporting of them.
18
 
 
19
 
Exceptions are caught at a high level to report errors to the user, and
20
 
might also be caught inside the program.  Therefore it needs to be
21
 
possible to convert them to a meaningful string, and also for them to be
22
 
interrogated by the program.
23
 
 
24
 
Exceptions are defined such that the arguments given to the constructor
25
 
are stored in the object as properties of the same name.  When the
26
 
object is printed as a string, the doc string of the class is used as
27
 
a format string with the property dictionary available to it.
28
 
 
29
 
This means that exceptions can used like this:
30
 
 
31
 
>>> import sys
32
 
>>> try:
33
 
...   raise NotBranchError(path='/foo/bar')
34
 
... except:
35
 
...   print sys.exc_type
36
 
...   print sys.exc_value
37
 
...   path = getattr(sys.exc_value, 'path')
38
 
...   if path is not None:
39
 
...     print path
40
 
bzrlib.errors.NotBranchError
41
 
Not a branch: /foo/bar
42
 
/foo/bar
43
 
 
44
 
Therefore:
45
 
 
46
 
 * create a new exception class for any class of error that can be
47
 
   usefully distinguished.
48
 
 
49
 
 * the printable form of an exception is generated by the base class
50
 
   __str__ method
51
 
 
52
 
Exception strings should start with a capital letter and not have a final
53
 
fullstop.
54
 
"""
55
 
 
56
 
# based on Scott James Remnant's hct error classes
57
 
 
58
 
# TODO: is there any value in providing the .args field used by standard
59
 
# python exceptions?   A list of values with no names seems less useful 
60
 
# to me.
61
 
 
62
 
# TODO: Perhaps convert the exception to a string at the moment it's 
63
 
# constructed to make sure it will succeed.  But that says nothing about
64
 
# exceptions that are never raised.
65
 
 
66
 
# TODO: Convert all the other error classes here to BzrNewError, and eliminate
67
 
# the old one.
68
 
 
69
 
 
 
18
 
 
19
__copyright__ = "Copyright (C) 2005 Canonical Ltd."
 
20
__author__ = "Martin Pool <mbp@canonical.com>"
 
21
 
 
22
 
 
23
######################################################################
 
24
# exceptions 
70
25
class BzrError(StandardError):
71
 
    def __str__(self):
72
 
        # XXX: Should we show the exception class in 
73
 
        # exceptions that don't provide their own message?  
74
 
        # maybe it should be done at a higher level
75
 
        ## n = self.__class__.__name__ + ': '
76
 
        n = ''
77
 
        if len(self.args) == 1:
78
 
            return str(self.args[0])
79
 
        elif len(self.args) == 2:
80
 
            # further explanation or suggestions
81
 
            try:
82
 
                return n + '\n  '.join([self.args[0]] + self.args[1])
83
 
            except TypeError:
84
 
                return n + "%r" % self
85
 
        else:
86
 
            return n + `self.args`
87
 
 
88
 
 
89
 
class BzrNewError(BzrError):
90
 
    """bzr error"""
91
 
    # base classes should override the docstring with their human-
92
 
    # readable explanation
93
 
 
94
 
    def __init__(self, **kwds):
95
 
        for key, value in kwds.items():
96
 
            setattr(self, key, value)
97
 
 
98
 
    def __str__(self):
99
 
        try:
100
 
            return self.__doc__ % self.__dict__
101
 
        except (NameError, ValueError, KeyError), e:
102
 
            return 'Unprintable exception %s: %s' \
103
 
                % (self.__class__.__name__, str(e))
104
 
 
105
 
 
106
 
class BzrCheckError(BzrNewError):
107
 
    """Internal check failed: %(message)s"""
108
 
    def __init__(self, message):
109
 
        BzrNewError.__init__(self)
110
 
        self.message = message
111
 
 
112
 
 
113
 
class InvalidEntryName(BzrNewError):
114
 
    """Invalid entry name: %(name)s"""
115
 
    def __init__(self, name):
116
 
        BzrNewError.__init__(self)
117
 
        self.name = name
118
 
 
119
 
 
120
 
class InvalidRevisionNumber(BzrNewError):
121
 
    """Invalid revision number %(revno)d"""
122
 
    def __init__(self, revno):
123
 
        BzrNewError.__init__(self)
124
 
        self.revno = revno
125
 
 
126
 
 
127
 
class InvalidRevisionId(BzrNewError):
128
 
    """Invalid revision-id {%(revision_id)s} in %(branch)s"""
129
 
    def __init__(self, revision_id, branch):
130
 
        BzrNewError.__init__(self)
131
 
        self.revision_id = revision_id
132
 
        self.branch = branch
133
 
 
134
 
 
135
 
class NoWorkingTree(BzrNewError):
136
 
    """No WorkingTree exists for %s(base)."""
137
 
    
138
 
    def __init__(self, base):
139
 
        BzrNewError.__init__(self)
140
 
        self.base = base
 
26
    pass
 
27
 
 
28
class BzrCheckError(BzrError):
 
29
    pass
141
30
 
142
31
 
143
32
class BzrCommandError(BzrError):
144
33
    # Error from malformed user command
145
 
    # This is being misused as a generic exception
146
 
    # pleae subclass. RBC 20051030
147
 
    #
148
 
    # I think it's a waste of effort to differentiate between errors that
149
 
    # are not intended to be caught anyway.  UI code need not subclass
150
 
    # BzrCommandError, and non-UI code should not throw a subclass of
151
 
    # BzrCommandError.  ADHB 20051211
152
 
    def __str__(self):
153
 
        return self.args[0]
154
 
 
155
 
 
156
 
class BzrOptionError(BzrCommandError):
157
 
    """Some missing or otherwise incorrect option was supplied."""
158
 
 
159
 
    
160
 
class StrictCommitFailed(Exception):
161
 
    """Commit refused because there are unknowns in the tree."""
162
 
 
163
 
 
164
 
class PathError(BzrNewError):
165
 
    """Generic path error: %(path)r%(extra)s)"""
166
 
    def __init__(self, path, extra=None):
167
 
        BzrNewError.__init__(self)
168
 
        self.path = path
169
 
        if extra:
170
 
            self.extra = ': ' + str(extra)
171
 
        else:
172
 
            self.extra = ''
173
 
 
174
 
 
175
 
class NoSuchFile(PathError):
176
 
    """No such file: %(path)r%(extra)s"""
177
 
 
178
 
 
179
 
class FileExists(PathError):
180
 
    """File exists: %(path)r%(extra)s"""
181
 
 
182
 
 
183
 
class PermissionDenied(PathError):
184
 
    """Permission denied: %(path)r%(extra)s"""
185
 
 
186
 
 
187
 
class PathNotChild(BzrNewError):
188
 
    """Path %(path)r is not a child of path %(base)r%(extra)s"""
189
 
    def __init__(self, path, base, extra=None):
190
 
        BzrNewError.__init__(self)
191
 
        self.path = path
192
 
        self.base = base
193
 
        if extra:
194
 
            self.extra = ': ' + str(extra)
195
 
        else:
196
 
            self.extra = ''
197
 
 
198
 
 
199
 
class NotBranchError(BzrNewError):
200
 
    """Not a branch: %(path)s"""
201
 
    def __init__(self, path):
202
 
        BzrNewError.__init__(self)
203
 
        self.path = path
204
 
 
205
 
 
206
 
class FileInWrongBranch(BzrNewError):
207
 
    """File %(path)s in not in branch %(branch_base)s."""
208
 
    def __init__(self, branch, path):
209
 
        BzrNewError.__init__(self)
210
 
        self.branch = branch
211
 
        self.branch_base = branch.base
212
 
        self.path = path
213
 
 
214
 
 
215
 
class UnsupportedFormatError(BzrError):
216
 
    """Specified path is a bzr branch that we recognize but cannot read."""
217
 
    def __str__(self):
218
 
        return 'unsupported branch format: %s' % self.args[0]
219
 
 
220
 
 
221
 
class UnknownFormatError(BzrError):
222
 
    """Specified path is a bzr branch whose format we do not recognize."""
223
 
    def __str__(self):
224
 
        return 'unknown branch format: %s' % self.args[0]
225
 
 
226
 
 
227
 
class NotVersionedError(BzrNewError):
228
 
    """%(path)s is not versioned"""
229
 
    def __init__(self, path):
230
 
        BzrNewError.__init__(self)
231
 
        self.path = path
232
 
 
233
 
 
234
 
class BadFileKindError(BzrError):
235
 
    """Specified file is of a kind that cannot be added.
236
 
 
237
 
    (For example a symlink or device file.)"""
238
 
 
239
 
 
240
 
class ForbiddenFileError(BzrError):
241
 
    """Cannot operate on a file because it is a control file."""
242
 
 
243
 
 
244
 
class LockError(Exception):
245
 
    """Lock error"""
246
 
    # All exceptions from the lock/unlock functions should be from
247
 
    # this exception class.  They will be translated as necessary. The
248
 
    # original exception is available as e.original_error
249
 
 
250
 
 
251
 
class CommitNotPossible(LockError):
252
 
    """A commit was attempted but we do not have a write lock open."""
253
 
 
254
 
 
255
 
class AlreadyCommitted(LockError):
256
 
    """A rollback was requested, but is not able to be accomplished."""
257
 
 
258
 
 
259
 
class ReadOnlyError(LockError):
260
 
    """A write attempt was made in a read only transaction."""
261
 
 
262
 
 
263
 
class PointlessCommit(BzrNewError):
264
 
    """No changes to commit"""
265
 
 
266
 
 
267
 
class UpgradeReadonly(BzrNewError):
268
 
    """Upgrade URL cannot work with readonly URL's."""
269
 
 
270
 
 
271
 
class StrictCommitFailed(Exception):
272
 
    """Commit refused because there are unknowns in the tree."""
273
 
 
274
 
 
275
 
class NoSuchRevision(BzrError):
276
 
    def __init__(self, branch, revision):
277
 
        self.branch = branch
278
 
        self.revision = revision
279
 
        msg = "Branch %s has no revision %s" % (branch, revision)
280
 
        BzrError.__init__(self, msg)
281
 
 
282
 
 
283
 
class HistoryMissing(BzrError):
284
 
    def __init__(self, branch, object_type, object_id):
285
 
        self.branch = branch
286
 
        BzrError.__init__(self,
287
 
                          '%s is missing %s {%s}'
288
 
                          % (branch, object_type, object_id))
289
 
 
290
 
 
291
 
class DivergedBranches(BzrError):
292
 
    def __init__(self, branch1, branch2):
293
 
        BzrError.__init__(self, "These branches have diverged.  Try merge.")
294
 
        self.branch1 = branch1
295
 
        self.branch2 = branch2
296
 
 
297
 
 
298
 
class UnrelatedBranches(BzrCommandError):
299
 
    def __init__(self):
300
 
        msg = "Branches have no common ancestor, and no base revision"\
301
 
            " specified."
302
 
        BzrCommandError.__init__(self, msg)
303
 
 
304
 
class NoCommonAncestor(BzrError):
305
 
    def __init__(self, revision_a, revision_b):
306
 
        msg = "Revisions have no common ancestor: %s %s." \
307
 
            % (revision_a, revision_b) 
308
 
        BzrError.__init__(self, msg)
309
 
 
310
 
class NoCommonRoot(BzrError):
311
 
    def __init__(self, revision_a, revision_b):
312
 
        msg = "Revisions are not derived from the same root: %s %s." \
313
 
            % (revision_a, revision_b) 
314
 
        BzrError.__init__(self, msg)
315
 
 
316
 
class NotAncestor(BzrError):
317
 
    def __init__(self, rev_id, not_ancestor_id):
318
 
        msg = "Revision %s is not an ancestor of %s" % (not_ancestor_id, 
319
 
                                                        rev_id)
320
 
        BzrError.__init__(self, msg)
321
 
        self.rev_id = rev_id
322
 
        self.not_ancestor_id = not_ancestor_id
323
 
 
324
 
 
325
 
class InstallFailed(BzrError):
326
 
    def __init__(self, revisions):
327
 
        msg = "Could not install revisions:\n%s" % " ,".join(revisions)
328
 
        BzrError.__init__(self, msg)
329
 
        self.revisions = revisions
330
 
 
331
 
 
332
 
class AmbiguousBase(BzrError):
333
 
    def __init__(self, bases):
334
 
        msg = "The correct base is unclear, becase %s are all equally close" %\
335
 
            ", ".join(bases)
336
 
        BzrError.__init__(self, msg)
337
 
        self.bases = bases
338
 
 
339
 
class NoCommits(BzrError):
340
 
    def __init__(self, branch):
341
 
        msg = "Branch %s has no commits." % branch
342
 
        BzrError.__init__(self, msg)
343
 
 
344
 
class UnlistableStore(BzrError):
345
 
    def __init__(self, store):
346
 
        BzrError.__init__(self, "Store %s is not listable" % store)
347
 
 
348
 
class UnlistableBranch(BzrError):
349
 
    def __init__(self, br):
350
 
        BzrError.__init__(self, "Stores for branch %s are not listable" % br)
351
 
 
352
 
 
353
 
class WeaveError(BzrNewError):
354
 
    """Error in processing weave: %(message)s"""
355
 
    def __init__(self, message=None):
356
 
        BzrNewError.__init__(self)
357
 
        self.message = message
358
 
 
359
 
 
360
 
class WeaveRevisionAlreadyPresent(WeaveError):
361
 
    """Revision {%(revision_id)s} already present in %(weave)s"""
362
 
    def __init__(self, revision_id, weave):
363
 
        WeaveError.__init__(self)
364
 
        self.revision_id = revision_id
365
 
        self.weave = weave
366
 
 
367
 
 
368
 
class WeaveRevisionNotPresent(WeaveError):
369
 
    """Revision {%(revision_id)s} not present in %(weave)s"""
370
 
    def __init__(self, revision_id, weave):
371
 
        WeaveError.__init__(self)
372
 
        self.revision_id = revision_id
373
 
        self.weave = weave
374
 
 
375
 
 
376
 
class WeaveFormatError(WeaveError):
377
 
    """Weave invariant violated: %(what)s"""
378
 
    def __init__(self, what):
379
 
        WeaveError.__init__(self)
380
 
        self.what = what
381
 
 
382
 
 
383
 
class WeaveParentMismatch(WeaveError):
384
 
    """Parents are mismatched between two revisions."""
385
 
    
386
 
 
387
 
class WeaveInvalidChecksum(WeaveError):
388
 
    """Text did not match it's checksum: %(message)s"""
389
 
 
390
 
 
391
 
class WeaveTextDiffers(WeaveError):
392
 
    """Weaves differ on text content. Revision: {%(revision_id)s}, %(weave_a)s, %(weave_b)s"""
393
 
 
394
 
    def __init__(self, revision_id, weave_a, weave_b):
395
 
        WeaveError.__init__(self)
396
 
        self.revision_id = revision_id
397
 
        self.weave_a = weave_a
398
 
        self.weave_b = weave_b
399
 
 
400
 
 
401
 
class NoSuchExportFormat(BzrNewError):
402
 
    """Export format %(format)r not supported"""
403
 
    def __init__(self, format):
404
 
        BzrNewError.__init__(self)
405
 
        self.format = format
406
 
 
407
 
 
408
 
class TransportError(BzrError):
409
 
    """All errors thrown by Transport implementations should derive
410
 
    from this class.
411
 
    """
412
 
    def __init__(self, msg=None, orig_error=None):
413
 
        if msg is None and orig_error is not None:
414
 
            msg = str(orig_error)
415
 
        BzrError.__init__(self, msg)
416
 
        self.msg = msg
417
 
        self.orig_error = orig_error
418
 
 
419
 
# A set of semi-meaningful errors which can be thrown
420
 
class TransportNotPossible(TransportError):
421
 
    """This is for transports where a specific function is explicitly not
422
 
    possible. Such as pushing files to an HTTP server.
423
 
    """
424
 
    pass
425
 
 
426
 
 
427
 
class ConnectionError(TransportError):
428
 
    """A connection problem prevents file retrieval.
429
 
    This does not indicate whether the file exists or not; it indicates that a
430
 
    precondition for requesting the file was not met.
431
 
    """
432
 
    def __init__(self, msg=None, orig_error=None):
433
 
        TransportError.__init__(self, msg=msg, orig_error=orig_error)
434
 
 
435
 
 
436
 
class ConnectionReset(TransportError):
437
 
    """The connection has been closed."""
438
 
    pass
439
 
 
440
 
class ConflictsInTree(BzrError):
441
 
    def __init__(self):
442
 
        BzrError.__init__(self, "Working tree has conflicts.")
443
 
 
444
 
class ParseConfigError(BzrError):
445
 
    def __init__(self, errors, filename):
446
 
        if filename is None:
447
 
            filename = ""
448
 
        message = "Error(s) parsing config file %s:\n%s" % \
449
 
            (filename, ('\n'.join(e.message for e in errors)))
450
 
        BzrError.__init__(self, message)
451
 
 
452
 
class SigningFailed(BzrError):
453
 
    def __init__(self, command_line):
454
 
        BzrError.__init__(self, "Failed to gpg sign data with command '%s'"
455
 
                               % command_line)
456
 
 
457
 
class WorkingTreeNotRevision(BzrError):
458
 
    def __init__(self, tree):
459
 
        BzrError.__init__(self, "The working tree for %s has changed since"
460
 
                          " last commit, but weave merge requires that it be"
461
 
                          " unchanged." % tree.basedir)
462
 
 
463
 
class CantReprocessAndShowBase(BzrNewError):
464
 
    """Can't reprocess and show base.
465
 
Reprocessing obscures relationship of conflicting lines to base."""
466
 
 
467
 
class GraphCycleError(BzrNewError):
468
 
    """Cycle in graph %(graph)r"""
469
 
    def __init__(self, graph):
470
 
        BzrNewError.__init__(self)
471
 
        self.graph = graph
472
 
 
473
 
 
474
 
class NotConflicted(BzrNewError):
475
 
    """File %(filename)s is not conflicted."""
476
 
 
477
 
    def __init__(self, filename):
478
 
        BzrNewError.__init__(self)
479
 
        self.filename = filename
480
 
 
481
 
 
482
 
class MustUseDecorated(Exception):
483
 
    """A decorating function has requested its original command be used.
484
 
    
485
 
    This should never escape bzr, so does not need to be printable.
486
 
    """
487
 
 
488
 
 
489
 
class MissingText(BzrNewError):
490
 
    """Branch %(base)s is missing revision %(text_revision)s of %(file_id)s"""
491
 
 
492
 
    def __init__(self, branch, text_revision, file_id):
493
 
        BzrNewError.__init__(self)
494
 
        self.branch = branch
495
 
        self.base = branch.base
496
 
        self.text_revision = text_revision
497
 
        self.file_id = file_id
498
 
 
499
 
 
500
 
class BzrBadParameter(BzrNewError):
501
 
    """A bad parameter : %(param)s is not usable.
502
 
    
503
 
    This exception should never be thrown, but it is a base class for all
504
 
    parameter-to-function errors.
505
 
    """
506
 
    def __init__(self, param):
507
 
        BzrNewError.__init__(self)
508
 
        self.param = param
509
 
 
510
 
 
511
 
class BzrBadParameterNotUnicode(BzrBadParameter):
512
 
    """Parameter %(param)s is neither unicode nor utf8."""
513
 
 
514
 
 
515
 
class BzrBadParameterNotString(BzrBadParameter):
516
 
    """Parameter %(param)s is not a string or unicode string."""
517
 
 
518
 
 
519
 
class DependencyNotPresent(BzrNewError):
520
 
    """Unable to import library: %(library)s, %(error)s"""
521
 
 
522
 
    def __init__(self, library, error):
523
 
        BzrNewError.__init__(self, library=library, error=error)
524
 
 
525
 
 
526
 
class ParamikoNotPresent(DependencyNotPresent):
527
 
    """Unable to import paramiko (required for sftp support): %(error)s"""
528
 
 
529
 
    def __init__(self, error):
530
 
        DependencyNotPresent.__init__(self, 'paramiko', error)
531
 
 
532
 
 
533
 
class UninitializableFormat(BzrNewError):
534
 
    """Format %(format)s cannot be initialised by this version of bzr."""
535
 
 
536
 
    def __init__(self, format):
537
 
        BzrNewError.__init__(self)
538
 
        self.format = format
 
34
    pass
 
35
 
 
36
 
 
37
def bailout(msg, explanation=[]):
 
38
    ex = BzrError(msg, explanation)
 
39
    import trace
 
40
    trace._tracefile.write('* raising %s\n' % ex)
 
41
    raise ex
 
42