Skip to content

Commit

Permalink
Stop using __utils__ in a few windows related module/states/utils
Browse files Browse the repository at this point in the history
Signed-off-by: Pedro Algarvio <palgarvio@vmware.com>
  • Loading branch information
s0undt3ch committed Jul 14, 2023
1 parent ce42bef commit 0de2602
Show file tree
Hide file tree
Showing 39 changed files with 471 additions and 776 deletions.
15 changes: 8 additions & 7 deletions salt/modules/chocolatey.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

import salt.utils.data
import salt.utils.platform
import salt.utils.win_dotnet
from salt.exceptions import (
CommandExecutionError,
CommandNotFoundError,
Expand Down Expand Up @@ -207,7 +208,7 @@ def bootstrap(force=False, source=None):
except CommandExecutionError:
choc_path = None
if choc_path and not force:
return "Chocolatey found at {}".format(choc_path)
return f"Chocolatey found at {choc_path}"

temp_dir = tempfile.gettempdir()

Expand Down Expand Up @@ -274,7 +275,7 @@ def bootstrap(force=False, source=None):
# Check that .NET v4.0+ is installed
# Windows 7 / Windows Server 2008 R2 and below do not come with at least
# .NET v4.0 installed
if not __utils__["dotnet.version_at_least"](version="4"):
if not salt.utils.win_dotnet.version_at_least(version="4"):
# It took until .NET v4.0 for Microsoft got the hang of making
# installers, this should work under any version of Windows
url = "http://download.microsoft.com/download/1/B/E/1BE39E79-7E39-46A3-96FF-047F95396215/dotNetFx40_Full_setup.exe"
Expand Down Expand Up @@ -335,7 +336,7 @@ def bootstrap(force=False, source=None):

if not os.path.exists(script):
raise CommandExecutionError(
"Failed to find Chocolatey installation script: {}".format(script)
f"Failed to find Chocolatey installation script: {script}"
)

# Run the Chocolatey bootstrap
Expand Down Expand Up @@ -377,7 +378,7 @@ def unbootstrap():
if os.path.exists(choco_dir):
log.debug("Removing Chocolatey directory: %s", choco_dir)
__salt__["file.remove"](path=choco_dir, force=True)
removed.append("Removed Directory: {}".format(choco_dir))
removed.append(f"Removed Directory: {choco_dir}")
else:
known_paths = [
os.path.join(os.environ.get("ProgramData"), "Chocolatey"),
Expand All @@ -387,7 +388,7 @@ def unbootstrap():
if os.path.exists(path):
log.debug("Removing Chocolatey directory: %s", path)
__salt__["file.remove"](path=path, force=True)
removed.append("Removed Directory: {}".format(path))
removed.append(f"Removed Directory: {path}")

# Delete all Chocolatey environment variables
for env_var in __salt__["environ.items"]():
Expand All @@ -399,14 +400,14 @@ def unbootstrap():
__salt__["environ.setval"](
key=env_var, val=False, false_unsets=True, permanent="HKCU"
)
removed.append("Removed Environment Var: {}".format(env_var))
removed.append(f"Removed Environment Var: {env_var}")

# Remove Chocolatey from the path:
for path in __salt__["win_path.get_path"]():
if "chocolatey" in path.lower():
log.debug("Removing Chocolatey path item: %s", path)
__salt__["win_path.remove"](path=path, rehash=True)
removed.append("Removed Path Item: {}".format(path))
removed.append(f"Removed Path Item: {path}")

return removed

Expand Down
10 changes: 6 additions & 4 deletions salt/modules/environ.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
import os

import salt.utils.platform
import salt.utils.win_functions
import salt.utils.win_reg

log = logging.getLogger(__name__)

Expand Down Expand Up @@ -71,8 +73,8 @@ def setval(key, val, false_unsets=False, permanent=False):
try:
os.environ.pop(key, None)
if permanent and is_windows:
__utils__["reg.delete_value"](permanent_hive, permanent_key, key)
__utils__["win_functions.broadcast_setting_change"]()
salt.utils.win_reg.delete_value(permanent_hive, permanent_key, key)
salt.utils.win_functions.broadcast_setting_change()
return None
except Exception as exc: # pylint: disable=broad-except
log.error(
Expand All @@ -88,8 +90,8 @@ def setval(key, val, false_unsets=False, permanent=False):
try:
os.environ[key] = val
if permanent and is_windows:
__utils__["reg.set_value"](permanent_hive, permanent_key, key, val)
__utils__["win_functions.broadcast_setting_change"]()
salt.utils.win_reg.set_value(permanent_hive, permanent_key, key, val)
salt.utils.win_functions.broadcast_setting_change()
return os.environ[key]
except Exception as exc: # pylint: disable=broad-except
log.error(
Expand Down
59 changes: 23 additions & 36 deletions salt/modules/pip.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@
import salt.utils.stringutils
import salt.utils.url
import salt.utils.versions
import salt.utils.win_dacl
from salt.exceptions import CommandExecutionError, CommandNotFoundError

# This needs to be named logger so we don't shadow it in pip.install
Expand Down Expand Up @@ -136,7 +137,7 @@ def _clear_context(bin_env=None):
"""
contextkey = "pip.version"
if bin_env is not None:
contextkey = "{}.{}".format(contextkey, bin_env)
contextkey = f"{contextkey}.{bin_env}"
__context__.pop(contextkey, None)


Expand Down Expand Up @@ -189,7 +190,7 @@ def _search_paths(*basedirs):
bin_path,
)
raise CommandNotFoundError(
"Could not find a pip binary in virtualenv {}".format(bin_env)
f"Could not find a pip binary in virtualenv {bin_env}"
)

# bin_env is the python or pip binary
Expand All @@ -201,12 +202,10 @@ def _search_paths(*basedirs):
# We have been passed a pip binary, use the pip binary.
return [os.path.normpath(bin_env)]

raise CommandExecutionError(
"Could not find a pip binary within {}".format(bin_env)
)
raise CommandExecutionError(f"Could not find a pip binary within {bin_env}")
else:
raise CommandNotFoundError(
"Access denied to {}, could not find a pip binary".format(bin_env)
f"Access denied to {bin_env}, could not find a pip binary"
)


Expand Down Expand Up @@ -325,7 +324,7 @@ def _process_requirements(requirements, cmd, cwd, saltenv, user):
# In Windows, just being owner of a file isn't enough. You also
# need permissions
if salt.utils.platform.is_windows():
__utils__["dacl.set_permissions"](
salt.utils.win_dacl.set_permissions(
obj_name=treq, principal=user, permissions="read_execute"
)

Expand Down Expand Up @@ -412,9 +411,7 @@ def _format_env_vars(env_vars):
val = str(val)
ret[key] = val
else:
raise CommandExecutionError(
"env_vars {} is not a dictionary".format(env_vars)
)
raise CommandExecutionError(f"env_vars {env_vars} is not a dictionary")
return ret


Expand Down Expand Up @@ -464,7 +461,7 @@ def install(
cache_dir=None,
no_binary=None,
disable_version_check=False,
**kwargs
**kwargs,
):
"""
Install packages with pip
Expand Down Expand Up @@ -757,9 +754,9 @@ def install(

if log:
if os.path.isdir(log):
raise OSError("'{}' is a directory. Use --log path_to_file".format(log))
raise OSError(f"'{log}' is a directory. Use --log path_to_file")
elif not os.access(log, os.W_OK):
raise OSError("'{}' is not writeable".format(log))
raise OSError(f"'{log}' is not writeable")

cmd.extend(["--log", log])

Expand All @@ -784,9 +781,7 @@ def install(
raise ValueError("Timeout cannot be a float")
int(timeout)
except ValueError:
raise ValueError(
"'{}' is not a valid timeout, must be an integer".format(timeout)
)
raise ValueError(f"'{timeout}' is not a valid timeout, must be an integer")
cmd.extend(["--timeout", timeout])

if find_links:
Expand All @@ -797,9 +792,7 @@ def install(
if not (
salt.utils.url.validate(link, VALID_PROTOS) or os.path.exists(link)
):
raise CommandExecutionError(
"'{}' is not a valid URL or path".format(link)
)
raise CommandExecutionError(f"'{link}' is not a valid URL or path")
cmd.extend(["--find-links", link])

if no_index and (index_url or extra_index_url):
Expand All @@ -809,14 +802,12 @@ def install(

if index_url:
if not salt.utils.url.validate(index_url, VALID_PROTOS):
raise CommandExecutionError("'{}' is not a valid URL".format(index_url))
raise CommandExecutionError(f"'{index_url}' is not a valid URL")
cmd.extend(["--index-url", index_url])

if extra_index_url:
if not salt.utils.url.validate(extra_index_url, VALID_PROTOS):
raise CommandExecutionError(
"'{}' is not a valid URL".format(extra_index_url)
)
raise CommandExecutionError(f"'{extra_index_url}' is not a valid URL")
cmd.extend(["--extra-index-url", extra_index_url])

if no_index:
Expand All @@ -836,7 +827,7 @@ def install(
cmd.append("--use-mirrors")
for mirror in mirrors:
if not mirror.startswith("http://"):
raise CommandExecutionError("'{}' is not a valid URL".format(mirror))
raise CommandExecutionError(f"'{mirror}' is not a valid URL")
cmd.extend(["--mirrors", mirror])

if disable_version_check:
Expand Down Expand Up @@ -994,7 +985,7 @@ def install(
# Don't allow any recursion into keyword arg definitions
# Don't allow multiple definitions of a keyword
if isinstance(val, (dict, list)):
raise TypeError("Too many levels in: {}".format(key))
raise TypeError(f"Too many levels in: {key}")
# This is a a normal one-to-one keyword argument
cmd.extend([key, val])
# It is a positional argument, append it to the list
Expand Down Expand Up @@ -1107,7 +1098,7 @@ def uninstall(
# TODO make this check if writeable
os.path.exists(log)
except OSError:
raise OSError("'{}' is not writeable".format(log))
raise OSError(f"'{log}' is not writeable")

cmd.extend(["--log", log])

Expand All @@ -1132,9 +1123,7 @@ def uninstall(
raise ValueError("Timeout cannot be a float")
int(timeout)
except ValueError:
raise ValueError(
"'{}' is not a valid timeout, must be an integer".format(timeout)
)
raise ValueError(f"'{timeout}' is not a valid timeout, must be an integer")
cmd.extend(["--timeout", timeout])

if pkgs:
Expand Down Expand Up @@ -1336,7 +1325,7 @@ def list_(prefix=None, bin_env=None, user=None, cwd=None, env_vars=None, **kwarg
user=user,
cwd=cwd,
env_vars=env_vars,
**kwargs
**kwargs,
)

cmd = _get_pip_bin(bin_env)
Expand Down Expand Up @@ -1394,7 +1383,7 @@ def version(bin_env=None, cwd=None, user=None):
cwd = _pip_bin_env(cwd, bin_env)
contextkey = "pip.version"
if bin_env is not None:
contextkey = "{}.{}".format(contextkey, bin_env)
contextkey = f"{contextkey}.{bin_env}"

if contextkey in __context__:
return __context__[contextkey]
Expand Down Expand Up @@ -1650,14 +1639,12 @@ def list_all_versions(

if index_url:
if not salt.utils.url.validate(index_url, VALID_PROTOS):
raise CommandExecutionError("'{}' is not a valid URL".format(index_url))
raise CommandExecutionError(f"'{index_url}' is not a valid URL")
cmd.extend(["--index-url", index_url])

if extra_index_url:
if not salt.utils.url.validate(extra_index_url, VALID_PROTOS):
raise CommandExecutionError(
"'{}' is not a valid URL".format(extra_index_url)
)
raise CommandExecutionError(f"'{extra_index_url}' is not a valid URL")
cmd.extend(["--extra-index-url", extra_index_url])

# Is the `pip index` command available
Expand All @@ -1669,7 +1656,7 @@ def list_all_versions(
if salt.utils.versions.compare(ver1=pip_version, oper=">=", ver2="20.3"):
cmd.append("--use-deprecated=legacy-resolver")
regex = re.compile(r"\s*Could not find a version.* \(from versions: (.*)\)")
cmd.extend(["install", "{}==versions".format(pkg)])
cmd.extend(["install", f"{pkg}==versions"])

cmd_kwargs = dict(
cwd=cwd, runas=user, output_loglevel="quiet", redirect_stderr=True
Expand Down
Loading

0 comments on commit 0de2602

Please sign in to comment.