~bzr-pqm/bzr/bzr.dev

1185.16.103 by mbp at sourcefrog
Fix up all calls to InvalidRevisionId() to specify parameters.
1
# (C) 2005 Canonical
1 by mbp at sourcefrog
import from baz patch-364
2
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.
7
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.
12
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
16
1185.16.61 by mbp at sourcefrog
- start introducing hct error classes
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
1185.31.50 by John Arbash Meinel
Renaming test_sftp.py => test_sftp_transport.py, so that 'bzr selftest transport' will run it too
37
...   if hasattr(sys.exc_value, 'path'):
38
...     print sys.exc_value.path
1185.16.61 by mbp at sourcefrog
- start introducing hct error classes
39
bzrlib.errors.NotBranchError
40
Not a branch: /foo/bar
41
/foo/bar
42
43
Therefore:
44
45
 * create a new exception class for any class of error that can be
46
   usefully distinguished.
47
48
 * the printable form of an exception is generated by the base class
49
   __str__ method
1185.33.7 by Martin Pool
Better formatting of builtin errors
50
51
Exception strings should start with a capital letter and not have a final
52
fullstop.
1185.16.61 by mbp at sourcefrog
- start introducing hct error classes
53
"""
54
55
# based on Scott James Remnant's hct error classes
56
1185.16.62 by mbp at sourcefrog
- convert NotBranchError to new exception base
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 
59
# to me.
60
1185.16.63 by Martin Pool
- more error conversion
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.
64
65
# TODO: Convert all the other error classes here to BzrNewError, and eliminate
66
# the old one.
1185.16.62 by mbp at sourcefrog
- convert NotBranchError to new exception base
67
1185.16.61 by mbp at sourcefrog
- start introducing hct error classes
68
1 by mbp at sourcefrog
import from baz patch-364
69
class BzrError(StandardError):
1193 by Martin Pool
- better string formatting of BzrErrors with explanation
70
    def __str__(self):
1393.1.64 by Martin Pool
- improved display of some errors, including NotBranchError
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__ + ': '
75
        n = ''
1195 by Martin Pool
- better error display
76
        if len(self.args) == 1:
1449 by Robert Collins
teach check about ghosts
77
            return str(self.args[0])
1195 by Martin Pool
- better error display
78
        elif len(self.args) == 2:
1193 by Martin Pool
- better string formatting of BzrErrors with explanation
79
            # further explanation or suggestions
1405 by Robert Collins
remove some of the upgrade code that was duplicated with inventory_entry, and give all inventory entries a weave
80
            try:
1393.1.64 by Martin Pool
- improved display of some errors, including NotBranchError
81
                return n + '\n  '.join([self.args[0]] + self.args[1])
1405 by Robert Collins
remove some of the upgrade code that was duplicated with inventory_entry, and give all inventory entries a weave
82
            except TypeError:
1393.1.64 by Martin Pool
- improved display of some errors, including NotBranchError
83
                return n + "%r" % self
1193 by Martin Pool
- better string formatting of BzrErrors with explanation
84
        else:
1393.1.64 by Martin Pool
- improved display of some errors, including NotBranchError
85
            return n + `self.args`
1193 by Martin Pool
- better string formatting of BzrErrors with explanation
86
1185.1.14 by Robert Collins
remove more duplicate merged hunks. Bad MERGE3, BAD.
87
1185.16.62 by mbp at sourcefrog
- convert NotBranchError to new exception base
88
class BzrNewError(BzrError):
1185.16.61 by mbp at sourcefrog
- start introducing hct error classes
89
    """bzr error"""
90
    # base classes should override the docstring with their human-
91
    # readable explanation
92
93
    def __init__(self, **kwds):
94
        for key, value in kwds.items():
95
            setattr(self, key, value)
96
97
    def __str__(self):
98
        try:
99
            return self.__doc__ % self.__dict__
100
        except (NameError, ValueError, KeyError), e:
101
            return 'Unprintable exception %s: %s' \
102
                % (self.__class__.__name__, str(e))
103
104
1185.16.63 by Martin Pool
- more error conversion
105
class BzrCheckError(BzrNewError):
106
    """Internal check failed: %(message)s"""
107
    def __init__(self, message):
1185.16.103 by mbp at sourcefrog
Fix up all calls to InvalidRevisionId() to specify parameters.
108
        BzrNewError.__init__(self)
1185.16.63 by Martin Pool
- more error conversion
109
        self.message = message
110
111
112
class InvalidEntryName(BzrNewError):
113
    """Invalid entry name: %(name)s"""
114
    def __init__(self, name):
1185.16.103 by mbp at sourcefrog
Fix up all calls to InvalidRevisionId() to specify parameters.
115
        BzrNewError.__init__(self)
1185.16.63 by Martin Pool
- more error conversion
116
        self.name = name
117
118
119
class InvalidRevisionNumber(BzrNewError):
120
    """Invalid revision number %(revno)d"""
121
    def __init__(self, revno):
1185.16.103 by mbp at sourcefrog
Fix up all calls to InvalidRevisionId() to specify parameters.
122
        BzrNewError.__init__(self)
1185.16.63 by Martin Pool
- more error conversion
123
        self.revno = revno
124
125
126
class InvalidRevisionId(BzrNewError):
1185.16.103 by mbp at sourcefrog
Fix up all calls to InvalidRevisionId() to specify parameters.
127
    """Invalid revision-id {%(revision_id)s} in %(branch)s"""
128
    def __init__(self, revision_id, branch):
129
        BzrNewError.__init__(self)
1185.12.90 by Aaron Bentley
Fixed InvalidRevisionID handling in Branch.get_revision_xml
130
        self.revision_id = revision_id
1185.16.103 by mbp at sourcefrog
Fix up all calls to InvalidRevisionId() to specify parameters.
131
        self.branch = branch
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
132
133
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
134
class NoWorkingTree(BzrNewError):
135
    """No WorkingTree exists for %s(base)."""
136
    
137
    def __init__(self, base):
138
        BzrNewError.__init__(self)
139
        self.base = base
1506 by Robert Collins
Merge Johns current integration work.
140
141
329 by Martin Pool
- refactor command functions into command classes
142
class BzrCommandError(BzrError):
143
    # Error from malformed user command
1495 by Robert Collins
Add a --create-prefix to the new push command.
144
    # This is being misused as a generic exception
145
    # pleae subclass. RBC 20051030
1185.54.18 by Aaron Bentley
Noted difference of opinion wrt BzrCommandError
146
    #
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
1393.1.64 by Martin Pool
- improved display of some errors, including NotBranchError
151
    def __str__(self):
152
        return self.args[0]
1 by mbp at sourcefrog
import from baz patch-364
153
1495 by Robert Collins
Add a --create-prefix to the new push command.
154
155
class BzrOptionError(BzrCommandError):
156
    """Some missing or otherwise incorrect option was supplied."""
157
158
    
1185.16.65 by mbp at sourcefrog
- new commit --strict option
159
class StrictCommitFailed(Exception):
160
    """Commit refused because there are unknowns in the tree."""
1 by mbp at sourcefrog
import from baz patch-364
161
1185.31.41 by John Arbash Meinel
Creating a PathNotChild exception, and using relpath in HTTPTestUtil
162
1185.31.44 by John Arbash Meinel
Cleaned up Exceptions for all transports.
163
class PathError(BzrNewError):
164
    """Generic path error: %(path)r%(extra)s)"""
165
    def __init__(self, path, extra=None):
166
        BzrNewError.__init__(self)
167
        self.path = path
168
        if extra:
169
            self.extra = ': ' + str(extra)
170
        else:
171
            self.extra = ''
172
173
174
class NoSuchFile(PathError):
175
    """No such file: %(path)r%(extra)s"""
176
177
178
class FileExists(PathError):
179
    """File exists: %(path)r%(extra)s"""
180
181
182
class PermissionDenied(PathError):
183
    """Permission denied: %(path)r%(extra)s"""
184
185
1185.31.41 by John Arbash Meinel
Creating a PathNotChild exception, and using relpath in HTTPTestUtil
186
class PathNotChild(BzrNewError):
1185.31.44 by John Arbash Meinel
Cleaned up Exceptions for all transports.
187
    """Path %(path)r is not a child of path %(base)r%(extra)s"""
188
    def __init__(self, path, base, extra=None):
1185.31.41 by John Arbash Meinel
Creating a PathNotChild exception, and using relpath in HTTPTestUtil
189
        BzrNewError.__init__(self)
190
        self.path = path
191
        self.base = base
1185.31.44 by John Arbash Meinel
Cleaned up Exceptions for all transports.
192
        if extra:
193
            self.extra = ': ' + str(extra)
194
        else:
195
            self.extra = ''
1185.31.41 by John Arbash Meinel
Creating a PathNotChild exception, and using relpath in HTTPTestUtil
196
197
1185.16.62 by mbp at sourcefrog
- convert NotBranchError to new exception base
198
class NotBranchError(BzrNewError):
199
    """Not a branch: %(path)s"""
1185.16.61 by mbp at sourcefrog
- start introducing hct error classes
200
    def __init__(self, path):
1185.16.62 by mbp at sourcefrog
- convert NotBranchError to new exception base
201
        BzrNewError.__init__(self)
202
        self.path = path
203
573 by Martin Pool
- new exception NotBranchError
204
1185.35.32 by Aaron Bentley
Fixed handling of files in mixed branches
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)
209
        self.branch = branch
210
        self.branch_base = branch.base
211
        self.path = path
212
213
1185.1.53 by Robert Collins
raise a specific error on unsupported branches so that they can be distinguished from generic errors
214
class UnsupportedFormatError(BzrError):
215
    """Specified path is a bzr branch that we cannot read."""
216
    def __str__(self):
217
        return 'unsupported branch format: %s' % self.args[0]
218
219
1185.16.72 by Martin Pool
[merge] from robert and fix up tests
220
class NotVersionedError(BzrNewError):
221
    """%(path)s is not versioned"""
222
    def __init__(self, path):
223
        BzrNewError.__init__(self)
224
        self.path = path
753 by Martin Pool
- new exception NotVersionedError
225
226
599 by Martin Pool
- better error reporting from smart_add
227
class BadFileKindError(BzrError):
228
    """Specified file is of a kind that cannot be added.
