3
# This program is free software; you can redistribute it and/or modify
 
 
4
# it under the terms of the GNU General Public License as published by
 
 
5
# the Free Software Foundation; either version 2 of the License, or
 
 
6
# (at your option) any later version.
 
 
8
# This program is distributed in the hope that it will be useful,
 
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
 
11
# GNU General Public License for more details.
 
 
13
# You should have received a copy of the GNU General Public License
 
 
14
# along with this program; if not, write to the Free Software
 
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
 
17
"""Exceptions for bzr, and reporting of them.
 
 
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.
 
 
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.
 
 
29
This means that exceptions can used like this:
 
 
33
...   raise NotBranchError(path='/foo/bar')
 
 
35
...   print sys.exc_type
 
 
36
...   print sys.exc_value
 
 
37
...   if hasattr(sys.exc_value, 'path'):
 
 
38
...     print sys.exc_value.path
 
 
39
bzrlib.errors.NotBranchError
 
 
40
Not a branch: /foo/bar
 
 
45
 * create a new exception class for any class of error that can be
 
 
46
   usefully distinguished.
 
 
48
 * the printable form of an exception is generated by the base class
 
 
51
Exception strings should start with a capital letter and not have a final
 
 
55
# based on Scott James Remnant's hct error classes
 
 
57
# TODO: is there any value in providing the .args field used by standard
 
 
58
# python exceptions?   A list of values with no names seems less useful 
 
 
61
# TODO: Perhaps convert the exception to a string at the moment it's 
 
 
62
# constructed to make sure it will succeed.  But that says nothing about
 
 
63
# exceptions that are never raised.
 
 
65
# TODO: Convert all the other error classes here to BzrNewError, and eliminate
 
 
69
class BzrError(StandardError):
 
 
71
        # XXX: Should we show the exception class in 
 
 
72
        # exceptions that don't provide their own message?  
 
 
73
        # maybe it should be done at a higher level
 
 
74
        ## n = self.__class__.__name__ + ': '
 
 
76
        if len(self.args) == 1:
 
 
77
            return str(self.args[0])
 
 
78
        elif len(self.args) == 2:
 
 
79
            # further explanation or suggestions
 
 
81
                return n + '\n  '.join([self.args[0]] + self.args[1])
 
 
83
                return n + "%r" % self
 
 
85
            return n + `self.args`
 
 
88
class BzrNewError(BzrError):
 
 
90
    # base classes should override the docstring with their human-
 
 
91
    # readable explanation
 
 
93
    def __init__(self, **kwds):
 
 
94
        for key, value in kwds.items():
 
 
95
            setattr(self, key, value)
 
 
99
            return self.__doc__ % self.__dict__
 
 
100
        except (NameError, ValueError, KeyError), e:
 
 
101
            return 'Unprintable exception %s: %s' \
 
 
102
                % (self.__class__.__name__, str(e))
 
 
105
class BzrCheckError(BzrNewError):
 
 
106
    """Internal check failed: %(message)s"""
 
 
107
    def __init__(self, message):
 
 
108
        BzrNewError.__init__(self)
 
 
109
        self.message = message
 
 
112
class InvalidEntryName(BzrNewError):
 
 
113
    """Invalid entry name: %(name)s"""
 
 
114
    def __init__(self, name):
 
 
115
        BzrNewError.__init__(self)
 
 
119
class InvalidRevisionNumber(BzrNewError):
 
 
120
    """Invalid revision number %(revno)d"""
 
 
121
    def __init__(self, revno):
 
 
122
        BzrNewError.__init__(self)
 
 
126
class InvalidRevisionId(BzrNewError):
 
 
127
    """Invalid revision-id {%(revision_id)s} in %(branch)s"""
 
 
128
    def __init__(self, revision_id, branch):
 
 
129
        BzrNewError.__init__(self)
 
 
130
        self.revision_id = revision_id
 
 
134
class NoWorkingTree(BzrNewError):
 
 
135
    """No WorkingTree exists for %s(base)."""
 
 
137
    def __init__(self, base):
 
 
138
        BzrNewError.__init__(self)
 
 
142
class BzrCommandError(BzrError):
 
 
143
    # Error from malformed user command
 
 
144
    # This is being misused as a generic exception
 
 
145
    # pleae subclass. RBC 20051030
 
 
147
    # I think it's a waste of effort to differentiate between errors that
 
 
148
    # are not intended to be caught anyway.  UI code need not subclass
 
 
149
    # BzrCommandError, and non-UI code should not throw a subclass of
 
 
150
    # BzrCommandError.  ADHB 20051211
 
 
155
class BzrOptionError(BzrCommandError):
 
 
156
    """Some missing or otherwise incorrect option was supplied."""
 
 
159
class StrictCommitFailed(Exception):
 
 
160
    """Commit refused because there are unknowns in the tree."""
 
 
163
class PathError(BzrNewError):
 
 
164
    """Generic path error: %(path)r%(extra)s)"""
 
 
165
    def __init__(self, path, extra=None):
 
 
166
        BzrNewError.__init__(self)
 
 
169
            self.extra = ': ' + str(extra)
 
 
174
class NoSuchFile(PathError):
 
 
175
    """No such file: %(path)r%(extra)s"""
 
 
178
class FileExists(PathError):
 
 
179
    """File exists: %(path)r%(extra)s"""
 
 
182
class PermissionDenied(PathError):
 
 
183
    """Permission denied: %(path)r%(extra)s"""
 
 
186
class PathNotChild(BzrNewError):
 
 
187
    """Path %(path)r is not a child of path %(base)r%(extra)s"""
 
 
188
    def __init__(self, path, base, extra=None):
 
 
189
        BzrNewError.__init__(self)
 
 
193
            self.extra = ': ' + str(extra)
 
 
198
class NotBranchError(BzrNewError):
 
 
199
    """Not a branch: %(path)s"""
 
 
200
    def __init__(self, path):
 
 
201
        BzrNewError.__init__(self)
 
 
205
class FileInWrongBranch(BzrNewError):
 
 
206
    """File %(path)s in not in branch %(branch_base)s."""
 
 
207
    def __init__(self, branch, path):
 
 
208
        BzrNewError.__init__(self)
 
 
210
        self.branch_base = branch.base
 
 
214
class UnsupportedFormatError(BzrError):
 
 
215
    """Specified path is a bzr branch that we cannot read."""
 
 
217
        return 'unsupported branch format: %s' % self.args[0]
 
 
220
class NotVersionedError(BzrNewError):
 
 
221
    """%(path)s is not versioned"""
 
 
222
    def __init__(self, path):
 
 
223
        BzrNewError.__init__(self)
 
 
227
class BadFileKindError(BzrError):
 
 
228
    """Specified file is of a kind that cannot be added.
 
 
