files.html
001| '''Directory and File Classes.
001|
001| Classes:
001| filefinder - File Finder
001| filefilter - File Filter
001|
001| fileobj - File Object - abstract file properties class
001| filecontent - File Object - abstract base class
001| datafile - File Object - binary data (bytes)
001| textfile - File Object - text data (chars)
001| linefile - File Object - text data (lines)
001|
001| jsonfile - File Object - JSON file
001| xmlfile - File Object - XML file (save only for now)
001|
001| srcfile - File Object - Generic source code file
001| inifile - File Object - INI-file
001|
001| tablefile - File Object - abstract class
001| tabfile - File Object - TAB-delimited data
001| csvfile - File Object - CSV-delimited data
001|
001| Functions:
001| dict2xml (doc_name, json_data)
001|
001| '''
002|
003| from os import listdir, path
004| from datetime import datetime
005| from time import localtime
006| from re import compile as RegEx, RegexFlag
007| from json import load as jsonload, dump as jsonsave
008| from html import escape
009| from logger import logger
010| from goodies import KWARG, typename, plural
011|
012|
013|
014|
015|
016| Log = logger('cjsFiles')
017|
018| TAB = '\t'
019| CR = '\r'
020| LF = '\n'
021| EOL = '\n'
022| SPC = ' '
023|
024| COMMA = ','
025|
026|
027| class filefinder:
028| '''File Finder class.'''
029|
030| def __init__ (self, folder, **kwargs):
031| '''New filefinder instance. Requires a folder name.'''
032| Log.trace(f'filefinder({folder})')
033| self.folder = folder
034| self.filenames = []
035| self.item_include = filefilter()
036| self.item_exclude = filefilter()
037| self.folder_include = filefilter()
038| self.folder_exclude = filefilter()
039| self.subdirs = int(kwargs['subs']) if 'subs' in kwargs else -1
040| self.filter_func = kwargs['ff'] if 'ff' in kwargs else None
041|
042| def scan (self, ff=None):
043| '''Scan for files. [DON'T FORGET TO DO THIS!!]'''
044| Log.trace(f'filefinder.scan()')
045| if ff:
046| self.filter_func = ff
047| self.filenames = []
048| self._scan(self.folder, 1)
049|
050| def _scan (self, folder, level):
051| '''Scan (recursive).'''
052|
053| names = listdir(folder)
054|
055|
056| ns = list(names)
057| if len(self.item_include):
058| ns = self.item_include.include_names(ns)
059| if len(self.item_exclude):
060| ns = self.item_exclude.exclude_names(ns)
061|
062| fns = [path.join(folder,n) for n in ns]
063| fs = [fn for fn in fns if path.isfile(fn)]
064|
065| self.filenames.extend(fs)
066|
067|
068| if 0 <= self.subdirs < level:
069| return
070|
071| fns = [path.join(folder,n) for n in names]
072| ds = [fn for fn in fns if path.isdir(fn)]
073|
074| if len(self.folder_include):
075| ds = self.folder_include.include_names(ds)
076| if len(self.folder_exclude):
077| ds = self.folder_exclude.exclude_names(ds)
078|
079| for d in sorted(ds):
080| self._scan(d, level+1)
081|
082| def add_include_item (self, item):
083| '''Item names in this list are (only) ones used for the list.'''
084| self.item_include.add_item(item)
085|
086| def add_exclude_item (self, item):
087| '''Item names in this list are excluded from the list.'''
088| self.item_exclude.add_item(item)
089|
090| def add_include_folder (self, folder):
091| '''Folder names in this list are (only) ones used for the list.'''
092| self.folder_include.add_item(folder)
093|
094| def add_exclude_folder (self, folder):
095| '''Folder names in this list are excluded from the list.'''
096| self.folder_exclude.add_item(folder)
097|
098| def namelist (self):
099| n = 1+len(self.folder)
100| return [fn[n:] for fn in self.filenames]
101|
102| def pathlist (self):
103| a = []
104| cd = None
105| for fn in self.filenames:
106| dn = path.dirname(fn)
107| if cd != dn:
108| a.append(dn)
109| cd = dn
110| return a
111|
112| def prune (self, function):
113| '''Apply {function} as a filter to the filename list.'''
114| self.filenames = [fn for fn in self.filenames if function(fn)]
115|
116| def process (self, function):
117| '''Apply {function} as a process to all filenames.'''
118| self.filenames = self.execute(function)
119|
120| def execute (self, function):
121| '''Return all filenames through {function} as process.'''
122| return [function(fn) for fn in self.filenames]
123|
124| def __str__ (self):
125| return self.folder
126|
127| def __bool__ (self):
128| return (0 < len(self.filenames))
129|
130| def __iter__ (self):
131| return iter(self.filenames)
132|
133| def __len__ (self):
134| return len(self.filenames)
135|
136| def __getitem__ (self, ix):
137| return self.filenames[ix]
138|
139|
140|
141| class filefilter:
142| '''File Filter class.'''
143|
144| def __init__ (self, items=[]):
145| self.items = []
146| self.add_items(items)
147|
148| def include_names (self, names):
149| return [n for n in names if self.test_name(n)]
150|
151| def exclude_names (self, names):
152| return [n for n in names if not self.test_name(n)]
153|
154| def test_name (self, name):
155| return 0 < len([ff for ff in self.items if ff.search(name)])
156|
157| def add_items (self, items):
158| for ix in items:
159| self.add_item(ix)
160|
161| def add_item (self, item):
162| self.items.append(RegEx(item, RegexFlag.IGNORECASE))
163|
164| def __str__ (self):
165| return '\n'.join(self.items)
166|
167| def __len__ (self):
168| return len(self.items)
169|
170| def __getitem__ (self, ix):
171| return self.items[ix]
172|
173| def __iter__ (self):
174| return iter(self.items)
175|
176|
177|
178| class fileobj:
179| '''File Object class.
179|
179| properties:
179| fullname - string : Full path/name of file.
179| pathname - string : File path (only).
179| filename - string : File name (only).
179| name - string : File name (only - no extension).
179| ext - string : File extension (duh; only).
179| fsize - int : File size
179| created - datetime : File created date
179| updated - datetime : File updated date
179| xflag - boolean : File exists flag
179| fflag - boolean : File is a file flag
179| dflag - boolean : File is a directory flag
179|
179| methods:
179| get_text - returns file contents (as a string of bytes)
179| get_lines - returns file contents (as a list of lines)
179|
179| '''
180| def __init__ (self, filespec, log=None):
181| '''New fileobj instance.'''
182| Log.trace(f'fileobj({filespec})')
183| if isinstance(filespec, fileobj):
184| self.fullname = filespec.fullname
185| self.pathname = filespec.pathname
186| self.filename = filespec.filename
187| self.name = filespec.name
188| self.ext = filespec.ext
189| self.fsize = filespec.fsize
190| self.created = filespec.created
191| self.updated = filespec.updated
192| self.dflag = filespec.dflag
193| self.fflag = filespec.fflag
194| self.xflag = filespec.xflag
195| return
196|
197| self.fullname = filespec
198|
199| t = path.split(self.fullname)
200| self.pathname = t[0]
201| self.filename = t[1]
202| t = path.splitext(self.filename)
203| self.name = t[0]
204| self.ext = t[1][1:]
205|
206| self.fsize = 0
207| self.created = None
208| self.updated = None
209|
210| self.dflag = False
211| self.fflag = False
212| self.xflag = path.exists(self.fullname)
213| if self.xflag:
214|
215| self.dflag = path.isdir(self.fullname)
216| self.fflag = path.isfile(self.fullname)
217|
218| if self.fflag:
219|
220| self.fsize = path.getsize(self.fullname)
221|
222| t = localtime(path.getctime(self.fullname))
223| self.created = datetime(t[0],t[1],t[2],t[3],t[4],t[5])
224|
225| t = localtime(path.getmtime(self.fullname))
226| self.updated = datetime(t[0],t[1],t[2],t[3],t[4],t[5])
227|
228| @property
229| def exists (self): return self.xflag
230|
231| @property
232| def isfile (self): return self.fflag
233|
234| @property
235| def isdir (self): return self.dflag
236|
237| @property
238| def ftype (self):
239| if self.fflag: return 'F'
240| if self.dflag: return 'D'
241| if self.xflag: return 'X'
242| return ''
243|
244| def __bool__ (self):
245| return True if self.xflag else False
246|
247| def __eq__ (self, other):
248| if self.fullname != other.fullname: return False
249| if self.fsize != other.fsize: return False
250| if self.created != other.created: return False
251| if self.updated != other.updated: return False
252| return True
253|
254| def __le__ (self, other):
255| if self.fullname > other.fullname: return False
256| if self.fsize > other.fsize: return False
257| if self.created > other.created: return False
258| if self.updated > other.updated: return False
259| return True
260|
261| def __ge__ (self, other):
262| if self.fullname < other.fullname: return False
263| if self.fsize < other.fsize: return False
264| if self.created < other.created: return False
265| if self.updated < other.updated: return False
266| return True
267|
268| def __ne__ (self, other): return not self.__eq__(other)
269| def __lt__ (self, other): return not self.__ge__(other)
270| def __gt__ (self, other): return not self.__le__(other)
271|
272| def __str__ (self):
273| s = plural(self.fsize)
274| return f'{self.filename} ({self.fsize} byte{s}) [{self.created}]'
275|
276| def __repr__ (self):
277| return f'<{typename(self)} {self.ftype} @{id(self):08x}>'
278|
279|
280| class filecontent (fileobj):
281| '''Abstract File Class.'''
282| def __init__ (self, filespec, log=None):
283| super().__init__(filespec, log=log)
284| Log.trace(f'filecontent({filespec})')
285| self.data = None
286|
287| def __bool__ (self):
288| return (0 < len(self.data))
289|
290| def __iter__ (self):
291| return iter(self.data)
292|
293| def __len__ (self):
294| return len(self.data)
295|
296| def __getitem__ (self, ix):
297| return self.data[ix]
298|
299| def __setitem__ (self, ix, new_value):
300| raise NotImplementedError('Not allowed to modify file datums.')
301|
302| def __delitem__ (self, ix):
303| raise NotImplementedError('Not allowed to delete file datums.')
304|
305| def __reversed__ (self):
306| return reversed(self.data)
307|
308| def __contains__ (self, item):
309| return (item in self.data)
310|
311|
312| class datafile (filecontent):
313| '''Basic Data File Class.'''
314| def __init__ (self, filespec, log=None):
315| super().__init__(filespec, log=log)
316| Log.trace(f'datafile({filespec})')
317| self.data = bytes()
318|
319| def load (self):
320| fp = open(self.fullname, mode='rb')
321| try:
322| self.data = fp.read()
323| except:
324| Log.error(f'error: {self.fullname}')
325| raise
326| else:
327| Log.info(f'read: {self.fullname}')
328| finally:
329| fp.close()
330|
331| def save (self):
332| fp = open(self.fullname, mode='wb')
333| try:
334| fp.write(self.data)
335| except:
336| Log.error(f'error: {self.fullname}')
337| raise
338| else:
339| Log.info(f'wrote: {self.fullname}')
340| finally:
341| fp.close()
342|
343|
344| class textfile (filecontent):
345| '''Basic Text File Class.'''
346| def __init__ (self, filespec, log=None):
347| super().__init__(filespec, log=log)
348| Log.trace(f'textfile({filespec})')
349| self.data = str()
350|
351| def add (self, ch):
352| self.data.append(ch)
353|
354| def load (self, encoding='utf-8'):
355| fp = open(self.fullname, mode='r', encoding=encoding)
356| try:
357| self.data = fp.read()
358| if self.data[0] == '\ufeff':
359| self.data = self.data[1:]
360|
361| except:
362| Log.error(f'error: {self.fullname}')
363| raise
364| else:
365| Log.info(f'read: {self.fullname}')
366| finally:
367| fp.close()
368|
369| def save (self, encoding='utf-8'):
370| fp = open(self.fullname, mode='w', encoding=encoding)
371| try:
372| fp.write(self.data)
373| except:
374| Log.error(f'error: {self.fullname}')
375| raise
376| else:
377| Log.info(f'wrote: {self.fullname}')
378| finally:
379| fp.close()
380|
381|
382| class linefile (filecontent):
383| '''Lines of Text File Class.'''
384| def __init__ (self, filespec, log=None):
385| super().__init__(filespec, log=log)
386| Log.trace(f'linefile({filespec})')
387| self.data = []
388|
389| def __call__ (self):
390| return EOL.join(self.data)
391|
392| def add (self, txt=''):
393| self.data.append(txt)
394|
395| def load (self, encoding='utf-8'):
396| fp = open(self.fullname, mode='r', encoding=encoding)
397| try:
398| self.data = [s.rstrip() for s in fp]
399| if 0 < len(self.data):
400| if 0 < len(self.data[0]):
401| if self.data[0][0] == '\ufeff':
402| self.data[0] = self.data[0][1:]
403| except:
404| raise
405| else:
406| Log.info(f'read: {self.fullname}')
407| finally:
408| fp.close()
409|
410| def save (self, encoding='utf-8'):
411| fp = open(self.fullname, mode='w', encoding=encoding)
412| try:
413| for s in self.data:
414| fp.write(s)
415| fp.write(EOL)
416| except:
417| raise
418| else:
419| Log.info(f'wrote: {self.fullname}')
420| finally:
421| fp.close()
422|
423|
424|
425| class jsonfile (filecontent):
426| '''JSON File Class.'''
427| def __init__ (self, filespec, log=None):
428| super().__init__(filespec, log=log)
429| Log.trace(f'jsonfile({filespec})')
430| self.data = {}
431|
432| def __bool__ (self):
433| return (0 < len(self.data))
434|
435| def load (self):
436| fp = open(self.fullname, mode='rb')
437| try:
438| self.data = jsonload(fp)
439| except:
440| raise
441| else:
442| Log.info(f'read: {self.fullname}')
443| finally:
444| fp.close()
445|
446| def save (self):
447| fp = open(self.fullname, mode='w')
448| try:
449| jsonsave(self.data, fp, indent=3)
450| except:
451| raise
452| else:
453| Log.info(f'wrote: {self.fullname}')
454| finally:
455| fp.close()
456|
457|
458|
459| class tablefile (filecontent):
460| '''Abstract Intermediate Class. Don't use!'''
461| def __init__ (self, filespec, maxrows=-1, headers=True, log=None):
462| super().__init__(filespec, log=log)
463| Log.trace(f'tablefile({filespec})')
464| self.maxrows = maxrows
465| self.headers = headers
466| self.delim = '|'
467| self.hdrs = []
468| self.data = []
469|
470| def add (self, row=[]):
471| self.data.append(row)
472|
473| def delete_blank_lines (self):
474| self.data = [t for t in self.data if 0 < len(t)]
475|
476| def save (self, encoding='utf-8'):
477| fp = open(self.fullname, mode='w', encoding=encoding)
478| try:
479|
480| if self.headers:
481| t = [str(h) for h in self.hdrs]
482| fp.write(self.delim.join(t))
483| fp.write(EOL)
484|
485| for rx,row in enumerate(self.data):
486| if 0 <= self.maxrows <= rx:
487| break
488| t = [str(col) for col in row]
489| fp.write(self.delim.join(t))
490| fp.write(EOL)
491| except:
492| raise
493| else:
494| Log.info(f'wrote: {self.fullname}')
495| finally:
496| fp.close()
497|
498|
499| class tabfile (tablefile):
500| '''TAB-delimited Table File Class.'''
501| def __init__ (self, filespec, maxrows=-1, headers=True, log=None):
502| super().__init__(filespec, maxrows=maxrows, headers=headers, log=log)
503| Log.trace(f'tabfile({filespec})')
504| self.delim = TAB
505|
506| def load (self, encoding='utf-8'):
507| self.hdrs = []
508| self.data = []
509| fp = open(self.fullname, mode='r', encoding=encoding)
510| try:
511| rx = -1
512| for s in fp:
513| rx += 1
514| if 0 <= self.maxrows < rx:
515| break
516| if (not self.hdrs) and (s[0] == '\ufeff'):
517| s = s[1:]
518| fields = s.rstrip().split(TAB)
519| if self.headers and (len(self.hdrs) == 0):
520| self.hdrs = fields
521| else:
522| self.data.append(fields)
523| except:
524| raise
525| else:
526| Log.info(f'read: {self.fullname}')
527| finally:
528| fp.close()
529|
530|
531| class csvfile (tablefile):
532| '''Comma-delimited Table File Class.'''
533| def __init__ (self, filespec, maxrows=-1, headers=True, log=None):
534| super().__init__(filespec, maxrows=maxrows, headers=headers, log=log)
535| Log.trace(f'tabfile({filespec})')
536| self.delim = COMMA
537|
538| def load (self, encoding='utf-8'):
539| self.hdrs = []
540| self.data = []
541| fp = open(self.fullname, mode='r', encoding=encoding)
542| try:
543| rx = -1
544| for s in fp:
545| rx += 1
546| if 0 <= self.maxrows < rx:
547| break
548| if (not self.hdrs) and (s[0] == '\ufeff'):
549| s = s[1:]
550| fields = self._parse_fields(s)
551| if self.headers and (len(self.hdrs) == 0):
552| self.hdrs = fields
553| else:
554| self.data.append(fields)
555| except:
556| raise
557| else:
558| Log.info(f'read: {self.fullname}')
559| finally:
560| fp.close()
561|
562| def save (self, encoding='utf-8'):
563|
564| if self.headers:
565| for ix in range(len(self.hdrs)):
566| hdr = self.hdrs[ix]
567| if isinstance(hdr,str) and ('"' in hdr):
568| s = hdr.replace('"', '""')
569| self.hdrs[ix] = f'"{s}"'
570| Log.trace(hdr)
571| for row in self.data:
572| for ix in range(len(row)):
573| cell = row[ix]
574| if isinstance(cell,str) and ('"' in cell):
575| s = cell.replace('"', '""')
576| row[ix] = f'"{s}"'
577| Log.trace(cell)
578|
579| super().save(encoding=encoding)
580|
581| def _parse_fields (self, s):
582|
583| s = s.strip()
584| flds = []
585| while len(s):
586| if s[0] == ',':
587| flds.append('')
588| s = s[1:].lstrip()
589| continue
590|
591| if s[0] == '"':
592| s = s[1:]
593| ix = s.find('",')
594| if ix < 0:
595| ix = s.rindex('"')
596| flds.append(s[0:ix].rstrip().replace('""','"'))
597| s = s[ix+1:].lstrip()
598| if len(s) and (s[0] == ','):
599| s = s[1:].lstrip()
600| continue
601|
602| ix = s.find(',')
603| if ix < 0: ix = len(s)
604| flds.append(s[0:ix].rstrip())
605| s = s[ix+1:].lstrip()
606| return flds
607|
608|
609|
610| class xmlfile (tablefile):
611| '''XML Table File Class.'''
612| def __init__ (self, filespec, maxrows=-1, headers=True, attrs=False, log=None):
613| super().__init__(filespec, maxrows=maxrows, headers=headers, log=log)
614| Log.trace(f'xmlfile({filespec})')
615| self.indent = ' '
616| self.attrs = attrs
617|
618| def load (self, encoding='utf-8'):
619| self.hdrs = []
620| self.data = []
621|
622| def save (self, encoding='utf-8'):
623| '''Save table as XML file.'''
624| fp = open(self.fullname, mode='w', encoding=encoding)
625| try:
626| print('<?xml version="1.0" encoding="UTF-8"?>', file=fp)
627| print('<table id="tab1">', file=fp)
628| for rx,row in enumerate(self.data):
629| print(f'{self.indent}<row id="row{rx}">', file=fp)
630| for cx,col in enumerate(row):
631| if self.attrs:
632| print(f'{self.indent*2}<data id="col{rx}{cx}" name="{self.hdrs[cx]}">{col}</data>', file=fp)
633| else:
634| nm = self.hdrs[cx] if self.headers else 'data'
635| print(f'{self.indent*2}<{nm} id="col{rx}{cx}">{col}</{nm}>', file=fp)
636| print(' </row>', file=fp)
637| print('</table>', file=fp)
638| print(file=fp)
639| except:
640| raise
641| else:
642| Log.info(f'wrote: {self.fullname}')
643| finally:
644| fp.close()
645|
646|
647| def dict2xml (doc_name, json_data):
648| '''Convert a dict object to XML.'''
649| outbuf = []
650|
651| outbuf.append(f'<{doc_name}>')
652|
653|
654| for k in json_data:
655|
656| _dict2xml(outbuf, k, json_data[k])
657|
658|
659| outbuf.append(f'</{doc_name}>')
660| return outbuf
661|
662|
663| def _dict2xml (outbuf, name, json_data):
664| '''Convert dict to XML recursive sub-function.'''
665|
666| if json_data is None:
667| outbuf.append(f'<{name} type="object">None</{name}>')
668| return
669|
670|
671| if isinstance(json_data, str):
672| outbuf.append(f'<{name} type="str">{escape(json_data)}</{name}>')
673| return
674|
675|
676| if isinstance(json_data, int):
677| outbuf.append(f'<{name} type="int">{json_data}</{name}>')
678| return
679|
680| if isinstance(json_data, float):
681| outbuf.append(f'<{name} type="float">{json_data}</{name}>')
682| return
683|
684|
685| if isinstance(json_data, datetime):
686| outbuf.append(f'<{name} type="date">{json_data:%Y-%d-%m %H:%M:%S}</{name}>')
687| return
688|
689|
690| if isinstance(json_data, list):
691| outbuf.append(f'<{name} type="list">')
692| for item in json_data:
693|
694| _dict2xml(outbuf, 'listitem', item)
695| outbuf.append(f'</{name}>')
696| return
697|
698|
699| if isinstance(json_data, dict):
700| outbuf.append(f'<{name} type="group">')
701| for k in json_data:
702|
703| _dict2xml(outbuf, k, json_data[k])
704| outbuf.append(f'</{name}>')
705| return
706|
707|
708| raise RuntimeError(f'Unknown data: "{json_data}"')
709|
710|
711|
712| class srcfile (linefile):
713| '''Base class for a source code file. Auto-skips blank lines and comments.'''
714| def __init__ (self, filespec, rems=None, log=None):
715| super().__init__(filespec, log=log)
716| Log.trace(f'sourcefile({filespec})')
717| self.rems = rems if rems else [';', '#', '//', '--']
718| self.src = []
719|
720| def __bool__ (self):
721| return (0 < len(self.src))
722|
723| def __iter__ (self):
724| return iter(self.src)
725|
726| def __len__ (self):
727| return len(self.src)
728|
729| def __getitem__ (self, ix):
730| return self.src[ix]
731|
732| def load (self):
733| super().load()
734| for line in self.data:
735| for rem in self.rems:
736| if rem not in line:
737|
738| continue
739|
740|
741| qt_flag = ''
742| for cx in range(len(line)):
743| ch = line[cx]
744|
745| if qt_flag:
746|
747| if ch == qt_flag:
748| qt_flag = False
749| continue
750|
751| if ch in ['"', "'"]:
752| qt_flag = ch
753| continue
754|
755| if line[cx:cx+len(rem)] == rem:
756|
757| line = line[0:cx].rstrip()
758| break
759|
760|
761|
762|
763|
764|
765| if len(line) == 0:
766| continue
767|
768| self.src.append(line)
769|
770| return len(self)
771|
772| def save (self):
773| raise NotImplementedError()
774|
775|
776|
777| class inifile (linefile):
778| '''INI-file File Class (based on linefile).'''
779| def __init__ (self, filespec, log=None):
780| super().__init__(filespec, log=log)
781| Log.trace(f'inifile({filespec})')
782| self.config = {'':{}}
783| self.section_name = ''
784|
785| def load (self):
786| super().load()
787| self.section_name = ''
788| for ix,txt in enumerate(self.data):
789| txt = txt.strip()
790|
791| if len(txt) == 0:
792| continue
793|
794| if txt.startswith('#') or txt.startswith(';'):
795| continue
796|
797| if txt.startswith('['):
798| end = txt.index(']')
799| self.section_name = txt[1:end].strip()
800| if self.section_name not in self.config:
801| self.config[self.section_name] = {}
802| continue
803|
804|
805|
806|
807| if txt.startswith('"'):
808| end = txt.find('"', 1)
809| nam = txt[1:end]
810| self.config[self.section_name][nam] = ''
811| continue
812|
813| if 0 <= txt.find('='):
814| n,_,v = txt.partition('=')
815| elif 0 <= txt.find(':'):
816| n,_,v = txt.partition(':')
817| else:
818| n,v = txt,''
819|
820| nam = n.strip()
821| val = v.strip()
822| vtype = str
823|
824| ix = nam.find(':')
825| if 0 <= ix:
826| vtype = eval(nam[ix+1:])
827| nam = nam[0:ix]
828|
829| if nam not in self.config[self.section_name]:
830| self.config[self.section_name][nam] = vtype(val)
831| continue
832|
833| curr = self.config[self.section_name][nam]
834|
835| if isinstance(curr,list):
836|
837| curr.append(vtype(val))
838| continue
839|
840| self.config[self.section_name][nam] = [curr, vtype(val)]
841|
842| def save (self):
843|
844| raise NotImplementedError()
845|
846|
847|
848| def directory_sizes (basepath, results):
849| '''Directory Sizes (recursive).'''
850| return _directory_sizes(basepath, results)
851|
852|
853| def _directory_sizes (pathname, results):
854| '''Directory Sizes; Recursive Function.'''
855| dt = [pathname, 0, 0, 0, 0]
856| results.append(dt)
857|
858| ds = []
859| for n in listdir(pathname):
860| fn = path.join(pathname, n)
861| if path.isfile(fn):
862| dt[3] += path.getsize(fn)
863| dt[4] += 1
864| continue
865| if path.isdir(fn):
866| ds.append(fn)
867| continue
868|
869| dt[1] += dt[3]
870| dt[2] += dt[4]
871| for dn in sorted(ds):
872|
873| t = _directory_sizes(dn, results)
874|
875| dt[1] += t[1]
876| dt[2] += t[2]
877|
878|
879| return dt
880|
881|
882|
883| def xml_listing (basepath):
884| '''XML File List.'''
885| xml = ['<?xml version="1.0" encoding="UTF-8"?>']
886| xml.append(f'<filelist basepath="{basepath}">')
887| _xml_listing(basepath, xml)
888| xml.append('</filelist>')
889|
890|
891| return EOL.join(xml)
892|
893|
894| def _xml_listing (pathname, xml):
895| '''XML File List; Recursive Function.'''
896| fs = []
897| ds = []
898|
899| ns = listdir(pathname)
900| for n in ns:
901| fn = path.join(pathname, n)
902| if path.isfile(fn):
903| fs.append(fn)
904| continue
905| if path.isdir(fn):
906| ds.append(fn)
907| continue
908|
909| xml.append(f'<directory name="{pathname}">')
910|
911| for dn in sorted(ds):
912|
913| _xml_listing(dn, xml)
914|
915| for fn in sorted(fs):
916| tm = localtime(path.getctime(fn))
917| tc = datetime(tm[0],tm[1],tm[2],tm[3],tm[4],tm[5])
918| tm = localtime(path.getmtime(fn))
919| tu = datetime(tm[0],tm[1],tm[2],tm[3],tm[4],tm[5])
920| s = f'<file name="{fn}" size="{path.getsize(fn)}" cdate="{tc}" mdate="{tu}" />'
921| xml.append(s)
922|
923| xml.append('</directory>')
924|
925|
926|
927|
928|
929|
930|
931|
932|
933|
934|
935|
936|
937|
938|
939|
940|
941|
942|
943|
944|
945|
946|
947|
948|
949|
950|
951|
952|
953|
954|
955|
956|
957|
958|
959|
960|
961|
962|
963|
964|
965|
966|
967|
968|
969|
970|
971|
972|
973|
974|
975|
976|
977|
978|
979|
980|
981| '''eof'''
982|