Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# -*- coding: utf-8 -*-
2"""
3@file
4@brief keep the status of a folder, assuming this folder is not moved
5"""
6import os
7import datetime
8from ..loghelper.flog import noLOG
9from .file_info import convert_st_date_to_datetime, checksum_md5, FileInfo
12class FilesStatus:
13 """
14 This class maintains a list of files
15 and does some verifications in order to check if a file
16 was modified or not (if yes, then it will be updated to the website).
17 """
19 def __init__(self, file, fLOG=noLOG):
20 """
21 file which will contains the status
22 @param file file, if None, fill _children
23 @param fLOG logging function
24 """
25 self._file = file
26 self.copyFiles = {}
27 self.fileKeep = file
28 self.LOG = fLOG
30 if os.path.exists(self.fileKeep):
31 with open(self.fileKeep, "r", encoding="utf8") as f:
32 for ni, _ in enumerate(f.readlines()):
33 if ni == 0 and _.startswith("\ufeff"):
34 _ = _[len("\ufeff"):] # pragma: no cover
35 spl = _.strip("\r\n ").split("\t")
36 try:
37 if len(spl) >= 2:
38 a, b = spl[:2]
39 obj = FileInfo(a, int(b), None, None, None)
40 if len(spl) > 2 and len(spl[2]) > 0:
41 obj.set_date(
42 convert_st_date_to_datetime(spl[2]))
43 if len(spl) > 3 and len(spl[3]) > 0:
44 obj.set_mdate(
45 convert_st_date_to_datetime(spl[3]))
46 if len(spl) > 4 and len(spl[4]) > 0:
47 obj.set_md5(spl[4])
48 self.copyFiles[a] = obj
49 else:
50 raise ValueError( # pragma: no cover
51 "expecting a filename and a date on this line: " + _)
52 except Exception as e:
53 raise Exception( # pragma: no cover
54 "issue with line:\n {0} -- {1}".format(_, spl)) from e
56 # contains all file to update
57 self.modifiedFile = {}
59 def __iter__(self):
60 """
61 Iterates on all files stored in the current file,
62 yield a couple *(filename, FileInfo)*.
63 """
64 for a, b in self.copyFiles.items():
65 yield a, b
67 def iter_modified(self):
68 """
69 Iterates on all modified files yield a
70 couple *(filename, reason)*.
71 """
72 for a, b in self.modifiedFile:
73 yield a, b
75 def save_dates(self, checkfile=None):
76 """
77 Saves the status of the copy.
79 @param checkfile check the status for file checkfile
80 """
81 typstr = str
82 if checkfile is None:
83 checkfile = []
84 rows = []
85 for k in sorted(self.copyFiles):
86 obj = self.copyFiles[k]
87 da = "" if obj.date is None else str(obj.date)
88 mda = "" if obj.mdate is None else str(obj.mdate)
89 sum5 = "" if obj.checksum is None else str(obj.checksum)
91 if k in checkfile and len(da) == 0:
92 raise ValueError( # pragma: no cover
93 "There should be a date for file " + k + "\n" + str(obj))
94 if k in checkfile and len(mda) == 0:
95 raise ValueError( # pragma: no cover
96 "There should be a mdate for file " + k + "\n" + str(obj))
97 if k in checkfile and len(sum5) <= 10:
98 raise ValueError( # pragma: no cover
99 "There should be a checksum( for file " + k + "\n" + str(obj))
101 values = [k, typstr(obj.size), da, mda, sum5]
102 sval = "%s\n" % "\t".join(values)
103 if "\tNone" in sval:
104 raise AssertionError( # pragma: no cover
105 "This case should happen " + sval + "\n" + str(obj))
107 rows.append(sval)
109 with open(self.fileKeep, "w", encoding="utf8") as f:
110 for r in rows:
111 f.write(r)
113 def has_been_modified_and_reason(self, file):
114 """
115 Returns *(True, reason)* if a file was modified or *(False, None)* if not.
116 @param file filename
117 @return *(True, reason)* or *(False, None)*
118 """
119 res = True
120 reason = None
121 typstr = str
123 if file not in self.copyFiles:
124 reason = "new"
125 res = True
126 else:
127 obj = self.copyFiles[file]
128 st = os.stat(file)
129 if st.st_size != obj.size:
130 reason = "size %s != old size %s" % (
131 str(st.st_size), typstr(obj.size))
132 res = True
133 else:
134 ld = obj.mdate
135 _m = st.st_mtime
136 d = convert_st_date_to_datetime(_m)
137 if d != ld:
138 # dates are different but files might be the same
139 if obj.checksum is not None:
140 ch = checksum_md5(file)
141 if ch != obj.checksum:
142 reason = "date/md5 %s != old date %s md5 %s != %s" % (
143 typstr(ld), typstr(d), obj.checksum, ch)
144 res = True
145 else:
146 res = False
147 else:
148 # it cannot know, it does nothing
149 res = False
150 else:
151 # mda.... no expected modification (dates did not change)
152 res = False
154 return res, reason
156 def add_modified_file(self, file, reason):
157 """
158 Adds a file the modified list of files.
160 @param file file to add
161 @param reason reason for modification
162 """
163 if file in self.modifiedFile:
164 raise KeyError("file {0} is already present".format(file))
165 self.modifiedFile[file] = reason
167 def add_if_modified(self, file):
168 """
169 Adds a file to self.modifiedList if it was modified.
170 @param file filename
171 @return True or False
172 """
173 res, reason = self.has_been_modified_and_reason(file)
174 if res:
175 self.add_modified_file(res, reason)
176 return res
178 def difference(self, files, u4=False, nlog=None):
179 """
180 Goes through the list of files and tells which one has changed.
182 @param files @see cl FileTreeNode
183 @param u4 @see cl FileTreeNode (changes the output)
184 @param nlog if not None, print something every ``nlog`` processed files
185 @return iterator on files which changed
186 """
187 memo = {}
188 if u4:
189 nb = 0
190 for file in files:
191 memo[file.fullname] = True
192 if file._file is None:
193 continue
194 nb += 1
195 if nlog is not None and nb % nlog == 0:
196 self.LOG( # pragma: no cover
197 "[FileTreeStatus], processed", nb, "files")
199 full = file.fullname
200 r, reason = self.has_been_modified_and_reason(full)
201 if r:
202 if reason == "new":
203 r = (">+", file._file, file, None)
204 yield r
205 else:
206 r = (">", file._file, file, None)
207 yield r
208 else:
209 r = ("==", file._file, file, None)
210 yield r
211 else:
212 nb = 0
213 for file in files:
214 memo[file.fullpath] = True
215 nb += 1
216 if nlog is not None and nb % nlog == 0:
217 self.LOG("[FileTreeStatus], processed", nb, "files")
218 full = file.fullname
219 if self.has_been_modified_and_reason(full):
220 yield file
222 for file in self.copyFiles.values():
223 if file.filename not in memo:
224 yield ("<+", file.filename, None, None)
226 def update_copied_file(self, file, delete=False):
227 """
228 Updates the file in copyFiles (before saving), update all fields.
229 @param file filename
230 @param delete to remove this file
231 @return file object
232 """
233 if delete:
234 if file not in self.copyFiles:
235 raise FileNotFoundError( # pragma: no cover
236 "Unable to find a file in the list of monitored files: '{0}'.".format(file))
237 del self.copyFiles[file]
238 return None
239 st = os.stat(file)
240 size = st.st_size
241 mdate = convert_st_date_to_datetime(st.st_mtime)
242 date = datetime.datetime.now()
243 md = checksum_md5(file)
244 obj = FileInfo(file, size, date, mdate, md)
245 self.copyFiles[file] = obj
246 return obj