|
| 1 | +###################################################################### |
| 2 | +# |
| 3 | +# File: b2/_cli/autocomplete_cache.py |
| 4 | +# |
| 5 | +# Copyright 2020 Backblaze Inc. All Rights Reserved. |
| 6 | +# |
| 7 | +# License https://www.backblaze.com/using_b2_code.html |
| 8 | +# |
| 9 | +###################################################################### |
| 10 | +from __future__ import annotations |
| 11 | + |
| 12 | +import abc |
| 13 | +import argparse |
| 14 | +import os |
| 15 | +import pathlib |
| 16 | +import pickle |
| 17 | +from typing import Callable |
| 18 | + |
| 19 | +import argcomplete |
| 20 | +import platformdirs |
| 21 | + |
| 22 | +from b2.version import VERSION |
| 23 | + |
| 24 | + |
| 25 | +def identity(x): |
| 26 | + return x |
| 27 | + |
| 28 | + |
| 29 | +class StateTracker(abc.ABC): |
| 30 | + @abc.abstractmethod |
| 31 | + def current_state_identifier(self) -> str: |
| 32 | + raise NotImplementedError() |
| 33 | + |
| 34 | + |
| 35 | +class PickleStore(abc.ABC): |
| 36 | + @abc.abstractmethod |
| 37 | + def get_pickle(self, identifier: str) -> bytes | None: |
| 38 | + raise NotImplementedError() |
| 39 | + |
| 40 | + @abc.abstractmethod |
| 41 | + def set_pickle(self, identifier: str, data: bytes) -> None: |
| 42 | + raise NotImplementedError() |
| 43 | + |
| 44 | + |
| 45 | +class VersionTracker(StateTracker): |
| 46 | + def current_state_identifier(self) -> str: |
| 47 | + return VERSION |
| 48 | + |
| 49 | + |
| 50 | +class HomeCachePickleStore(PickleStore): |
| 51 | + _dir: pathlib.Path |
| 52 | + |
| 53 | + def __init__(self, dir: pathlib.Path | None = None) -> None: |
| 54 | + self._dir = dir |
| 55 | + |
| 56 | + def _cache_dir(self) -> pathlib.Path: |
| 57 | + if self._dir: |
| 58 | + return self._dir |
| 59 | + self._dir = pathlib.Path( |
| 60 | + platformdirs.user_cache_dir(appname='b2', appauthor='backblaze') |
| 61 | + ) / 'autocomplete' |
| 62 | + return self._dir |
| 63 | + |
| 64 | + def _fname(self, identifier: str) -> str: |
| 65 | + return f"b2-autocomplete-cache-{identifier}.pickle" |
| 66 | + |
| 67 | + def get_pickle(self, identifier: str) -> bytes | None: |
| 68 | + path = self._cache_dir() / self._fname(identifier) |
| 69 | + if path.exists(): |
| 70 | + with open(path, 'rb') as f: |
| 71 | + return f.read() |
| 72 | + |
| 73 | + def set_pickle(self, identifier: str, data: bytes) -> None: |
| 74 | + """Sets the pickle for identifier if it doesn't exist. |
| 75 | + When a new pickle is added, old ones are removed.""" |
| 76 | + |
| 77 | + dir = self._cache_dir() |
| 78 | + os.makedirs(dir, exist_ok=True) |
| 79 | + path = dir / self._fname(identifier) |
| 80 | + for file in dir.glob('b2-autocomplete-cache-*.pickle'): |
| 81 | + file.unlink() |
| 82 | + with open(path, 'wb') as f: |
| 83 | + f.write(data) |
| 84 | + |
| 85 | + |
| 86 | +class AutocompleteCache: |
| 87 | + _tracker: StateTracker |
| 88 | + _store: PickleStore |
| 89 | + _unpickle: Callable[[bytes], argparse.ArgumentParser] |
| 90 | + |
| 91 | + def __init__( |
| 92 | + self, |
| 93 | + tracker: StateTracker, |
| 94 | + store: PickleStore, |
| 95 | + unpickle: Callable[[bytes], argparse.ArgumentParser] | None = None |
| 96 | + ): |
| 97 | + self._tracker = tracker |
| 98 | + self._store = store |
| 99 | + self._unpickle = unpickle or pickle.loads |
| 100 | + |
| 101 | + def _is_autocomplete_run(self) -> bool: |
| 102 | + return '_ARGCOMPLETE' in os.environ |
| 103 | + |
| 104 | + def autocomplete_from_cache(self, uncached_args: dict | None = None) -> None: |
| 105 | + if not self._is_autocomplete_run(): |
| 106 | + return |
| 107 | + |
| 108 | + try: |
| 109 | + identifier = self._tracker.current_state_identifier() |
| 110 | + pickle_data = self._store.get_pickle(identifier) |
| 111 | + if pickle_data: |
| 112 | + parser = self._unpickle(pickle_data) |
| 113 | + argcomplete.autocomplete(parser, **(uncached_args or {})) |
| 114 | + except Exception: |
| 115 | + # Autocomplete from cache failed but maybe we can autocomplete from scratch |
| 116 | + return |
| 117 | + |
| 118 | + def _clean_parser(self, parser: argparse.ArgumentParser) -> None: |
| 119 | + parser.register('type', None, identity) |
| 120 | + for action in parser._actions: |
| 121 | + if action.type not in [str, int]: |
| 122 | + action.type = None |
| 123 | + for action in parser._action_groups: |
| 124 | + for key in parser._defaults: |
| 125 | + action.set_defaults(**{key: None}) |
| 126 | + parser.description = None |
| 127 | + if parser._subparsers: |
| 128 | + for group_action in parser._subparsers._group_actions: |
| 129 | + for parser in group_action.choices.values(): |
| 130 | + self._clean_parser(parser) |
| 131 | + |
| 132 | + def cache_and_autocomplete( |
| 133 | + self, parser: argparse.ArgumentParser, uncached_args: dict | None = None |
| 134 | + ) -> None: |
| 135 | + if not self._is_autocomplete_run(): |
| 136 | + return |
| 137 | + |
| 138 | + try: |
| 139 | + identifier = self._tracker.current_state_identifier() |
| 140 | + self._clean_parser(parser) |
| 141 | + self._store.set_pickle(identifier, pickle.dumps(parser)) |
| 142 | + finally: |
| 143 | + argcomplete.autocomplete(parser, **(uncached_args or {})) |
| 144 | + |
| 145 | + |
| 146 | +AUTOCOMPLETE = AutocompleteCache(tracker=VersionTracker(), store=HomeCachePickleStore()) |
0 commit comments