230
    (For example a symlink or device file.)"""
 
 
233
class ForbiddenFileError(BzrError):
 
 
234
    """Cannot operate on a file because it is a control file."""
 
 
237
class LockError(Exception):
 
 
239
    # All exceptions from the lock/unlock functions should be from
 
 
240
    # this exception class.  They will be translated as necessary. The
 
 
241
    # original exception is available as e.original_error
 
 
244
class CommitNotPossible(LockError):
 
 
245
    """A commit was attempted but we do not have a write lock open."""
 
 
248
class AlreadyCommitted(LockError):
 
 
249
    """A rollback was requested, but is not able to be accomplished."""
 
 
252
class ReadOnlyError(LockError):
 
 
253
    """A write attempt was made in a read only transaction."""
 
 
256
class PointlessCommit(BzrNewError):
 
 
257
    """No changes to commit"""
 
 
259
class StrictCommitFailed(Exception):
 
 
260
    """Commit refused because there are unknowns in the tree."""
 
 
262
class NoSuchRevision(BzrError):
 
 
263
    def __init__(self, branch, revision):
 
 
265
        self.revision = revision
 
 
266
        msg = "Branch %s has no revision %s" % (branch, revision)
 
 
267
        BzrError.__init__(self, msg)
 
 
270
class HistoryMissing(BzrError):
 
 
271
    def __init__(self, branch, object_type, object_id):
 
 
273
        BzrError.__init__(self,
 
 
274
                          '%s is missing %s {%s}'
 
 
275
                          % (branch, object_type, object_id))
 
 
278
class DivergedBranches(BzrError):
 
 
279
    def __init__(self, branch1, branch2):
 
 
280
        BzrError.__init__(self, "These branches have diverged.  Try merge.")
 
 
281
        self.branch1 = branch1
 
 
282
        self.branch2 = branch2
 
 
285
class UnrelatedBranches(BzrCommandError):
 
 
287
        msg = "Branches have no common ancestor, and no base revision"\
 
 
289
        BzrCommandError.__init__(self, msg)
 
 
291
class NoCommonAncestor(BzrError):
 
 
292
    def __init__(self, revision_a, revision_b):
 
 
293
        msg = "Revisions have no common ancestor: %s %s." \
 
 
294
            % (revision_a, revision_b) 
 
 
295
        BzrError.__init__(self, msg)
 
 
297
class NoCommonRoot(BzrError):
 
 
298
    def __init__(self, revision_a, revision_b):
 
 
299
        msg = "Revisions are not derived from the same root: %s %s." \
 
 
300
            % (revision_a, revision_b) 
 
 
301
        BzrError.__init__(self, msg)
 
 
303
class NotAncestor(BzrError):
 
 
304
    def __init__(self, rev_id, not_ancestor_id):
 
 
305
        msg = "Revision %s is not an ancestor of %s" % (not_ancestor_id, 
 
 
307
        BzrError.__init__(self, msg)
 
 
309
        self.not_ancestor_id = not_ancestor_id
 
 
312
class InstallFailed(BzrError):
 
 
313
    def __init__(self, revisions):
 
 
314
        msg = "Could not install revisions:\n%s" % " ,".join(revisions)
 
 
315
        BzrError.__init__(self, msg)
 
 
316
        self.revisions = revisions
 
 
319
class AmbiguousBase(BzrError):
 
 
320
    def __init__(self, bases):
 
 
321
        msg = "The correct base is unclear, becase %s are all equally close" %\
 
 
323
        BzrError.__init__(self, msg)
 
 
326
class NoCommits(BzrError):
 
 
327
    def __init__(self, branch):
 
 
328
        msg = "Branch %s has no commits." % branch
 
 
329
        BzrError.__init__(self, msg)
 
 
331
class UnlistableStore(BzrError):
 
 
332
    def __init__(self, store):
 
 
333
        BzrError.__init__(self, "Store %s is not listable" % store)
 
 
335
class UnlistableBranch(BzrError):
 
 
336
    def __init__(self, br):
 
 
337
        BzrError.__init__(self, "Stores for branch %s are not listable" % br)
 
 
340
class WeaveError(BzrNewError):
 
 
341
    """Error in processing weave: %(message)s"""
 
 
342
    def __init__(self, message=None):
 
 
343
        BzrNewError.__init__(self)
 
 
344
        self.message = message
 
 
347
class WeaveRevisionAlreadyPresent(WeaveError):
 
 
348
    """Revision {%(revision_id)s} already present in %(weave)s"""
 
 
349
    def __init__(self, revision_id, weave):
 
 
350
        WeaveError.__init__(self)
 
 
351
        self.revision_id = revision_id
 
 
355
class WeaveRevisionNotPresent(WeaveError):
 
 
356
    """Revision {%(revision_id)s} not present in %(weave)s"""
 
 
357
    def __init__(self, revision_id, weave):
 
 
358
        WeaveError.__init__(self)
 
 
359
        self.revision_id = revision_id
 
 
363
class WeaveFormatError(WeaveError):
 
 
364
    """Weave invariant violated: %(what)s"""
 
 
365
    def __init__(self, what):
 
 
366
        WeaveError.__init__(self)
 
 
370
class WeaveParentMismatch(WeaveError):
 
 
371
    """Parents are mismatched between two revisions."""
 
 
374
class WeaveInvalidChecksum(WeaveError):
 
 
375
    """Text did not match it's checksum: %(message)s"""
 
 
