Initial support for deletion schedule
[pysize.git] / pysize / core / chdir_browsing.py
blobe9efa2af94f2c293374181ecd7177baa7ff9c1a2
1 # This program is free software; you can redistribute it and/or modify
2 # it under the terms of the GNU General Public License as published by
3 # the Free Software Foundation; either version 2 of the License, or
4 # (at your option) any later version.
6 # This program is distributed in the hope that it will be useful,
7 # but WITHOUT ANY WARRANTY; without even the implied warranty of
8 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
9 # GNU Library General Public License for more details.
11 # You should have received a copy of the GNU General Public License
12 # along with this program; if not, write to the Free Software
13 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
15 # See the COPYING file for license information.
17 # Copyright (c) 2006 Guillaume Chazarain <guichaz@yahoo.fr>
19 import os
20 import stat
22 from pysize.core.deletion import filter_deleted
24 # We cannot use a generator because we rely on the finally block to
25 # be sure finalize() will be called. Python 2.5 allows finally block
26 # in generator, but it relies on the GC so it's not sure it will be
27 # called at the right time.
29 # The expected use of these browsing functions is:
31 # cookie = chdir_browsing.init(path)
32 # try:
33 # for child in chdir_browsing.browsedir(cookie, (True|False)):
34 # .. Do something with child ..
35 # finally:
36 # chdir_browsing.finalize(cookie)
38 def init(path):
39 previous_cwd = os.open('.', os.O_RDONLY)
40 try:
41 os.chdir(path)
42 return previous_cwd
43 except OSError, e:
44 os.close(previous_cwd)
45 raise e
47 def browsedir(previous_cwd, cross_device):
48 res = os.listdir('.')
49 if not cross_device:
50 dev = os.stat('.')[stat.ST_DEV]
51 res = [p for p in res if os.stat(p)[stat.ST_DEV] == dev]
52 res = filter_deleted(res)
53 # We want the order to be always so same so that hard links
54 # detection will be consistent across filesystems
55 res.sort()
56 return res
58 def finalize(previous_cwd):
59 if previous_cwd:
60 try:
61 os.fchdir(previous_cwd)
62 finally:
63 os.close(previous_cwd)
65 def listdir(path, cross_device):
66 cookie = init(path)
67 try:
68 return browsedir(cookie, cross_device)
69 finally:
70 finalize(cookie)