Setting tag myplc-5.3-5
[myplc.git] / bin / clean-empty-dirs.py
1 #!/usr/bin/python
2 ###
3 ### utility script for cleaning empty directories
4 ### useful to clean up /var/tmp/bootmedium
5 ### 
6
7 """
8 Usage: $0 dir [ .. dir]
9 scans all provided directories and prunes any empty directory under
10 the arg directories are always preserved 
11 """
12
13 import os,sys
14
15 ### cleans up a everything under a given root
16 def clean_root (path, cleanRoot = False):
17
18     if not os.path.isdir(path):
19         return
20     
21     # scan dir contents
22     files=os.listdir(path)
23
24     for x in files:
25         fullpath=os.path.join(path, x)
26         if os.path.isfile(fullpath):
27             # we do not remove files
28             return
29         elif os.path.isdir(fullpath):
30             clean_root(fullpath,True)
31
32     if (cleanRoot):
33         # rescan, and clean if empty
34         files=os.listdir(path)
35         if not files:
36             os.rmdir(path)
37
38 ERROR_STR= """Error removing %(path)s, %(error)s """
39
40 def main (dirs):
41
42     for dir in dirs:
43         try:
44             if dir.index("/") != 0:
45                 print "%s: args must be absolute paths"%(sys.argv[0])
46                 print "%s: %s ignored"%(sys.argv[0],dir)
47             else:
48                 clean_root(dir)
49         except OSError, (errno, strerror):
50             print ERROR_STR % {'path' : path, 'error': strerror }
51
52 if __name__ == '__main__':
53     main (sys.argv[1:])