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

120 lines
3.0 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
1 year ago
from catcli import nodes
2 years ago
from catcli.exceptions import CatcliException
7 years ago
1 year ago
WILD = '*'
def path_to_top(path: str) -> str:
"""path pivot under top"""
pre = f'{os.path.sep}{nodes.NAME_TOP}'
1 year ago
if not path.startswith(pre):
# prepend with top node path
path = pre + path
return path
def path_to_search_all(path: str) -> str:
"""path to search for all subs"""
if not path:
path = os.path.sep
if not path.startswith(os.path.sep):
path = os.path.sep + path
pre = f'{os.path.sep}{nodes.NAME_TOP}'
1 year ago
if not path.startswith(pre):
# prepend with top node path
path = pre + path
if not path.endswith(os.path.sep):
1 year ago
# ensure ends with a separator
path += os.path.sep
# if not path.endswith(WILD):
# # add wild card
# path += WILD
1 year ago
return path
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'
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')