import nilmdb
import os
from math import log

def sizeof_fmt(num):
    """Human friendly file size"""
    unit_list = zip(['bytes', 'kiB', 'MiB', 'GiB', 'TiB'], [0, 0, 1, 2, 2])
    if num > 1:
        exponent = min(int(log(num, 1024)), len(unit_list) - 1)
        quotient = float(num) / 1024**exponent
        unit, num_decimals = unit_list[exponent]
        format_string = '{:.%sf} {}' % (num_decimals)
        return format_string.format(quotient, unit)
    if num == 0: # pragma: no cover
        return '0 bytes'
    if num == 1: # pragma: no cover
        return '1 byte'

def du_bytes(path):
    """Like du -sb, returns total size of path in bytes."""
    size = os.path.getsize(path)
    if os.path.isdir(path):
        for file in os.listdir(path):
            filepath = os.path.join(path, file)
            size += du_bytes(filepath)
    return size

def du(path):
    """Like du -sh, returns total size of path as a human-readable string."""
    return sizeof_fmt(du_bytes(path))
