allow recursive (-p) directory creation
[enigma2.git] / lib / python / Tools / Directories.py
1 # -*- coding: utf-8 -*-
2
3 from os import path as os_path, mkdir, rmdir, system, walk, stat as os_stat, listdir, readlink, makedirs, error as os_error, symlink
4 from stat import S_IMODE
5 from re import compile
6
7 try:
8         from os import chmod
9         have_chmod = True
10 except:
11         have_chmod = False
12
13 try:
14         from os import utime
15         have_utime = True
16 except:
17         have_utime = False
18
19 SCOPE_TRANSPONDERDATA = 0
20 SCOPE_SYSETC = 1
21 SCOPE_FONTS = 2
22 SCOPE_SKIN = 3
23 SCOPE_SKIN_IMAGE = 4
24 SCOPE_USERETC = 5
25 SCOPE_CONFIG = 6
26 SCOPE_LANGUAGE = 7
27 SCOPE_HDD = 8
28 SCOPE_PLUGINS = 9
29 SCOPE_MEDIA = 10
30 SCOPE_PLAYLIST = 11
31 SCOPE_CURRENT_SKIN = 12
32 SCOPE_DEFAULTDIR = 13
33 SCOPE_DEFAULTPARTITION = 14
34 SCOPE_DEFAULTPARTITIONMOUNTDIR = 14
35
36 PATH_CREATE = 0
37 PATH_DONTCREATE = 1
38 PATH_FALLBACK = 2
39 defaultPaths = {
40                 SCOPE_TRANSPONDERDATA: ("/etc/", PATH_DONTCREATE),
41                 SCOPE_SYSETC: ("/etc/", PATH_DONTCREATE),
42                 SCOPE_FONTS: ("/usr/share/fonts/", PATH_DONTCREATE),
43                 SCOPE_CONFIG: ("/etc/enigma2/", PATH_CREATE),
44                 SCOPE_PLUGINS: ("/usr/lib/enigma2/python/Plugins/", PATH_CREATE),
45     
46                 SCOPE_LANGUAGE: ("/usr/share/enigma2/po/", PATH_DONTCREATE),
47
48                 SCOPE_SKIN: ("/usr/share/enigma2/", PATH_DONTCREATE),
49                 SCOPE_SKIN_IMAGE: ("/usr/share/enigma2/", PATH_DONTCREATE),
50                 SCOPE_HDD: ("/hdd/movie/", PATH_DONTCREATE),
51                 SCOPE_MEDIA: ("/media/", PATH_DONTCREATE),
52                 SCOPE_PLAYLIST: ("/etc/enigma2/playlist/", PATH_CREATE),
53                 
54                 SCOPE_USERETC: ("", PATH_DONTCREATE), # user home directory
55                 
56                 SCOPE_DEFAULTDIR: ("/usr/share/enigma2/defaults/", PATH_CREATE),
57                 SCOPE_DEFAULTPARTITION: ("/dev/mtdblock/6", PATH_DONTCREATE),
58                 SCOPE_DEFAULTPARTITIONMOUNTDIR: ("/usr/share/enigma2/dealer", PATH_CREATE),
59         }
60
61 FILE_COPY = 0 # copy files from fallback dir to the basedir
62 FILE_MOVE = 1 # move files
63 PATH_COPY = 2 # copy the complete fallback dir to the basedir
64 PATH_MOVE = 3 # move the fallback dir to the basedir (can be used for changes in paths)
65 fallbackPaths = {
66                 SCOPE_CONFIG: [("/home/root/", FILE_MOVE),
67                                            ("/usr/share/enigma2/defaults/", FILE_COPY)],
68                 SCOPE_HDD: [("/hdd/movies", PATH_MOVE)]
69         }
70
71 def resolveFilename(scope, base = "", path_prefix = None):
72         if base[0:2] == "~/":
73                 # you can only use the ~/ if we have a prefix directory
74                 assert path_prefix is not None
75                 base = os_path.join(path_prefix, base[2:])
76
77         # don't resolve absolute paths
78         if base[0:1] == '/':
79                 return base
80
81         if scope == SCOPE_CURRENT_SKIN:
82                 from Components.config import config
83                 tmp = defaultPaths[SCOPE_SKIN]
84                 pos = config.skin.primary_skin.value.rfind('/')
85                 if pos != -1:
86                         path = tmp[0]+config.skin.primary_skin.value[:pos+1]
87                 else:
88                         path = tmp[0]
89         else:
90                 tmp = defaultPaths[scope]
91                 path = tmp[0]
92
93         flags = tmp[1]
94
95         if flags == PATH_CREATE:
96                 if not pathExists(path):
97                         mkdir(path)
98
99         fallbackPath = fallbackPaths.get(scope)
100
101         if fallbackPath and not fileExists(path + base):
102                 for x in fallbackPath:
103                         if x[1] == FILE_COPY:
104                                 if fileExists(x[0] + base):
105                                         system("cp " + x[0] + base + " " + path + base)
106                                         break
107                         elif x[1] == FILE_MOVE:
108                                 if fileExists(x[0] + base):
109                                         system("mv " + x[0] + base + " " + path + base)
110                                         break
111                         elif x[1] == PATH_COPY:
112                                 if pathExists(x[0]):
113                                         if not pathExists(defaultPaths[scope][0]):
114                                                 mkdir(path)
115                                         system("cp -a " + x[0] + "* " + path)
116                                         break
117                         elif x[1] == PATH_MOVE:
118                                 if pathExists(x[0]):
119                                         system("mv " + x[0] + " " + path)
120                                         break
121
122         # FIXME: we also have to handle DATADIR etc. here.
123         return path + base
124         # this is only the BASE - an extension must be added later.
125
126 def pathExists(path):
127         return os_path.exists(path)
128
129 def createDir(path, makeParents = False):
130         try:
131                 if makeParents:
132                         makedirs(path)
133                 else:
134                         mkdir(path)
135         except:
136                 ret = 0
137         else:
138                 ret = 1
139         return ret
140
141 def removeDir(path):
142         try:
143                 rmdir(path)
144         except:
145                 ret = 0
146         else:
147                 ret = 1
148         return ret
149
150 def fileExists(f, mode='r'):
151         try:
152                 file = open(f, mode)
153         except IOError:
154                 exists = 0
155         else:
156                 exists = 1
157         return exists
158
159 def getRecordingFilename(basename, dirname = None):
160         # filter out non-allowed characters
161         non_allowed_characters = "/.\\:*?<>|\""
162         filename = ""
163         
164         basename = basename.replace('\xc2\x86', '').replace('\xc2\x87', '')
165         
166         for c in basename:
167                 if c in non_allowed_characters:
168                         c = "_"
169                 filename += c
170
171         if dirname is not None:
172                 filename = ''.join([dirname, filename])
173
174         i = 0
175         while True:
176                 path = resolveFilename(SCOPE_HDD, filename)
177                 if i > 0:
178                         path += "_%03d" % i
179                 try:
180                         open(path + ".ts")
181                         i += 1
182                 except IOError:
183                         return path
184
185 # this is clearly a hack:
186 def InitFallbackFiles():
187         resolveFilename(SCOPE_CONFIG, "userbouquet.favourites.tv")
188         resolveFilename(SCOPE_CONFIG, "bouquets.tv")
189         resolveFilename(SCOPE_CONFIG, "userbouquet.favourites.radio")
190         resolveFilename(SCOPE_CONFIG, "bouquets.radio")
191
192 # returns a list of tuples containing pathname and filename matching the given pattern
193 # example-pattern: match all txt-files: ".*\.txt$"
194 def crawlDirectory(directory, pattern):
195         expression = compile(pattern)
196         list = []
197         for root, dirs, files in walk(directory):
198                 for file in files:
199                         if expression.match(file) is not None:
200                                 list.append((root, file))
201         return list
202
203 def copyfile(src, dst):
204         try:
205                 f1 = open(src, "rb")
206                 if os_path.isdir(dst):
207                         dst = os_path.join(dst, os_path.basename(src))
208                 f2 = open(dst, "w+b")
209                 while True:
210                         buf = f1.read(16*1024)
211                         if not buf:
212                                 break
213                         f2.write(buf)
214                 st = os_stat(src)
215                 mode = S_IMODE(st.st_mode)
216                 if have_chmod:
217                         chmod(dst, mode)
218                 if have_utime:
219                         utime(dst, (st.st_atime, st.st_mtime))
220         except:
221                 print "copy", src, "to", dst, "failed!"
222                 return -1
223         return 0
224
225 def copytree(src, dst, symlinks=False):
226         names = listdir(src)
227         if os_path.isdir(dst):
228                 dst = os_path.join(dst, os_path.basename(src))
229                 if not os_path.isdir(dst):
230                         mkdir(dst)
231         else:
232                 makedirs(dst)
233         for name in names:
234                 srcname = os_path.join(src, name)
235                 dstname = os_path.join(dst, name)
236                 try:
237                         if symlinks and os_path.islink(srcname):
238                                 linkto = readlink(srcname)
239                                 symlink(linkto, dstname)
240                         elif os_path.isdir(srcname):
241                                 copytree(srcname, dstname, symlinks)
242                         else:
243                                 copyfile(srcname, dstname)
244                 except:
245                         print "dont copy srcname (no file or link or folder)"
246         try:
247                 st = os_stat(src)
248                 mode = S_IMODE(st.st_mode)
249                 if have_chmod:
250                         chmod(dst, mode)
251                 if have_utime:
252                         utime(dst, (st.st_atime, st.st_mtime))
253         except:
254                 print "copy stats for", src, "failed!"