Skip to content

Commit

Permalink
Address ruff PTH123 (#1769)
Browse files Browse the repository at this point in the history
  • Loading branch information
shatakshiiii authored May 21, 2024
1 parent 2528f02 commit 031938a
Show file tree
Hide file tree
Showing 11 changed files with 28 additions and 21 deletions.
1 change: 0 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -323,7 +323,6 @@ ignore = [
'PTH119', # `os.path.basename()` should be replaced by `Path.name`
'PTH120', # `os.path.dirname()` should be replaced by `Path.parent`
'PTH122', # `os.path.splitext()` should be replaced by `Path.suffix`
'PTH123', # `open()` should be replaced by `Path.open()`
'PTH204', # `os.path.getmtime` should be replaced by `Path.stat().st_mtime`
'PTH207', # Replace `glob` with `Path.glob` or `Path.rglob`
'RET505', # Unnecessary `else` after `return` statement
Expand Down
4 changes: 3 additions & 1 deletion src/ansible_navigator/actions/log.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
"""``:log`` command implementation."""

from pathlib import Path

from ansible_navigator.action_base import ActionBase
from ansible_navigator.app_public import AppPublic
from ansible_navigator.configuration_subsystem.definitions import ApplicationConfiguration
Expand Down Expand Up @@ -35,7 +37,7 @@ def run(self, interaction: Interaction, app: AppPublic) -> Interaction:
auto_scroll = True
while True:
self._calling_app.update()
with open(self._args.log_file, encoding="utf-8") as fh:
with Path(self._args.log_file).open(encoding="utf-8") as fh:
log_contents = fh.read()

new_scroll = len(log_contents.splitlines())
Expand Down
2 changes: 1 addition & 1 deletion src/ansible_navigator/actions/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -423,7 +423,7 @@ def _init_replay(self) -> bool:
artifact_file = populated_form["fields"]["artifact_file"]["value"]

try:
with open(artifact_file, encoding="utf-8") as fh:
with Path(artifact_file).open(encoding="utf-8") as fh:
data = json.load(fh)
except json.JSONDecodeError as exc:
self._logger.debug("json decode error: %s", str(exc))
Expand Down
3 changes: 2 additions & 1 deletion src/ansible_navigator/actions/write_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,8 @@ def run(self, interaction: Interaction, app: AppPublic) -> None:
write_as = interaction.ui.content_format().value.file_extension

if write_as == ".txt":
with open(os.path.abspath(filename), file_mode, encoding="utf-8") as fh:
file = Path(os.path.abspath(filename))
with file.open(file_mode, encoding="utf-8") as fh:
fh.write(obj)
elif write_as == ".yaml":
serialize_write_file(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import os

from copy import deepcopy
from pathlib import Path

from ansible_navigator.utils.definitions import ExitMessage
from ansible_navigator.utils.definitions import ExitPrefix
Expand Down Expand Up @@ -178,7 +179,7 @@ def raise_value_error(message: str) -> None:
migration_types=(MigrationType.SETTINGS_FILE,),
)

with open(settings_filesystem_path, encoding="utf-8") as fh:
with Path(settings_filesystem_path).open(encoding="utf-8") as fh:
try:
config = yaml.load(fh, Loader=SafeLoader)
if config is None:
Expand Down
10 changes: 5 additions & 5 deletions src/ansible_navigator/data/catalog_collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ def _catalog_plugins(self, collection: dict[Any, Any]) -> None:
if file_manifest_file:
file_path = Path(collection["path"], file_manifest_file)
if file_path.exists():
with open(file=file_path, encoding="utf-8") as fh:
with file_path.open(encoding="utf-8") as fh:
try:
loaded = json.load(fh)
file_checksums = {v["name"]: v for v in loaded["files"]}
Expand Down Expand Up @@ -214,7 +214,7 @@ def _generate_checksum(file_path: Path, relative_path: Path) -> dict[str, Any]:
:returns: Details about the file, including the checksum
"""
sha256_hash = hashlib.sha256()
with open(file_path, "rb") as fh:
with file_path.open("rb") as fh:
for byte_block in iter(lambda: fh.read(4096), b""):
sha256_hash.update(byte_block)
res = {
Expand Down Expand Up @@ -264,7 +264,7 @@ def _one_path(self, directory: Path) -> None:
galaxy_file = directory_path / "galaxy.yml"
collection = None
if manifest_file.exists():
with open(file=manifest_file, encoding="utf-8") as fh:
with manifest_file.open(encoding="utf-8") as fh:
try:
collection = json.load(fh)
collection["meta_source"] = "MANIFEST.json"
Expand All @@ -275,7 +275,7 @@ def _one_path(self, directory: Path) -> None:
}
self._errors.append(error)
elif galaxy_file.exists():
with open(file=galaxy_file, encoding="utf-8") as fh:
with galaxy_file.open(encoding="utf-8") as fh:
try:
collection = {"collection_info": yaml.load(fh, Loader=SafeLoader)}
collection["meta_source"] = "galaxy.yml"
Expand All @@ -295,7 +295,7 @@ def _one_path(self, directory: Path) -> None:
runtime_file = directory_path / "meta" / "runtime.yml"
collection["runtime"] = {}
if runtime_file.exists():
with open(file=runtime_file, encoding="utf-8") as fh:
with runtime_file.open(encoding="utf-8") as fh:
try:
collection["runtime"] = yaml.load(fh, Loader=SafeLoader)
except YAMLError as exc:
Expand Down
5 changes: 3 additions & 2 deletions src/ansible_navigator/tm_tokenize/grammars.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import json
import os

from pathlib import Path
from typing import Any
from typing import NamedTuple
from typing import TypeVar
Expand Down Expand Up @@ -68,8 +69,8 @@ def _raw_for_scope(self, scope: str) -> dict[str, Any]:
except KeyError:
pass

grammar_path = self._scope_to_files.pop(scope)
with open(grammar_path, encoding="UTF-8") as f:
grammar_path = Path(self._scope_to_files.pop(scope))
with grammar_path.open(encoding="UTF-8") as f:
ret = self._raw[scope] = json.load(f)

file_types = frozenset(ret.get("fileTypes", ()))
Expand Down
4 changes: 2 additions & 2 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -349,10 +349,10 @@ def pytest_sessionstart(session: pytest.Session) -> None:
USER_ENVIRONMENT = {}


def is_config_empty(filename: str) -> bool:
def is_config_empty(filename: Path) -> bool:
"""Establish if config file is empty."""
pattern = re.compile(r"^\s*(?:#|$)")
with open(filename, encoding="utf-8") as file:
with filename.open(encoding="utf-8") as file:
for line in file:
if not pattern.match(line):
pytest.exit(f"[{line}]")
Expand Down
8 changes: 4 additions & 4 deletions tests/integration/_tmux_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -308,8 +308,8 @@ def interaction(
return showing
time.sleep(0.1)

setup_capture_path = os.path.join(self._test_log_dir, "showing_setup.txt")
timeout_capture_path = os.path.join(self._test_log_dir, "showing_timeout.txt")
setup_capture_path = Path(os.path.join(self._test_log_dir, "showing_setup.txt"))
timeout_capture_path = Path(os.path.join(self._test_log_dir, "showing_timeout.txt"))

ok_to_return = False
err_message = "RESPONSE"
Expand Down Expand Up @@ -350,7 +350,7 @@ def interaction(

elapsed = timer() - start_time
if elapsed > timeout:
with open(file=setup_capture_path, mode="w", encoding="utf-8") as fh:
with setup_capture_path.open(mode="w", encoding="utf-8") as fh:
fh.writelines("\n".join(self._setup_capture))

time_stamp = datetime.datetime.now(tz=datetime.timezone.utc).isoformat()
Expand All @@ -361,7 +361,7 @@ def interaction(
]
alerts.append(f"******** Captured to: {timeout_capture_path}")
showing = alerts + showing
with open(file=timeout_capture_path, mode="w", encoding="utf-8") as fh:
with timeout_capture_path.open(mode="w", encoding="utf-8") as fh:
fh.writelines("\n".join(showing))
self._fail_remaining = ["******** PREVIOUS TEST FAILURE ********"]
return showing
Expand Down
3 changes: 2 additions & 1 deletion tests/unit/configuration_subsystem/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import os

from copy import deepcopy
from pathlib import Path
from typing import TYPE_CHECKING
from typing import Any
from typing import NamedTuple
Expand Down Expand Up @@ -75,7 +76,7 @@ def _generate_config(

if settings_file_name:
settings_file_path = os.path.join(TEST_FIXTURE_DIR, settings_file_name)
with open(file=settings_file_path, encoding="utf-8") as fh:
with Path(settings_file_path).open(encoding="utf-8") as fh:
try:
settings_contents = yaml.load(fh, Loader=Loader)
except yaml.parser.ParserError:
Expand Down
6 changes: 4 additions & 2 deletions tests/unit/configuration_subsystem/test_fixture_sanity.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@

import os

from pathlib import Path

from ansible_navigator.configuration_subsystem import NavigatorConfiguration
from ansible_navigator.utils.serialize import Loader
from ansible_navigator.utils.serialize import yaml
Expand All @@ -23,8 +25,8 @@ def test_data_no_missing_env_var_data() -> None:

def test_full_settings_file() -> None:
"""Test using a full settings file."""
settings_file_path = os.path.join(TEST_FIXTURE_DIR, "ansible-navigator.yml")
with open(file=settings_file_path, encoding="utf-8") as fh:
settings_file_path = Path(os.path.join(TEST_FIXTURE_DIR, "ansible-navigator.yml"))
with settings_file_path.open(encoding="utf-8") as fh:
settings_contents = yaml.load(fh, Loader=Loader)
for entry in NavigatorConfiguration.entries:
path = entry.settings_file_path("ansible-navigator")
Expand Down

0 comments on commit 031938a

Please sign in to comment.