You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
catcli/catcli/utils.py

91 lines
2.2 KiB
Python

7 years ago
"""
author: deadc0de6 (https://github.com/deadc0de6)
Copyright (c) 2017, deadc0de6
helpers
"""
import os
import hashlib
import tempfile
import subprocess
import datetime
7 years ago
# local imports
2 years ago
from catcli.exceptions import CatcliException
7 years ago
SEPARATOR = '/'
1 year ago
def md5sum(path: str) -> str:
2 years ago
"""
calculate md5 sum of a file
may raise exception
"""
2 years ago
rpath = os.path.realpath(path)
if not os.path.exists(rpath):
2 years ago
raise CatcliException(f'md5sum - file does not exist: {rpath}')
7 years ago
try:
2 years ago
with open(rpath, mode='rb') as file:
hashv = hashlib.md5()
7 years ago
while True:
2 years ago
buf = file.read(4096)
7 years ago
if not buf:
break
2 years ago
hashv.update(buf)
return hashv.hexdigest()
7 years ago
except PermissionError:
pass
2 years ago
except OSError as exc:
2 years ago
raise CatcliException(f'md5sum error: {exc}') from exc
1 year ago
return ''
7 years ago
1 year ago
def size_to_str(size: float,
raw: bool = True) -> str:
2 years ago
"""convert size to string, optionally human readable"""
7 years ago
div = 1024.
suf = ['B', 'K', 'M', 'G', 'T', 'P']
if raw or size < div:
return f'{size}'
7 years ago
for i in suf:
if size < div:
return f'{size:.1f}{i}'
7 years ago
size = size / div
sufix = suf[-1]
return f'{size:.1f}{sufix}'
7 years ago
1 year ago
def epoch_to_str(epoch: int) -> str:
2 years ago
"""convert epoch to string"""
if not epoch:
return ''
fmt = '%Y-%m-%d %H:%M:%S'
2 years ago
timestamp = datetime.datetime.fromtimestamp(float(epoch))
return timestamp.strftime(fmt)
1 year ago
def ask(question: str) -> bool:
2 years ago
"""ask the user what to do"""
resp = input(f'{question} [y|N] ? ')
7 years ago
return resp.lower() == 'y'
1 year ago
def edit(string: str) -> str:
2 years ago
"""edit the information with the default EDITOR"""
1 year ago
data = string.encode('utf-8')
2 years ago
editor = os.environ.get('EDITOR', 'vim')
with tempfile.NamedTemporaryFile(prefix='catcli', suffix='.tmp') as file:
1 year ago
file.write(data)
2 years ago
file.flush()
subprocess.call([editor, file.name])
file.seek(0)
new = file.read()
return new.decode('utf-8')
2 years ago
1 year ago
def fix_badchars(string: str) -> str:
2 years ago
"""fix none utf-8 chars in string"""
return string.encode('utf-8', 'ignore').decode('utf-8')