major refactoring

This commit is contained in:
artus
2018-11-18 21:47:04 +01:00
parent 77fd72cb22
commit 3b94a602ed
9 changed files with 137 additions and 202 deletions

92
photograb/store.py Normal file
View File

@@ -0,0 +1,92 @@
# -*- coding:utf-8 -*-
from pathlib import Path
import shutil
import os
import time
class Content(dict):
def difference(self, other):
"""
Returns a new view containing only items from
this instance that are not present in the other
"""
my_keys = set(self.keys())
your_keys = set(other.keys())
new_keys = my_keys.difference(your_keys)
def in_new_keys(item):
return item[0] in new_keys
return Content(filter(in_new_keys, self.items()))
def filter_by_ext(self, ext):
""" Returns a new view containing only items with file extension """
ext = ext.lower()
def has_extension(item):
return item[1].suffix[1:].lower() == ext
return Content(filter(has_extension, self.items()))
class Store:
def __init__(self, path):
if not isinstance(path, Path):
path = Path(path)
if not path.exists():
path.mkdir()
elif not path.is_dir():
raise ValueError(f"{path} is not a folder !")
self.path = path
def read_content(self, exclude=None):
content = Content()
for path, _, filenames in os.walk(self.path):
# Ignore excluded folders
if exclude and Path(path).absolute().name == exclude:
continue
for name in filenames:
content[name] = path + "/" + name
return content
def copy_content(self, content):
print(f"Copy files to {self.path} : ", end="")
count = len(content)
start_time = time.process_time()
for name, path in content.items():
shutil.copy2(str(path), self.path)
elapsed = time.process_time() - start_time
print(f"{count} in {elapsed:.2f}s.")
def move_content(self, content):
print(f"Move files to {self.path} : ", end="")
count = len(content)
start_time = time.process_time()
for name, path in content.items():
shutil.move(str(path), self.path)
elapsed = time.process_time() - start_time
print(f"{count} in {elapsed:.2f}s.")
def remove_content(self, content):
print("Removing files from {self.path} : ", end="")
count = len(content)
start_time = time.process_time()
for name, path in content.items():
shutil.rm(path)
elapsed = time.process_time() - start_time
print(f"{count} in {elapsed:.2f}s.")
class Backup(Store):
def __init__(self, path):
super().__init__(path)
self.trash = Store(self.path / self.TRASH_NAME)
def trash_content(self, content):
self.trash.move_content(content)
def clean_trash(self):
raise NotImplementedError