1# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4; encoding:utf8 -*-
2#
3# Copyright 2002 Ben Escoto <ben@emerose.org>
4# Copyright 2007 Kenneth Loafman <kenneth@loafman.com>
5#
6# This file is part of duplicity.
7#
8# Duplicity is free software; you can redistribute it and/or modify it
9# under the terms of the GNU General Public License as published by the
10# Free Software Foundation; either version 2 of the License, or (at your
11# option) any later version.
12#
13# Duplicity is distributed in the hope that it will be useful, but
14# WITHOUT ANY WARRANTY; without even the implied warranty of
15# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16# General Public License for more details.
17#
18# You should have received a copy of the GNU General Public License
19# along with duplicity; if not, write to the Free Software Foundation,
20# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21
22import errno
23
24from duplicity import librsync
25from duplicity import log
26
27tmp_file_index = 1
28
29
30def check_common_error(error_handler, function, args=()):
31    u"""Apply function to args, if error, run error_handler on exception
32
33    This only catches certain exceptions which seem innocent
34    enough.
35
36    """
37    # todo: import here to avoid circular dependency issue
38    from duplicity import path
39
40    try:
41        return function(*args)
42    # except (EnvironmentError, SkipFileException, DSRPPermError,
43    #        RPathException, Rdiff.RdiffException,
44    #        librsync.librsyncError, C.UnknownFileTypeError), exc:
45    #    TracebackArchive.add()
46    except (IOError, EnvironmentError, librsync.librsyncError, path.PathException) as exc:
47        if (not isinstance(exc, EnvironmentError) or
48            hasattr(exc, u"errno") and
49            errno.errorcode[exc.errno] in
50            [u'EPERM', u'ENOENT', u'EACCES', u'EBUSY', u'EEXIST',
51             u'ENOTDIR', u'ENAMETOOLONG', u'EINTR', u'ENOTEMPTY',
52             u'EIO', u'ETXTBSY', u'ESRCH', u'EINVAL']):
53            # Log.exception()
54            if error_handler:
55                return error_handler(exc, *args)
56        else:
57            # Log.exception(1, 2)
58            raise
59
60
61def listpath(path):
62    u"""Like path.listdir() but return [] if error, and sort results"""
63    def error_handler(exc):  # pylint: disable=unused-argument
64        log.Warn(_(u"Error listing directory %s") % path.uc_name)
65        return []
66    dir_listing = check_common_error(error_handler, path.listdir)
67    dir_listing.sort()
68    return dir_listing
69