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

93 lines
2.3 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
3 months ago
import string
7 years ago
# local imports
2 years ago
from catcli.exceptions import CatcliException
7 years ago
1 year ago
WILD = '*'
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
def epoch_to_str(epoch: float) -> str:
2 years ago
"""convert epoch to string"""
if not epoch:
return ''
fmt = '%Y-%m-%d %H:%M:%S'
timestamp = datetime.datetime.fromtimestamp(epoch)
2 years ago
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'
3 months ago
def edit(data: str) -> str:
2 years ago
"""edit the information with the default EDITOR"""
3 months ago
content = fix_badchars(data)
2 years ago
editor = os.environ.get('EDITOR', 'vim')
with tempfile.NamedTemporaryFile(prefix='catcli', suffix='.tmp') as file:
3 months ago
file.write(content.encode('utf-8'))
2 years ago
file.flush()
3 months ago
subprocess.call([editor, file.get_name()])
2 years ago
file.seek(0)
new = file.read()
return new.decode('utf-8')
2 years ago
3 months ago
def fix_badchars(data: str) -> str:
2 years ago
"""fix none utf-8 chars in string"""
3 months ago
data = "".join(x for x in data if x in string.printable)
return data.encode("utf-8", "ignore").decode("utf-8")