229
230
    (For example a symlink or device file.)"""
231
232
233
class ForbiddenFileError(BzrError):
234
    """Cannot operate on a file because it is a control file."""
235
236
614 by Martin Pool
- unify two defintions of LockError
237
class LockError(Exception):
1185.16.63 by Martin Pool
- more error conversion
238
    """Lock error"""
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
882 by Martin Pool
- Optionally raise EmptyCommit if there are no changes. Test for this.
242
243
1417.1.6 by Robert Collins
introduce transactions for grouping actions done to and with branches
244
class CommitNotPossible(LockError):
245
    """A commit was attempted but we do not have a write lock open."""
246
247
248
class AlreadyCommitted(LockError):
249
    """A rollback was requested, but is not able to be accomplished."""
250
251
1417.1.8 by Robert Collins
use transactions in the weave store interface, which enables caching for log
252
class ReadOnlyError(LockError):
253
    """A write attempt was made in a read only transaction."""
254
255
1185.16.63 by Martin Pool
- more error conversion
256
class PointlessCommit(BzrNewError):
1185.16.64 by Martin Pool
- more error conversions
257
    """No changes to commit"""
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
258
1185.22.1 by Michael Ellerman
Implement strict commits with --strict flag.
259
class StrictCommitFailed(Exception):
260
    """Commit refused because there are unknowns in the tree."""
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
261
262
class NoSuchRevision(BzrError):
263
    def __init__(self, branch, revision):
264
        self.branch = branch
265
        self.revision = revision
266
        msg = "Branch %s has no revision %s" % (branch, revision)
267
        BzrError.__init__(self, msg)
268
1034 by Martin Pool
- merge bzrlib.revision.is_ancestor from aaron
269
1192 by Martin Pool
- clean up code for retrieving stored inventories
270
class HistoryMissing(BzrError):
271
    def __init__(self, branch, object_type, object_id):
272
        self.branch = branch
273
        BzrError.__init__(self,
274
                          '%s is missing %s {%s}'
275
                          % (branch, object_type, object_id))
276
277
1185.2.1 by Lalo Martins
moving DivergedBranches from bzrlib.branch to bzrlib.errors, obeying:
278
class DivergedBranches(BzrError):
279
    def __init__(self, branch1, branch2):
1185.56.1 by Michael Ellerman
Simplify handling of DivergedBranches in cmd_pull()
280
        BzrError.__init__(self, "These branches have diverged.  Try merge.")
1185.2.1 by Lalo Martins
moving DivergedBranches from bzrlib.branch to bzrlib.errors, obeying:
281
        self.branch1 = branch1
282
        self.branch2 = branch2
283
1390 by Robert Collins
pair programming worx... merge integration and weave
284
1105 by Martin Pool
- expose 'find-merge-base' as a new expert command,
285
class UnrelatedBranches(BzrCommandError):
286
    def __init__(self):
287
        msg = "Branches have no common ancestor, and no base revision"\
288
            " specified."
289
        BzrCommandError.__init__(self, msg)
290
974.1.80 by Aaron Bentley
Improved merge error handling and testing
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)
296
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)
1105 by Martin Pool
- expose 'find-merge-base' as a new expert command,
302
974.2.7 by aaron.bentley at utoronto
Merged from bzr.24
303
class NotAncestor(BzrError):
304
    def __init__(self, rev_id, not_ancestor_id):
1185.1.14 by Robert Collins
remove more duplicate merged hunks. Bad MERGE3, BAD.
305
        msg = "Revision %s is not an ancestor of %s" % (not_ancestor_id, 
306
                                                        rev_id)
307
        BzrError.__init__(self, msg)
308
        self.rev_id = rev_id
309
        self.not_ancestor_id = not_ancestor_id
1185.1.12 by Robert Collins
merge in lsdiff/filterdiff friendliness
310
311
974.1.30 by aaron.bentley at utoronto
Changed copy_multi to permit failure and return a tuple, tested missing required revisions
312
class InstallFailed(BzrError):
313
    def __init__(self, revisions):
1185.1.14 by Robert Collins
remove more duplicate merged hunks. Bad MERGE3, BAD.
314
        msg = "Could not install revisions:\n%s" % " ,".join(revisions)
315
        BzrError.__init__(self, msg)
974.1.30 by aaron.bentley at utoronto
Changed copy_multi to permit failure and return a tuple, tested missing required revisions
316
        self.revisions = revisions
1154 by Martin Pool
- fix imports for moved errors
317
318
319
class AmbiguousBase(BzrError):
320
    def __init__(self, bases):
321
        msg = "The correct base is unclear, becase %s are all equally close" %\
322
            ", ".join(bases)
323
        BzrError.__init__(self, msg)
324
        self.bases = bases
325
974.1.80 by Aaron Bentley
Improved merge error handling and testing
326
class NoCommits(BzrError):
327
    def __init__(self, branch):
328
        msg = "Branch %s has no commits." % branch
329
        BzrError.__init__(self, msg)
1185.10.1 by Aaron Bentley
Added --basis option to bzr branch
330
331
class UnlistableStore(BzrError):
332
    def __init__(self, store):
333
        BzrError.__init__(self, "Store %s is not listable" % store)
334
335
class UnlistableBranch(BzrError):
336
    def __init__(self, br):
337
        BzrError.__init__(self, "Stores for branch %s are not listable" % br)
1392 by Robert Collins
reinstate testfetch test case
338
339
1185.16.116 by mbp at sourcefrog
Move weave errors into bzrlib.errors and make consistent with new system.
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
345
346
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
352
        self.weave = weave
353
354
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
360
        self.weave = weave
361
362
363
class WeaveFormatError(WeaveError):
364
    """Weave invariant violated: %(what)s"""
365
    def __init__(self, what):
366
        WeaveError.__init__(self)
367
        self.what = what
368
369
370
class WeaveParentMismatch(WeaveError):
371
    """Parents are mismatched between two revisions."""
372
    
1393.2.1 by John Arbash Meinel
Merged in split-storage-2 branch. Need to cleanup a little bit more still.
373
1185.50.23 by John Arbash Meinel
Adding sha1 check when weave extracts a text.
374
class WeaveInvalidChecksum(WeaveError):
375
    """Text did not match it's checksum: %(message)s"""
