pferd/PFERD/utils.py

65 lines
1.8 KiB
Python
Raw Normal View History

import os
import sys
2018-11-26 14:39:06 +01:00
import pathlib
from colorama import Style
from colorama import Fore
__all__ = [
2019-04-24 14:34:20 +02:00
"get_base_dir",
"move",
"rename",
"stream_to_path",
"ContentTypeException",
2019-04-24 14:34:20 +02:00
"FileNotFoundException",
"PrettyLogger",
]
def get_base_dir(script_file):
2019-04-24 14:34:20 +02:00
return pathlib.Path(os.path.dirname(os.path.abspath(script_file)))
def move(path, from_folders, to_folders):
2019-04-24 14:34:20 +02:00
l = len(from_folders)
if path.parts[:l] == from_folders:
return pathlib.PurePath(*to_folders, *path.parts[l:])
def rename(path, to_name):
2019-04-24 14:34:20 +02:00
return pathlib.PurePath(*path.parts[:-1], to_name)
def stream_to_path(response, to_path, chunk_size=1024**2):
2019-04-24 14:34:20 +02:00
with open(to_path, 'wb') as fd:
for chunk in response.iter_content(chunk_size=chunk_size):
2019-04-24 14:34:20 +02:00
fd.write(chunk)
def isOutputPipe():
"""Returns whether this program's output is attached to a pipe.
"""
return sys.stdout.isatty
class ContentTypeException(Exception):
2019-04-24 14:34:20 +02:00
pass
class FileNotFoundException(Exception):
2019-04-24 14:34:20 +02:00
pass
class PrettyLogger:
def __init__(self, logger):
self.logger = logger
def modified_file(self, file_name):
self.logger.info(f"{Fore.MAGENTA}{Style.BRIGHT}Modified {file_name}.{Style.RESET_ALL}")
def new_file(self, file_name):
self.logger.info(f"{Fore.GREEN}{Style.BRIGHT}Created {file_name}.{Style.RESET_ALL}")
def ignored_file(self, file_name):
self.logger.info(f"{Style.DIM}Ignored {file_name}.{Style.RESET_ALL}")
def starting_synchronizer(self, target_directory, synchronizer_name, subject=None):
subject_str = f"{subject} " if subject else ""
self.logger.info("")
self.logger.info((
f"{Fore.CYAN}{Style.BRIGHT}Synchronizing {subject_str}to {target_directory}"
f" using the {synchronizer_name} synchronizer.{Style.RESET_ALL}"
))