Fix copyright
[yaffs2.git] / direct / test-framework / python / yaffs_importer.py
1 ##
2 ## YAFFS: Yet Another Flash File System. A NAND-flash specific file system.
3 ##
4 # Copyright (C) 2002-2018 Aleph One Ltd.
5 ##
6 ## Created by Timothy Manning <timothy@yaffs.net>
7 ##
8 ## This program is free software; you can redistribute it and/or modify
9 ## it under the terms of the GNU General Public License version 2 as
10 ## published by the Free Software Foundation.
11 ##
12
13 import os
14 from yaffsfs import *
15 import sys
16 import ctypes
17
18
19 dir_in_snapshot=[]
20 files_in_snapshot=[]
21 symlinks_in_snapshot=[]
22 unknown_in_snapshot=[]
23 is_mount_in_snapshot=[]
24 def check_for_yaffs_errors(output):
25     if output<0:
26         ##error has happened
27         error=ctypes.c_int()
28         error=yaffs_get_error()
29         debug_message("error######################################",0)
30         debug_message(("error code", error),  0)
31         error_message=ctypes.c_char_p()
32         error_message.value=yaffs_error_to_str(error);
33         print "error message", error_message.value
34         
35
36 def debug_message(message, debug_level):
37     """note: that debug level 0 will always be printed unless debug_level is set to -1"""
38     """level 0 error messages"""
39     """level 1 basic tasks are shown(creating, deleating,ect)"""
40     """level 2 all process are shown"""
41     """level 3 shows minor tasks such as join_paths, ect"""
42     """level 4 is used for bug hunting and shows each step in detail"""
43     if current_debug_level>=debug_level:
44 #        for i in range(0, len(message)):
45 #            print message, 
46 #        print"\n \n \n"
47         print message
48 def join_paths(path1, path2):
49     new_path=path1
50     if path1[len(path1)-1]=="/"and path2[0]=="/":
51         new_path+=path2[1:]
52     elif path1[len(path1)-1]!="/"and path2[0]!="/":
53         new_path+="/"
54         new_path+=path2
55     else:
56         new_path+=path2
57     
58     debug_message(("adding path ", path1, " to ",  path2, " resulting path: ", new_path), 3)
59     return new_path
60     
61 def subtract_paths(path1, path2):
62     if len(path1)>len(path2):
63         if path1[len(path1)-1]!="/":
64             path1 +="/"
65         if path2[len(path2)-1]!="/":
66             path2 += "/"
67         debug_message("the two path1 is longer than path2 and can therefore be subtracted.", 4)
68         ##if the two paths are diretly subtractable
69         if path1[0:len (path2)-1]==path2:
70             debug_message("the two paths are direcly subtractable", 4)
71             new_path=path1[len(path2):]
72         elif path1[1:len (path2)-1]==path2:
73             debug_message("the path1 has one more charecter at the begining. assuming that the first chareter is a slash", 4)##fix this assumption.
74             new_path=path1[len(path2)+1:]
75         elif path1[1:len (path2)]==path2[1:]:
76             debug_message("the path2 has one more charecter at the begining. assuming that the first chareter is a slash", 4)##fix this assumption.
77
78             new_path=path1[len(path2)-1:]
79         else :
80             debug_message("error:could not subtract paths", 0)
81             debug_message( ("paths do not match:"+ path1+ "  "+path2), 0)
82             return 0
83     else :
84         debug_message( ("cannot subtract path2(:", path2, ") from path1(", path1, ")because path 2 is too long"), 0)
85         
86         return 0
87     debug_message(("subtracting paths ", path2, " from ",  path1, " resulting path: ", new_path), 3)
88     return new_path
89     
90 def create_file(file):
91 #    freespace=ctypes.c_longlong
92 #    freespace.value=yaffs_freespace(yaffs_root_dir_path)
93 #    print "yaffs free space:", freespace.value
94     debug_message( "\n \n \n", 2)
95     file_path= join_paths(yaffs_root_dir_path, file["path"][len(path):])
96     debug_message( ("creating file:", file_path), 2)
97     debug_message (("mode", file["mode"]), 2)
98     debug_message("opening file",2)
99 #    yaffs_ls(file["path"])
100
101     ##if there is already a file in yaffs then remove the file . this is to prevent yaffs from opening and writing to a read only file
102     if yaffs_access(file_path, 0)==0:##the 0 means does it exist. 
103         debug_message ("file already exists in yaffs", 2)
104         output=yaffs_unlink(file_path)
105         debug_message(("unlinking", file_path, output), 2)
106         check_for_yaffs_errors(output)
107     
108     current_handle=yaffs_open(file_path, yaffs_O_CREAT | yaffs_O_TRUNC| yaffs_O_RDWR, yaffs_S_IREAD | yaffs_S_IWRITE)  ##opens a file with mode set to write
109     debug_message(("current_handle", current_handle), 2)
110     data_file=open(file["path"], "r")
111     output=yaffs_lseek(current_handle, 0, 0)
112     if output==-1:
113         ##if there is no more space in the emfile then this is where it will show up.
114         freespace=ctypes.c_longlong
115         freespace.value=yaffs_freespace(yaffs_root_dir_path)
116         print "yaffs free space:", freespace.value
117
118         if freespace.value==0:
119             #print "yaffs free space:", yaffs_freespace(yaffs_root_dir_path)
120             print "yaffs is out of space exiting program"
121            #sys.exit() 
122         debug_message("error with yaffs lseeking", 2)
123         
124         check_for_yaffs_errors(output)
125     data_to_be_written= data_file.read()
126     
127     
128     length_of_file=len(data_to_be_written)
129     debug_message (("length of data to be written",length_of_file), 3) 
130     output=yaffs_write(current_handle,data_to_be_written , length_of_file)
131     if output>=0:
132         debug_message(( "writing to ", file_path," ",  output), 1)
133     else :
134         debug_message(( "error writing file:", output), 0)
135         check_for_yaffs_errors(output)
136     output=yaffs_ftruncate(current_handle, length_of_file)
137     if output>=0:
138         debug_message(( "truncating file:", output), 2)
139     else :
140         debug_message(( "error truncating file:", output), 0)
141         check_for_yaffs_errors(output)
142     output=yaffs_close(current_handle)
143     if output>=0:
144         debug_message(( "closing file:", output), 2)
145     else :
146         debug_message(( "error closing file:", output), 0)
147         check_for_yaffs_errors(output)
148     ##changes the mode of the yaffs file to be the same as the scanned file
149     yaffs_chmod(file_path, file["mode"]);
150     if output>=0:
151         debug_message(( "chmoding file:", output), 2)
152     else :
153         debug_message(( "error chmoding file:", output), 0)
154         check_for_yaffs_errors(output)
155
156
157
158 def create_dir(dir, scanned_path, yaffs_path):
159     debug_message( "\n \n \n", 2)
160     absolute_dir_path=join_paths(yaffs_path, subtract_paths(dir["path"],scanned_path)) 
161     debug_message( ("creating dir:", absolute_dir_path), 2)
162     debug_message (("mode(in octal", oct(dir["mode"])), 2)
163
164        ##this is a bug in yaffs which will not make a dir if there is a slash on the end
165     if absolute_dir_path[len(absolute_dir_path)-1]=="/":
166         absolute_dir_path=absolute_dir_path[0:len(absolute_dir_path)-1]
167         debug_message (("path has slash on the end. removing slash new path is:",absolute_dir_path) , 4)
168         
169         
170     ##if there is already a dir in yaffs then remove the dir . this is to clean the yaffs folder if it already exists.
171     ##in yaffs all of the files in the dir to be removed must be empty.
172     ##need to create a reverse ls to delete all of the files first.
173 #    if yaffs_access(absolute_dir_path, 0)==0:##the 0 means does it exist. 
174 #        debug_message ("folder already exists in yaffs", 2)
175 #        output=yaffs_rmdir(absolute_dir_path)
176 #        debug_message(("unlinking", absolute_dir_path, output), 2)
177 #        check_for_yaffs_errors(output)
178         
179  
180         
181     output=yaffs_mkdir(absolute_dir_path, dir["mode"] )
182     if output>=0:
183         debug_message(( "created dir:", absolute_dir_path," ", output), 1)
184     else :
185         debug_message(( "error creating dir ", absolute_dir_path, " ", output), 0)
186         check_for_yaffs_errors(output)
187         if output==17:
188             printf("the directory already exists")
189     
190     
191
192
193 def remove_file_from_path(path):
194     slash_id=[]
195     for i in range(0, len(path)):
196         if path[i]=="/":
197             slash_id.append(i)
198     new_path=path[:slash_id[len(slash_id)-1]]
199     debug_message( ("removed file from path", new_path), 2)
200     return new_path
201     
202 def is_dir_hidden(dir):
203     """this code tests if a directory is hidden (has a ./<name> format) and returns true if it is hidden"""
204     slash_id=[]
205     for i in range(0, len(dir)):
206         if dir[i]=="/":
207             slash_id.append(i)
208
209     if dir[slash_id[len(slash_id)-1]+1]==".":
210         return True
211     else :
212         return False
213     
214 def scan_dir(path, search_hidden_directories=True, ):
215     """this function scans all of the files and directories in a directory. The function then calls its self on any of the directories that it found. this causes it to build up a tree of all the files and directories """
216     global files_in_snapshot
217     global symlinks_in_snapshot
218     global dir_in_snapshot
219     dir_in_current_dir=[]
220     global unknown_in_snapshot
221 #    files_in_snapshot=[]
222 #    symlinks_in_snapshot=[]
223 #    dir_in_snapshot=[]
224 #    dir_in_current_dir=[]
225 #    unknown_in_snapshot=[]
226     if os.path.exists(path)==False:
227         debug_message ("error#############################",0)
228         debug_message (("path:", path, "  doesnot exist"), 0)
229         return 0
230     dir_snapshot=os.listdir(path)
231     for i in range(0, len(dir_snapshot)):
232
233         current_snapshot=os.path.join(path, dir_snapshot[i])
234         ##debug_message (("current snapshot:", current_snapshot), 2)
235         isDir=os.path.isdir(current_snapshot)
236         isFile=os.path.isfile(current_snapshot)
237         isLink=os.path.islink(current_snapshot)
238         isMount=os.path.ismount(current_snapshot)
239
240         stat=os.lstat(current_snapshot)
241         
242         ##note the order of these if and elif statemens is importaint since a file can be symbloic link and a file
243         if isDir:
244             if search_hidden_directories==True or (is_dir_hidden(current_snapshot) ==False or search_hidden_directories==True ) :
245 #                st_mode ##mode of the folder read/write ect
246                 dir_in_snapshot.append({"path":current_snapshot, "mode":stat.st_mode})
247                 dir_in_current_dir.append(current_snapshot)
248             else :
249                 debug_message( ("file is hidden so it is ingored", current_snapshot,), 1)
250         elif  isLink:
251
252             ##for some reason the os.readlink only gives the target link realative to the directory which the symbloic link is in. change this into a absolute path
253             x=current_snapshot
254             x=remove_file_from_path(x)
255             target=join_paths(x,os.readlink(current_snapshot) )
256             symlinks_in_snapshot.append({"path":current_snapshot, "target":target})
257         elif isFile:
258
259 #            stat.st_ino ##inode number
260 #            st_nlink ##number of hard links to this file
261 #            st_size ##size of file
262             files_in_snapshot.append({"path":current_snapshot, "inode": stat.st_ino, "size":stat.st_size, "num_of_hardlinks":stat.st_nlink, "mode":stat.st_mode})
263
264 #        elif isMount:
265 #            is_mount_in_snapshot.append(current_snapshot)
266         else:
267             unknown_in_snapshot.append(current_snapshot)
268             
269     for i in range(0, len(dir_in_current_dir)):
270         debug_message(("scanning dir", dir_in_current_dir[i]) , 2)
271         scan_dir(dir_in_current_dir[i], search_hidden_directories)
272         
273 #        #debug_message(("data 0", data[0][0]), 2)
274 #        if len(files)
275 #        files_in_snapshot.append(data[0][0])
276 #        dir_in_snapshot.append(data[1][0])
277 #        symlinks_in_snapshot.append(data[2][0])
278 #        unknown_in_snapshot.append(data[3][0])
279     return (files_in_snapshot, dir_in_snapshot, symlinks_in_snapshot, unknown_in_snapshot)
280 ##
281 ##def print_scanned_dir_list():
282 ##    global files_in_snapshot
283 ##    global symlinks_in_snapshot
284 ##    print( "scanning dir", 2)
285 ##
286 ##
287 ##    for i in range(0, len(files_in_snapshot)):
288 ##        if files_in_snapshot[i]["num_of_hardlinks"]>1:
289 ##            print "inode",files_in_snapshot[i]["inode"],"size",files_in_snapshot[i]["size"],"path:", files_in_snapshot[i]["path"], "    num of hard links",  files_in_snapshot[i]["num_of_hardlinks"] 
290 ##
291 ##        else :
292 ##            print "inode",files_in_snapshot[i]["inode"],"size",files_in_snapshot[i]["size"],"path:", files_in_snapshot[i]["path"]
293 ###        current_open_file=open(files_in_snapshot[i], "r")
294 ###        #current_open_file.f.read(3)
295 ###        lines_in_file=current_open_file.readlines()
296 ###        #use for loop to write code into yaffs file
297 ###        print "number of line of code:", len(lines_in_file)
298 ###    print current_open_file
299 ##    for i in range(0, len(symlinks_in_snapshot)):
300 ##        print "symlinks in snapshot:", symlinks_in_snapshot[i]
301 ##    for i in range(0, len(dir_in_snapshot)):
302 ##        print "directories in snapshot:", dir_in_snapshot[i]
303 ##    for i in range(0, len(unknown_in_snapshot)):
304 ##        print "unknown objects in snapshot:", unknown_in_snapshot[i]
305 ##
306
307
308 def copy_scanned_files_into_yaffs(files_in_snapshot, dir_in_snapshot,  symlinks_in_snapshot, unknown_in_snapshot,   path, yaffs_root_dir_path="/yaffs2/", yaffs_mount_point_path="/yaffs2/" ):
309 #files_in_snapshot, dir_in_snapshot, symlinks_in_snapshot, unknown_in_snapshot
310 #########################################copy directories into yaffs so the files can be created in these directories
311     debug_message("making directories in yaffs", 1)
312     if yaffs_root_dir_path!=yaffs_mount_point_path:
313         slash_id=[]
314         debug_message("making directories to the place in yaffs where the directories will copied to", 2)
315         root_branch_path=subtract_paths(yaffs_root_dir_path, yaffs_mount_point_path)
316         for i in range(0, len(root_branch_path)):
317
318             if root_branch_path[i]=="/" and i != 0:
319                slash_id.append(i)
320         debug_message(("slash_id", slash_id),4) 
321         for i in range(0, len(slash_id)):
322             create_dir({"path":root_branch_path[:slash_id[i]], "mode": yaffs_S_IREAD | yaffs_S_IWRITE}, "/", yaffs_mount_point_path) 
323     
324     for i in range(0, len(dir_in_snapshot)):
325         create_dir(dir_in_snapshot[i], path, yaffs_root_dir_path)
326   
327     
328     
329 #########################################copy file into yaffs
330     debug_message("copying scanned files into yaffs", 1)
331     list=[]
332     inode_blacklist=[]
333
334     debug_message("files to be copyied into yaffs", 2)
335     for a in range(0, len(files_in_snapshot)):
336         debug_message(files_in_snapshot[a], 2)
337     debug_message("\n\n\n", 2)
338     for i in range(0, len(files_in_snapshot)):
339         list=[]
340         if files_in_snapshot[i]["num_of_hardlinks"]>1 and files_in_snapshot[i]["inode"] not in inode_blacklist :
341             debug_message("found a hard link", 2)
342             debug_message(("inode",files_in_snapshot[i]["inode"],"size",files_in_snapshot[i]["size"],"path:", files_in_snapshot[i]["path"], "    num of hard links",  files_in_snapshot[i]["num_of_hardlinks"] ), 2)
343             for a in range(0, len(files_in_snapshot) ) :
344                 if files_in_snapshot[a]["inode"] ==files_in_snapshot[i]["inode"]  :
345                     ##and os.path.isfile(files_in_snapshot[i])
346                     debug_message(("found this file which matches inode",files_in_snapshot[a]), 2) 
347                     list.append(files_in_snapshot[a])
348                     debug_message(("length of list", len(list)), 2)
349                 if len(list)==files_in_snapshot[i]["num_of_hardlinks"]:
350                     break
351             for a in range(0, len(list)):
352                 debug_message(list[a], 2)
353             ##add inode to blacklist. all of the indoes in the list should be the same.
354             inode_blacklist.append(list[0]["inode"])
355             ##create a file from the first hardlink.
356             create_file(list[0])
357             target_path=yaffs_root_dir_path+list[0]["path"][len(path):]
358             for i in range(1, len(list)):
359                 debug_message("creating_symlink", 2)
360                 debug_message(("target path", target_path), 2)
361                 hardlink_path=yaffs_root_dir_path+list[i]["path"][len(path):]
362                 debug_message(("hardlink path", hardlink_path), 2)
363                 output=yaffs_link(target_path,hardlink_path)
364                 debug_message(("creating hardlink:", list[i]["path"], "output:", output), 1)
365         elif files_in_snapshot[i]["inode"] not in inode_blacklist :
366             create_file(files_in_snapshot[i])
367
368
369 ############################copy symlinks into yaffs
370
371     for i in range(0, len(symlinks_in_snapshot)):
372         debug_message(("symlinks in snapshot:", symlinks_in_snapshot[i]), 2)
373         target_path=join_paths(yaffs_root_dir_path, subtract_paths(symlinks_in_snapshot[i]["target"],  path))
374         new_path=join_paths(yaffs_root_dir_path, subtract_paths(symlinks_in_snapshot[i]["path"], path))
375         output=yaffs_symlink(target_path, new_path)
376         debug_message(("created symlink",new_path , " > ", target_path, "  output:", output), 1)
377         ##yaffs_symlink(const YCHAR *oldpath, const YCHAR *newpath);
378    
379     
380     for i in range(0, len(unknown_in_snapshot)):
381         debug_message( ("unknown object in snapshot:", unknown_in_snapshot[i]), 0)
382     
383     
384 def import_into_yaffs(file_path, yaffs_path="/yaffs2/", debug_level=1,  copy_hidden_dir=True ,new_yaffs_trace_val=-1 ):
385 #    global current_debug_level
386 #    global search_hidden_directories
387 #    global yaffs_root_dir_path
388 #    global path
389     
390 #    current_debug_level=debug_level
391 #    search_hidden_directories=copy_hidden_dir
392 #    yaffs_root_dir_path=yaffs_path
393 #    path=file_path
394     old_yaffs_trace_val=yaffs_get_trace()
395     if new_yaffs_trace_val!=-1:
396         yaffs_set_trace(new_yaffs_trace_val)
397     
398     data=scan_dir(file_path, copy_hidden_dir)
399     copy_scanned_files_into_yaffs(data[0], data[1], data[2], data[3],file_path,  yaffs_path)
400     
401     yaffs_set_trace(old_yaffs_trace_val)
402     
403     
404 if __name__=="__main__":
405     yaffs_start_up()
406     yaffs_mount("/yaffs2/")
407     #yaffs_set_trace(0)
408 #    absolute_path = os.path.abspath(os.path.curdir)
409     #print "absolute path:", absolute_path
410     current_debug_level=1
411     search_hidden_directories=True
412     yaffs_root_dir_path="/yaffs2/"
413     yaffs_trace=-1
414     #print sys.argv
415     path=sys.argv[1]
416     for i in range(2, len(sys.argv)):
417         if sys.argv[i]=="-d":
418             current_debug_level=int( sys.argv[i+1])
419         if sys.argv[i]=="-ignore_hidden_directories":
420             search_hidden_directories=False
421         if sys.argv[i]=="-o":
422             yaffs_root_dir_path=sys.argv[i+1]
423         if sys.argv[i]=="-yaffs_trace":
424             yaffs_trace=int(sys.argv[i+1])
425 #
426 #
427 #    path="/home/timothy/work/yaffs/git/yaffs2"
428 #    path="/home/timothy/my_stuff/old_laptop/timothy/programming_lejos/"
429
430
431     import_into_yaffs(path, yaffs_root_dir_path, current_debug_level,  search_hidden_directories, yaffs_trace )
432 #    scan_dir(path)
433 #    copy_scanned_files_into_yaffs()
434     #print_scanned_dir_list()
435
436     print"unmounting yaffs:", yaffs_unmount("/yaffs2/")