From 60fd075506093d94107515788511f4a56f876817 Mon Sep 17 00:00:00 2001 From: Guilhem Moulin Date: Mon, 3 Jun 2024 16:06:25 +0200 Subject: webmap-download: Move format_bytes() and format_time() to common.py. --- common.py | 17 +++++++++++++++++ webmap-download | 23 +++-------------------- 2 files changed, 20 insertions(+), 20 deletions(-) diff --git a/common.py b/common.py index 00d1add..0036df4 100644 --- a/common.py +++ b/common.py @@ -4,6 +4,7 @@ from fnmatch import fnmatchcase from pathlib import Path, PosixPath from urllib.parse import urlparse, urlunparse from stat import S_ISDIR +from math import modf from xdg.BaseDirectory import xdg_config_home import logging import yaml @@ -118,6 +119,22 @@ def load_config(path=None, groupnames=None): config['layers'] = layers sys.modules[__name__].config = config +def format_bytes(n): + if n < 768: + return f'{n}B' + elif n < 768*1024: + return f'{n/1024:.2f}kiB' + elif n < 768*1024*1024: + return f'{n/1048576:.2f}MiB' + else: + return f'{n/1073741824:.2f}GiB' + +def format_time(s): + fs, s = modf(s) + m, s = divmod(int(s), 60) + h, m = divmod(m, 60) + return f'{h:02d}:{m:02d}:{s + fs:06.3f}' + ###### # The function definitions below are taken from cpython's source code diff --git a/webmap-download b/webmap-download index 6040356..fb52d7d 100755 --- a/webmap-download +++ b/webmap-download @@ -10,7 +10,6 @@ import itertools from pathlib import Path from email.utils import parsedate_to_datetime, formatdate from hashlib import sha1 -from math import modf import requests import common @@ -112,24 +111,8 @@ def download(url, dest, dir_fd=None, headers={}, session=requests, progress=None raise e elapsed = time_monotonic() - start - logging.info("%s: Downloaded %s in %s (%s/s)", dest, format_bytes(size), - format_time(elapsed), format_bytes(int(size/elapsed))) - -def format_bytes(n): - if n < 768: - return f'{n}B' - elif n < 786432: - return f'{n/1024:.2f}kiB' - elif n < 805306368: - return f'{n/1048576:.2f}MiB' - else: - return f'{n/1073741824:.2f}GiB' - -def format_time(s): - fs, s = modf(s) - m, s = divmod(int(s), 60) - h, m = divmod(m, 60) - return f'{h:02d}:{m:02d}:{s + fs:06.3f}' + logging.info("%s: Downloaded %s in %s (%s/s)", dest, common.format_bytes(size), + common.format_time(elapsed), common.format_bytes(int(size/elapsed))) if __name__ == '__main__': logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.INFO) @@ -229,7 +212,7 @@ if __name__ == '__main__': s = max_age + max(st.st_ctime, st.st_mtime) - time() if s > 0: logging.info('%s: Too young, try again in %s', - dest, format_time(s)) + dest, common.format_time(s)) continue headers['If-Modified-Since'] = formatdate(timeval=st.st_mtime, localtime=False, usegmt=True) fetch(dl, dest, dir_fd=destdir_fd, -- cgit v1.2.3