60 lines
1.7 KiB
Python
60 lines
1.7 KiB
Python
import json
|
|
import os
|
|
|
|
from loguru import logger
|
|
|
|
|
|
class DuCache():
|
|
def __init__(self, json_file_name, archives_path):
|
|
self.json_file_name = json_file_name
|
|
self.archives_path = archives_path
|
|
self.cache = None
|
|
self.read_json_file()
|
|
|
|
def write_json_file(self):
|
|
if self.cache is None:
|
|
count = 0
|
|
else:
|
|
count = len(self.cache)
|
|
|
|
with open(self.json_file_name, 'w') as f:
|
|
f.write(json.dumps(self.cache, indent=2))
|
|
logger.info(
|
|
f"wrote du cache to '{self.json_file_name}' ({count} items)")
|
|
|
|
def read_json_file(self):
|
|
try:
|
|
with open(self.json_file_name, 'r') as f:
|
|
self.cache = json.loads(f.read())
|
|
except FileNotFoundError:
|
|
logger.info(
|
|
f"no such file '{self.json_file_name}', using empty dict")
|
|
# create empty json file
|
|
self.cache = dict()
|
|
self.write_json_file()
|
|
|
|
def _du(self, path) -> int:
|
|
total = 0
|
|
for entry in os.scandir(path):
|
|
if entry.is_file(follow_symlinks=False):
|
|
total += entry.stat().st_size
|
|
elif entry.is_dir(follow_symlinks=False):
|
|
dirsize = self._du(entry.path)
|
|
self.cache[entry.path] = dirsize
|
|
total += dirsize
|
|
return total
|
|
|
|
def update(self):
|
|
total = self._du(self.archives_path)
|
|
self.write_json_file()
|
|
return total
|
|
|
|
def get_size(self, rel_path):
|
|
self.read_json_file()
|
|
full_path = os.path.join(self.archives_path, rel_path)
|
|
try:
|
|
size = self.cache[full_path]
|
|
return size
|
|
except KeyError:
|
|
return None
|