Skip to content

Commit 745785e

Browse files
authored
Merge pull request #105 from machow/chore-prompts-logs
Chore prompts logs
2 parents f9391b5 + 0a44e52 commit 745785e

File tree

7 files changed

+85
-36
lines changed

7 files changed

+85
-36
lines changed

pins/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010

1111
# Imports ----
1212
from .boards import BaseBoard
13-
from .cache import PinsCache, PinsUrlCache, cache_prune
13+
from .cache import PinsCache, PinsUrlCache, cache_prune, cache_info
1414
from .constructors import (
1515
board_deparse,
1616
board_folder,

pins/boards.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,10 @@
1515
from .meta import Meta, MetaRaw, MetaFactory
1616
from .errors import PinsError
1717
from .drivers import load_data, save_data, default_title
18+
from .utils import inform
19+
20+
21+
_log = logging.getLogger(__name__)
1822

1923

2024
# Note that once we drop python 3.7, we can make this a Protocol
@@ -292,6 +296,8 @@ def pin_write(
292296
"but that directory already exists."
293297
)
294298

299+
inform(_log, f"Writing to pin {repr(pin_name)}")
300+
295301
res = self.fs.put(tmp_dir, dst_version_path, recursive=True)
296302

297303
if dst_version_path == dst_pin_path:
@@ -391,9 +397,9 @@ def pin_versions_prune(
391397
# TODO(question): how to pin_inform? Log or warning?
392398
if to_delete:
393399
str_vers = ", ".join([v.version for v in to_delete])
394-
logging.info(f"Deleting versions: {str_vers}.")
400+
inform(_log, f"Deleting versions: {str_vers}.")
395401
if not to_delete:
396-
logging.info("No old versions to delete")
402+
inform(_log, "No old versions to delete")
397403

398404
for version in to_delete:
399405
self.pin_version_delete(name, version.version)

pins/cache.py

Lines changed: 33 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,9 @@
1010
from pathlib import Path
1111

1212
from .config import get_cache_dir
13+
from .utils import inform
14+
15+
_log = logging.getLogger(__name__)
1316

1417

1518
# used if needed to preserve board path structure in the cache
@@ -65,7 +68,7 @@ def _make_local_details(self, path):
6568
# note that this is called in ._open(), at the point it's known the file
6669
# will be cached
6770
fn = super()._make_local_details(path)
68-
logging.info(f"cache file: {fn}")
71+
_log.info(f"cache file: {fn}")
6972
Path(fn).parent.mkdir(parents=True, exist_ok=True)
7073

7174
return fn
@@ -200,7 +203,7 @@ def prune(self, days=30):
200203
for path in to_prune:
201204
delete_version(to_prune)
202205

203-
logging.info("Skipping cache deletion")
206+
_log.info("Skipping cache deletion")
204207

205208

206209
def delete_version(path: "str | Path"):
@@ -213,10 +216,28 @@ def disk_usage(path):
213216

214217

215218
def prompt_cache_prune(to_prune, size) -> bool:
216-
logging.info(f"Pruning items: {to_prune}")
219+
_log.info(f"Pruning items: {to_prune}")
217220
human_size = humanize.naturalsize(size, binary=True)
218-
resp = input(f"Delete {len(to_prune)} pin versions, freeing {human_size}?")
219-
return resp == "yes"
221+
resp = input(
222+
f"Delete {len(to_prune)} pin versions, freeing {human_size}?"
223+
"\n1: Yes"
224+
"\n2: No"
225+
"\n\nSelection: "
226+
)
227+
return resp == "1"
228+
229+
230+
def cache_info():
231+
cache_root = get_cache_dir()
232+
233+
cache_boards = list(Path(cache_root).glob("*"))
234+
235+
print(f"Cache info: {cache_root}")
236+
for p_board in cache_boards:
237+
du = disk_usage(p_board)
238+
human_size = humanize.naturalsize(du, binary=True)
239+
rel_path = p_board.relative_to(cache_root)
240+
print(f"* {rel_path}: {human_size}")
220241

221242

222243
def cache_prune(days=30, cache_root=None, prompt=True):
@@ -230,32 +251,21 @@ def cache_prune(days=30, cache_root=None, prompt=True):
230251

231252
size = sum(map(disk_usage, final_delete))
232253

254+
if not final_delete:
255+
inform(_log, "No stale pins found")
256+
233257
if prompt:
234258
confirmed = prompt_cache_prune(final_delete, size)
235259
else:
236260
confirmed = True
261+
237262
if confirmed:
263+
inform(_log, "Deleting pins from cache.")
238264
for p in final_delete:
239265
delete_version(p)
266+
else:
267+
inform(_log, "Skipping deletion of pins from cache.")
240268

241269

242-
# def prune_files(days = 30, path = None):
243-
# if path is None:
244-
# for p_cache in Path(get_cache_dir()).glob("*"):
245-
# return prune_files(days=days, path=str(p_cache.absolute()))
246-
#
247-
# expiry_time_sec = days * 60 * 60 * 24
248-
# fs_cache = PinsCache(
249-
# target_protocol=None,
250-
# cache_storage=path,
251-
# check_files=True,
252-
# expiry_time=expiry_time_sec
253-
# )
254-
#
255-
# # note that fsspec considers only the last entry in cached_files deletable
256-
# for hash_path, entry in fs_cache.cached_files[-1].items():
257-
# if time.time() - detail["time"] > self.expiry:
258-
# fs_cache.pop_from_cache(entry["original"])
259-
260270
# TODO: swap to use entrypoint
261271
register_implementation("pinscache", PinsCache)

pins/config.py

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,15 @@
11
import appdirs
22
import os
33

4+
from types import SimpleNamespace
5+
46
PINS_NAME = "pins-py"
57
PINS_ENV_DATA_DIR = "PINS_DATA_DIR"
68
PINS_ENV_CACHE_DIR = "PINS_CACHE_DIR"
79
PINS_ENV_INSECURE_READ = "PINS_ALLOW_PICKLE_READ"
810

11+
pins_options = SimpleNamespace(quiet=False)
12+
913

1014
def get_data_dir():
1115
return os.environ.get(PINS_ENV_DATA_DIR, appdirs.user_data_dir(PINS_NAME))
@@ -29,12 +33,3 @@ def get_allow_pickle_read(flag):
2933
flag = bool(env_int)
3034

3135
return flag
32-
33-
34-
def _enable_logs():
35-
import logging
36-
37-
format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
38-
handlers = [logging.FileHandler("filename.log"), logging.StreamHandler()]
39-
40-
logging.basicConfig(level=logging.INFO, format=format, handlers=handlers)

pins/rsconnect/api.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818
RSC_CODE_OBJECT_DOES_NOT_EXIST = 4
1919
RSC_CODE_INVALID_NUMERIC_PATH = 3
2020

21+
_log = logging.getLogger(__name__)
22+
2123

2224
def _download_file(response, local_fname):
2325
"""Download a potentially large file. Note that this mutates the response.
@@ -222,7 +224,7 @@ def _raw_query(self, url, method="GET", return_request=False, **kwargs):
222224

223225
headers = self._get_headers()
224226

225-
logging.info(f"RSConnect API {method}: {url} -- {kwargs}")
227+
_log.debug(f"RSConnect API {method}: {url} -- {kwargs}")
226228
r = self.session.request(method, url, headers=headers, **kwargs)
227229

228230
if return_request:

pins/tests/test_utils.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import pytest
2+
3+
from pins.utils import inform
4+
from pins.config import pins_options
5+
6+
7+
@pytest.fixture
8+
def quiet():
9+
orig = pins_options.quiet
10+
pins_options.quiet = True
11+
yield
12+
pins_options.quiet = orig
13+
14+
15+
def test_inform(capsys):
16+
msg = "a message"
17+
inform(None, msg)
18+
captured = capsys.readouterr()
19+
assert captured.err == msg + "\n"
20+
21+
22+
def test_inform_quiet(quiet, capsys):
23+
inform(None, "a message")
24+
captured = capsys.readouterr()
25+
assert captured.err == ""

pins/utils.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import sys
2+
3+
from .config import pins_options
4+
5+
6+
def inform(log, msg):
7+
if log is not None:
8+
log.info(msg)
9+
10+
if not pins_options.quiet:
11+
print(msg, file=sys.stderr)

0 commit comments

Comments
 (0)