Skip to content

Commit

Permalink
Improve install_collection implementation
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 22, 2021
1 parent 1fd086c commit cc34b97
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 8 deletions.
2 changes: 1 addition & 1 deletion src/ansiblelint/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@


options = Namespace(
cache_dir=".cache",
cache_dir=None,
colored=True,
configured=False,
cwd=".",
Expand Down
22 changes: 15 additions & 7 deletions src/ansiblelint/prerun.py
Original file line number Diff line number Diff line change
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,13 +106,13 @@ 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))
_logger.warning("Running %s", " ".join(cmd))
run = subprocess.run(
cmd,
universal_newlines=True,
Expand Down Expand Up @@ -201,7 +201,9 @@ 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}", f"{options.cache_dir}/collections"
)

_install_galaxy_role()
_perform_mockings()
Expand Down Expand Up @@ -437,7 +439,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 +455,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 cc34b97

Please sign in to comment.