378
class NoSuchExportFormat(BzrNewError):
 
 
379
    """Export format %(format)r not supported"""
 
 
380
    def __init__(self, format):
 
 
381
        BzrNewError.__init__(self)
 
 
385
class TransportError(BzrError):
 
 
386
    """All errors thrown by Transport implementations should derive
 
 
389
    def __init__(self, msg=None, orig_error=None):
 
 
390
        if msg is None and orig_error is not None:
 
 
391
            msg = str(orig_error)
 
 
392
        BzrError.__init__(self, msg)
 
 
394
        self.orig_error = orig_error
 
 
396
# A set of semi-meaningful errors which can be thrown
 
 
397
class TransportNotPossible(TransportError):
 
 
398
    """This is for transports where a specific function is explicitly not
 
 
399
    possible. Such as pushing files to an HTTP server.
 
 
404
class ConnectionError(TransportError):
 
 
405
    """A connection problem prevents file retrieval.
 
 
406
    This does not indicate whether the file exists or not; it indicates that a
 
 
407
    precondition for requesting the file was not met.
 
 
409
    def __init__(self, msg=None, orig_error=None):
 
 
410
        TransportError.__init__(self, msg=msg, orig_error=orig_error)
 
 
413
class ConnectionReset(TransportError):
 
 
414
    """The connection has been closed."""
 
 
417
class ConflictsInTree(BzrError):
 
 
419
        BzrError.__init__(self, "Working tree has conflicts.")
 
 
421
class ParseConfigError(BzrError):
 
 
422
    def __init__(self, errors, filename):
 
 
425
        message = "Error(s) parsing config file %s:\n%s" % \
 
 
426
            (filename, ('\n'.join(e.message for e in errors)))
 
 
427
        BzrError.__init__(self, message)
 
 
429
class SigningFailed(BzrError):
 
 
430
    def __init__(self, command_line):
 
 
431
        BzrError.__init__(self, "Failed to gpg sign data with command '%s'"
 
 
434
class WorkingTreeNotRevision(BzrError):
 
 
435
    def __init__(self, tree):
 
 
436
        BzrError.__init__(self, "The working tree for %s has changed since"
 
 
437
                          " last commit, but weave merge requires that it be"
 
 
438
                          " unchanged." % tree.basedir)
 
 
440
class CantReprocessAndShowBase(BzrNewError):
 
 
441
    """Can't reprocess and show base.
 
 
442
Reprocessing obscures relationship of conflicting lines to base."""
 
 
444
class GraphCycleError(BzrNewError):
 
 
445
    """Cycle in graph %(graph)r"""
 
 
446
    def __init__(self, graph):
 
 
447
        BzrNewError.__init__(self)
 
 
450
class NotConflicted(BzrNewError):
 
 
451
    """File %(filename)s is not conflicted."""
 
 
452
    def __init__(self, filename):
 
 
453
        BzrNewError.__init__(self)
 
 
454
        self.filename = filename
 
 
456
class MustUseDecorated(Exception):
 
 
457
    """A decorating function has requested its original command be used.
 
 
459
    This should never escape bzr, so does not need to be printable.
 
 
462
class MissingText(BzrNewError):
 
 
463
    """Branch %(base)s is missing revision %(text_revision)s of %(file_id)s"""
 
 
464
    def __init__(self, branch, text_revision, file_id):
 
 
466
        self.base = branch.base
 
 
467
        self.text_revision = text_revision
 
 
468
        self.file_id = file_id