Skip to content

Commit

Permalink
Improve install_collection implementation (#1637)
Browse files Browse the repository at this point in the history
- assure at default verbosity we do log ansible-galaxy command ran
- add ability to specify destination for install_collection
- assure we inject our own cache to top of collection path
- allow use of require_collection without a cache folder.
  • Loading branch information
ssbarnea committed Jun 24, 2021
1 parent 040ae19 commit 57a6d5b
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 7 deletions.
2 changes: 1 addition & 1 deletion src/ansiblelint/config.py
Expand Up @@ -60,7 +60,7 @@


options = Namespace(
cache_dir=".cache",
cache_dir=None,
colored=True,
configured=False,
cwd=".",
Expand Down
23 changes: 17 additions & 6 deletions src/ansiblelint/prerun.py
Expand Up @@ -97,7 +97,7 @@ def _get_ver_err() -> Tuple[str, str]:
return ver, err


def install_collection(collection: str) -> None:
def install_collection(collection: str, destination: Optional[str] = None) -> None:
"""Install an Ansible collection.
Can accept version constraints like 'foo.bar:>=1.2.3'
Expand All @@ -106,11 +106,11 @@ def install_collection(collection: str) -> None:
"ansible-galaxy",
"collection",
"install",
"-p",
f"{options.cache_dir}/collections",
"-v",
f"{collection}",
]
if destination:
cmd.extend(["-p", destination])
cmd.append(f"{collection}")

_logger.info("Running %s", " ".join(cmd))
run = subprocess.run(
Expand Down Expand Up @@ -201,7 +201,12 @@ def prepare_environment(required_collections: Optional[Dict[str, str]] = None) -

if required_collections:
for name, min_version in required_collections.items():
install_collection(f"{name}:>={min_version}")
install_collection(
f"{name}:>={min_version}",
destination=f"{options.cache_dir}/collections"
if options.cache_dir
else None,
)

_install_galaxy_role()
_perform_mockings()
Expand Down Expand Up @@ -437,7 +442,7 @@ def ansible_config_get(key: str, kind: Type[Any] = str) -> Union[str, List[str],
return None


def require_collection(
def require_collection( # noqa: C901
name: str, version: Optional[str] = None, install: bool = True
) -> None:
"""Check if a minimal collection version is present or exits.
Expand All @@ -453,6 +458,12 @@ def require_collection(
paths = ansible_config_get('COLLECTIONS_PATHS', list)
if not paths or not isinstance(paths, list):
sys.exit(f"Unable to determine ansible collection paths. ({paths})")

if options.cache_dir:
# if we have a cache dir, we want to be use that would be preferred
# destination when installing a missing collection
paths.insert(0, f"{options.cache_dir}/collections")

for path in paths:
collpath = os.path.join(path, 'ansible_collections', ns, coll)
if os.path.exists(collpath):
Expand Down

0 comments on commit 57a6d5b

Please sign in to comment.