Skip to content

Commit f8c7695

Browse files
committed
Change cache_dir location to prefer venv and project_directory
1 parent 18696a6 commit f8c7695

File tree

5 files changed

+42
-22
lines changed

5 files changed

+42
-22
lines changed

.vscode/settings.json

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
"source.fixAll": "explicit",
1111
"source.organizeImports": "explicit"
1212
},
13-
"editor.defaultFormatter": "ms-python.black-formatter",
13+
"editor.defaultFormatter": "charliermarsh.ruff",
1414
"editor.formatOnSave": true
1515
},
1616
"editor.formatOnSave": true,
@@ -40,5 +40,6 @@
4040
"yaml.completion": true,
4141
"yaml.customTags": ["!encrypted/pkcs1-oaep scalar", "!vault scalar"],
4242
"yaml.format.enable": false,
43-
"yaml.validate": true
43+
"yaml.validate": true,
44+
"cSpell.words": ["delenv"]
4445
}

src/ansible_compat/prerun.py

Lines changed: 18 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,25 @@
11
"""Utilities for configuring ansible runtime environment."""
22

3-
import hashlib
43
import os
54
from pathlib import Path
65

76

8-
def get_cache_dir(project_dir: Path) -> Path:
9-
"""Compute cache directory to be used based on project path."""
10-
# we only use the basename instead of the full path in order to ensure that
11-
# we would use the same key regardless the location of the user home
12-
# directory or where the project is clones (as long the project folder uses
13-
# the same name).
14-
basename = project_dir.resolve().name.encode(encoding="utf-8")
15-
# 6 chars of entropy should be enough
16-
cache_key = hashlib.sha256(basename).hexdigest()[:6]
17-
cache_dir = (
18-
Path(os.getenv("XDG_CACHE_HOME", "~/.cache")).expanduser()
19-
/ "ansible-compat"
20-
/ cache_key
21-
)
7+
def get_cache_dir(project_dir: Path, *, isolated: bool = True) -> Path:
8+
"""Compute cache directory to be used based on project path.
9+
10+
Returns:
11+
Cache directory path.
12+
"""
13+
if "VIRTUAL_ENV" in os.environ:
14+
cache_dir = Path(os.environ["VIRTUAL_ENV"]) / ".ansible"
15+
elif isolated:
16+
cache_dir = project_dir / ".ansible"
17+
else:
18+
cache_dir = Path(os.environ.get("ANSIBLE_HOME", "~/.ansible")).expanduser()
19+
20+
# Ensure basic folder structure exists so `ansible-galaxy list` does not
21+
# fail with: None of the provided paths were usable. Please specify a valid path with
22+
for name in ("roles", "collections"):
23+
(cache_dir / name).mkdir(parents=True, exist_ok=True)
24+
2225
return cache_dir

src/ansible_compat/runtime.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -208,8 +208,8 @@ def __init__(
208208
if "PYTHONWARNINGS" not in self.environ: # pragma: no cover
209209
self.environ["PYTHONWARNINGS"] = "ignore:Blowfish has been deprecated"
210210

211-
if isolated:
212-
self.cache_dir = get_cache_dir(self.project_dir)
211+
self.cache_dir = get_cache_dir(self.project_dir, isolated=self.isolated)
212+
213213
self.config = AnsibleConfig(cache_dir=self.cache_dir)
214214

215215
# Add the sys.path to the collection paths if not isolated

test/test_prerun.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,12 @@
11
"""Tests for ansible_compat.prerun module."""
22

3+
from __future__ import annotations
4+
35
from pathlib import Path
6+
from typing import TYPE_CHECKING
7+
8+
if TYPE_CHECKING:
9+
from _pytest.monkeypatch import MonkeyPatch
410

511
from ansible_compat.prerun import get_cache_dir
612

@@ -10,3 +16,9 @@ def test_get_cache_dir_relative() -> None:
1016
relative_path = Path()
1117
abs_path = relative_path.resolve()
1218
assert get_cache_dir(relative_path) == get_cache_dir(abs_path)
19+
20+
21+
def test_get_cache_dir_no_isolation_no_venv(monkeypatch: MonkeyPatch) -> None:
22+
"""Test behaviors of get_cache_dir."""
23+
monkeypatch.delenv("VIRTUAL_ENV", raising=False)
24+
assert get_cache_dir(Path(), isolated=False) == Path("~/.ansible").expanduser()

test/test_runtime.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -652,10 +652,9 @@ def test_upgrade_collection(runtime_tmp: Runtime) -> None:
652652
runtime_tmp.require_collection("community.molecule", "0.1.0")
653653

654654

655-
def test_require_collection_no_cache_dir() -> None:
655+
def test_require_collection_not_isolated() -> None:
656656
"""Check require_collection without a cache directory."""
657-
runtime = Runtime()
658-
assert not runtime.cache_dir
657+
runtime = Runtime(isolated=False)
659658
runtime.require_collection("community.molecule", "0.1.0", install=True)
660659

661660

@@ -1022,6 +1021,11 @@ def test_runtime_has_playbook() -> None:
10221021
"""Tests has_playbook method."""
10231022
runtime = Runtime(require_module=True)
10241023

1024+
runtime.prepare_environment(
1025+
required_collections={"community.molecule": "0.1.0"},
1026+
install_local=True,
1027+
)
1028+
10251029
assert not runtime.has_playbook("this-does-not-exist.yml")
10261030
# call twice to ensure cache is used:
10271031
assert not runtime.has_playbook("this-does-not-exist.yml")

0 commit comments

Comments
 (0)