376
377
1185.31.12 by John Arbash Meinel
Refactored the export code to make it easier to add new export formats.
378
class NoSuchExportFormat(BzrNewError):
379
    """Export format %(format)r not supported"""
380
    def __init__(self, format):
381
        BzrNewError.__init__(self)
382
        self.format = format
383
384
1185.11.9 by John Arbash Meinel
Most tests pass, some problems with unavailable socket recv
385
class TransportError(BzrError):
386
    """All errors thrown by Transport implementations should derive
387
    from this class.
388
    """
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)
393
        self.msg = msg
394
        self.orig_error = orig_error
395
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.
400
    """
401
    pass
402
1185.31.44 by John Arbash Meinel
Cleaned up Exceptions for all transports.
403
404
class ConnectionError(TransportError):
405
    """A connection problem prevents file retrieval.
1185.35.31 by Aaron Bentley
Throw ConnectionError instead of NoSuchFile except when we get a 404
406
    This does not indicate whether the file exists or not; it indicates that a
407
    precondition for requesting the file was not met.
408
    """
1185.31.44 by John Arbash Meinel
Cleaned up Exceptions for all transports.
409
    def __init__(self, msg=None, orig_error=None):
410
        TransportError.__init__(self, msg=msg, orig_error=orig_error)
411
1185.11.9 by John Arbash Meinel
Most tests pass, some problems with unavailable socket recv
412
413
class ConnectionReset(TransportError):
414
    """The connection has been closed."""
415
    pass
416
1185.14.10 by Aaron Bentley
Commit aborts with conflicts in the tree.
417
class ConflictsInTree(BzrError):
418
    def __init__(self):
419
        BzrError.__init__(self, "Working tree has conflicts.")
1185.12.49 by Aaron Bentley
Switched to ConfigObj
420
421
class ParseConfigError(BzrError):
422
    def __init__(self, errors, filename):
423
        if filename is None:
424
            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)
1185.12.52 by Aaron Bentley
Merged more config stuff from Robert
428
1442.1.58 by Robert Collins
gpg signing of content
429
class SigningFailed(BzrError):
430
    def __init__(self, command_line):
431
        BzrError.__init__(self, "Failed to gpg sign data with command '%s'"
432
                               % command_line)
1185.12.83 by Aaron Bentley
Preliminary weave merge support
433
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)
1185.12.104 by Aaron Bentley
Merged Martin's latest
439
1185.24.1 by Aaron Bentley
Got reprocessing working
440
class CantReprocessAndShowBase(BzrNewError):
441
    """Can't reprocess and show base.
