]> git.phdru.name Git - ppu.git/blob - scripts/rm.py
17d4164dcb35f14e2da2f692d09732876be5f962
[ppu.git] / scripts / rm.py
1 #! /usr/bin/env python
2
3 import argparse
4 import os
5 import shutil
6
7 try:
8     raw_input
9 except NameError:  # Python 3
10     raw_input = input
11
12
13 if __name__ == '__main__':
14     parser = argparse.ArgumentParser(description='Remove files/directories')
15     parser.add_argument('-f', '--force', action='store_true',
16                         help='force (ignore non-existing files and errors)')
17     parser.add_argument('-r', '--recursive', action='store_true',
18                         help='remove directories recursively')
19     parser.add_argument('names', nargs='+',
20                         help='files/directories names to remove')
21     args = parser.parse_args()
22
23     for name in args.names:
24         if args.force and not os.path.exists(name):
25             continue
26         is_dir = os.path.isdir(name)
27         if not os.access(name, os.W_OK):
28             if is_dir:
29                 ftype = 'directory'
30             else:
31                 ftype = 'file'
32             try:
33                 while True:
34                     rmw = raw_input(
35                         "rm.py: remove write-protected %s '%s'? [y/n] "
36                         % (ftype, name))
37                     answer = rmw[:1].lower()
38                     if answer == 'y':
39                         break
40                     elif answer == 'n':
41                         raise StopIteration
42                     else:
43                         continue
44             except StopIteration:
45                 continue
46         if is_dir:
47             if args.recursive:
48                 shutil.rmtree(name, args.force)
49             else:
50                 os.rmdir(name)
51         else:
52             os.unlink(name)