]> arthur.barton.de Git - bup.git/blob - drecurse.py
Speed up cmd-drecurse by 40%.
[bup.git] / drecurse.py
1 import stat, heapq
2 from helpers import *
3
4 try:
5     O_LARGEFILE = os.O_LARGEFILE
6 except AttributeError:
7     O_LARGEFILE = 0
8
9
10 # the use of fchdir() and lstat() is for two reasons:
11 #  - help out the kernel by not making it repeatedly look up the absolute path
12 #  - avoid race conditions caused by doing listdir() on a changing symlink
13 class OsFile:
14     def __init__(self, path):
15         self.fd = None
16         self.fd = os.open(path, os.O_RDONLY|O_LARGEFILE|os.O_NOFOLLOW)
17         
18     def __del__(self):
19         if self.fd:
20             fd = self.fd
21             self.fd = None
22             os.close(fd)
23
24     def fchdir(self):
25         os.fchdir(self.fd)
26
27     def stat(self):
28         return os.fstat(self.fd)
29
30
31 _IFMT = stat.S_IFMT(0xffffffff)  # avoid function call in inner loop
32 def _dirlist():
33     l = []
34     for n in os.listdir('.'):
35         try:
36             st = os.lstat(n)
37         except OSError, e:
38             add_error(Exception('%s: %s' % (realpath(n), str(e))))
39             continue
40         if (st.st_mode & _IFMT) == stat.S_IFDIR:
41             n += '/'
42         l.append((n,st))
43     l.sort(reverse=True)
44     return l
45
46
47 def _recursive_dirlist(prepend, xdev):
48     for (name,pst) in _dirlist():
49         if name.endswith('/'):
50             if xdev != None and pst.st_dev != xdev:
51                 log('Skipping %r: different filesystem.\n' % (prepend+name))
52                 continue
53             try:
54                 OsFile(name).fchdir()
55             except OSError, e:
56                 add_error('%s: %s' % (prepend, e))
57             else:
58                 for i in _recursive_dirlist(prepend=prepend+name, xdev=xdev):
59                     yield i
60                 os.chdir('..')
61         yield (prepend + name, pst)
62
63
64 def recursive_dirlist(paths, xdev):
65     startdir = OsFile('.')
66     try:
67         assert(type(paths) != type(''))
68         for path in paths:
69             try:
70                 rpath = os.path.realpath(path)
71                 pfile = OsFile(rpath)
72             except OSError, e:
73                 add_error(e)
74                 continue
75             pst = pfile.stat()
76             if xdev:
77                 xdev = pst.st_dev
78             else:
79                 xdev = None
80             if stat.S_ISDIR(pst.st_mode):
81                 pfile.fchdir()
82                 prepend = os.path.join(path, '')
83                 for i in _recursive_dirlist(prepend=prepend, xdev=xdev):
84                     yield i
85                 startdir.fchdir()
86             else:
87                 prepend = path
88             yield (prepend,pst)
89     except:
90         try:
91             startdir.fchdir()
92         except:
93             pass
94         raise