442
Reprocessing obscures relationship of conflicting lines to base."""
1185.24.2 by Aaron Bentley
Merge from mainline
443
1185.16.114 by mbp at sourcefrog
Improved topological sort
444
class GraphCycleError(BzrNewError):
445
    """Cycle in graph %(graph)r"""
446
    def __init__(self, graph):
447
        BzrNewError.__init__(self)
448
        self.graph = graph
1185.35.1 by Aaron Bentley
Implemented conflicts.restore
449
450
class NotConflicted(BzrNewError):
1185.35.4 by Aaron Bentley
Implemented remerge
451
    """File %(filename)s is not conflicted."""
1185.35.1 by Aaron Bentley
Implemented conflicts.restore
452
    def __init__(self, filename):
453
        BzrNewError.__init__(self)
454
        self.filename = filename
1185.35.13 by Aaron Bentley
Merged Martin
455
1492 by Robert Collins
Support decoration of commands.
456
class MustUseDecorated(Exception):
457
    """A decorating function has requested its original command be used.
458
    
459
    This should never escape bzr, so does not need to be printable.
460
    """
461
1185.35.42 by Aaron Bentley
Fixed fetch to be safer wrt ghosts and corrupt branches
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):
465
        self.branch = branch
466
        self.base = branch.base
467
        self.text_revision = text_revision
468
        self.file_id = file_id