|
71 | 71 | environment=SENTRY_ENV, |
72 | 72 | ) |
73 | 73 |
|
| 74 | +POW_10_BYTES = [ |
| 75 | + ("B", 10 ** 0), |
| 76 | + ("KB", 10 ** 3), |
| 77 | + ("MB", 10 ** 6), |
| 78 | + ("GB", 10 ** 9), |
| 79 | + ("TB", 10 ** 12), |
| 80 | + ("PB", 10 ** 15), |
| 81 | + ("EB", 10 ** 18), |
| 82 | +] |
| 83 | + |
| 84 | +POW_2_BYTES = [ |
| 85 | + ("B", 2 ** 0), |
| 86 | + ("KiB", 2 ** 10), |
| 87 | + ("MiB", 2 ** 20), |
| 88 | + ("GiB", 2 ** 30), |
| 89 | + ("TiB", 2 ** 40), |
| 90 | + ("PiB", 2 ** 50), |
| 91 | + ("EiB", 2 ** 60), |
| 92 | +] |
| 93 | + |
74 | 94 |
|
75 | 95 | def sentry_message(message): |
76 | 96 | if error_reporting_enabled(): |
@@ -1007,15 +1027,30 @@ def isatty(ob): |
1007 | 1027 | return hasattr(ob, "isatty") and ob.isatty() |
1008 | 1028 |
|
1009 | 1029 |
|
1010 | | -def sizeof_fmt(num, suffix="B"): |
1011 | | - """Pretty print file size |
1012 | | - https://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size |
1013 | | - """ |
1014 | | - for unit in ["", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"]: |
1015 | | - if abs(num) < 1024.0: |
1016 | | - return "%3.1f%s%s" % (num, unit, suffix) |
1017 | | - num /= 1024.0 |
1018 | | - return "%.1f%s%s" % (num, "Yi", suffix) |
| 1030 | +def to_human_size(bytes, units=None): |
| 1031 | + units = units or POW_10_BYTES |
| 1032 | + unit, value = units[0] |
| 1033 | + factor = round(float(bytes) / value, 1) |
| 1034 | + return ( |
| 1035 | + "{}{}".format(factor, unit) |
| 1036 | + if factor < 1024 or len(units) == 1 |
| 1037 | + else to_human_size(bytes, units[1:]) |
| 1038 | + ) |
| 1039 | + |
| 1040 | + |
| 1041 | +def from_human_size(size, units=None): |
| 1042 | + units = {unit.upper(): value for (unit, value) in units or POW_10_BYTES} |
| 1043 | + regex = re.compile( |
| 1044 | + r"(\d+\.?\d*)\s*({})?".format("|".join(units.keys())), re.IGNORECASE |
| 1045 | + ) |
| 1046 | + match = re.match(regex, size) |
| 1047 | + if not match: |
| 1048 | + raise ValueError("Size must be of the form `10`, `10B` or `10 B`.") |
| 1049 | + factor, unit = ( |
| 1050 | + float(match.group(1)), |
| 1051 | + units[match.group(2).upper()] if match.group(2) else 1, |
| 1052 | + ) |
| 1053 | + return int(factor * unit) |
1019 | 1054 |
|
1020 | 1055 |
|
1021 | 1056 | def auto_project_name(program): |
|
0 commit comments