llm.user_dir() creates directory if needed, closes #275

Would have fixed this bug too:
- https://github.com/simonw/llm-sentence-transformers/issues/9
This commit is contained in:
Simon Willison 2023-09-13 15:58:09 -07:00
parent 4711336800
commit 6c43948325
3 changed files with 16 additions and 3 deletions

View file

@ -9,7 +9,7 @@ LLM stores various pieces of logging and configuration data in a directory on th
On macOS this directory is `~/Library/Application Support/io.datasette.llm`, but this will differ on other operating systems.
The `llm.user_dir()` function returns the path to this directory as a `pathlib.Path` object.
The `llm.user_dir()` function returns the path to this directory as a `pathlib.Path` object, after creating that directory if it does not yet exist.
Plugins can use this to store their own data in a subdirectory of this directory.

View file

@ -188,8 +188,11 @@ def load_keys():
def user_dir():
llm_user_path = os.environ.get("LLM_USER_PATH")
if llm_user_path:
return pathlib.Path(llm_user_path)
return pathlib.Path(click.get_app_dir("io.datasette.llm"))
path = pathlib.Path(llm_user_path)
else:
path = pathlib.Path(click.get_app_dir("io.datasette.llm"))
path.mkdir(exist_ok=True, parents=True)
return path
def set_alias(alias, model_id_or_alias):

View file

@ -1,5 +1,6 @@
from click.testing import CliRunner
import datetime
import llm
from llm.cli import cli
from llm.migrations import migrate
import json
@ -354,3 +355,12 @@ def test_llm_models_options(user_path):
result = runner.invoke(cli, ["models", "--options"], catch_exceptions=False)
assert result.exit_code == 0
assert EXPECTED_OPTIONS.strip() in result.output
def test_llm_user_dir(tmpdir, monkeypatch):
user_dir = str(tmpdir / "u")
monkeypatch.setenv("LLM_USER_PATH", user_dir)
assert not os.path.exists(user_dir)
user_dir2 = llm.user_dir()
assert user_dir == str(user_dir2)
assert os.path.exists(user_dir)