Skip to content

Commit c02b8ef

Browse files
committed
change path constants from str to Path type
1 parent 208d420 commit c02b8ef

File tree

5 files changed

+31
-43
lines changed

5 files changed

+31
-43
lines changed

policy_sentry/command/initialize.py

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import logging
99
import os
1010
import shutil
11+
from pathlib import Path
1112

1213
import click
1314

@@ -96,7 +97,7 @@ def initialize(
9697
if not access_level_overrides_file:
9798
overrides_file = LOCAL_ACCESS_OVERRIDES_FILE
9899
else:
99-
overrides_file = access_level_overrides_file
100+
overrides_file = Path(access_level_overrides_file)
100101
# Create the config directory
101102
database_path = create_policy_sentry_config_directory()
102103

@@ -107,15 +108,15 @@ def initialize(
107108
# provided by AWS documentation
108109
file_list = [
109110
f
110-
for f in os.listdir(BUNDLED_DATA_DIRECTORY)
111-
if os.path.isfile(os.path.join(BUNDLED_DATA_DIRECTORY, f))
111+
for f in BUNDLED_DATA_DIRECTORY.iterdir()
112+
if (BUNDLED_DATA_DIRECTORY / f).is_file()
112113
]
113114

114115
for file in file_list:
115-
if file.endswith(".yml"):
116-
shutil.copy(os.path.join(BUNDLED_DATA_DIRECTORY, file), CONFIG_DIRECTORY)
116+
if file.suffix == ".yml":
117+
shutil.copy(BUNDLED_DATA_DIRECTORY / file, CONFIG_DIRECTORY)
117118
logger.debug("copying overrides file %s to %s", file, CONFIG_DIRECTORY)
118-
print("Database will be stored here: " + database_path)
119+
print(f"Database will be stored here: {database_path}")
119120

120121
if not build and not fetch:
121122
# copy from the bundled database location to the destination path
@@ -140,24 +141,21 @@ def initialize(
140141
logger.debug(", ".join(all_aws_service_prefixes))
141142

142143

143-
def create_policy_sentry_config_directory() -> str:
144+
def create_policy_sentry_config_directory() -> Path:
144145
"""
145146
Creates a config directory at $HOME/.policy_sentry/
146147
:return: the path of the database file
147148
"""
148149
print("Creating the database...")
149150
logger.debug(f"We will store the new database here: {DATASTORE_FILE_PATH}")
150151
# If the database file already exists, remove it
151-
if os.path.exists(LOCAL_DATASTORE_FILE_PATH):
152+
if LOCAL_DATASTORE_FILE_PATH.exists():
152153
logger.debug(
153154
f"The database at {DATASTORE_FILE_PATH} already exists. Removing and replacing it."
154155
)
155-
os.remove(LOCAL_DATASTORE_FILE_PATH)
156-
elif os.path.exists(CONFIG_DIRECTORY):
157-
pass
158-
# If the config directory does not exist
156+
LOCAL_DATASTORE_FILE_PATH.unlink()
159157
else:
160-
os.mkdir(CONFIG_DIRECTORY)
158+
CONFIG_DIRECTORY.mkdir(exist_ok=True)
161159
return LOCAL_DATASTORE_FILE_PATH
162160

163161

policy_sentry/command/query.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66

77
import json
88
import logging
9-
import os
109
from typing import Any
1110

1211
import click
@@ -144,7 +143,7 @@ def query_action_table(
144143
) -> list[str] | dict[str, list[dict[str, Any]]]:
145144
"""Query the Action Table from the Policy Sentry database.
146145
Use this one when leveraging Policy Sentry as a library."""
147-
if os.path.exists(LOCAL_DATASTORE_FILE_PATH):
146+
if LOCAL_DATASTORE_FILE_PATH.exists():
148147
logger.info(
149148
f"Using the Local IAM definition: {LOCAL_DATASTORE_FILE_PATH}. To leverage the bundled definition instead, remove the folder $HOME/.policy_sentry/"
150149
)
@@ -267,7 +266,7 @@ def query_arn_table(
267266
name: str, service: str, list_arn_types: bool, fmt: str
268267
) -> list[str] | dict[str, str]:
269268
"""Query the ARN Table from the Policy Sentry database. Use this one when leveraging Policy Sentry as a library."""
270-
if os.path.exists(LOCAL_DATASTORE_FILE_PATH):
269+
if LOCAL_DATASTORE_FILE_PATH.exists():
271270
logger.info(
272271
f"Using the Local IAM definition: {LOCAL_DATASTORE_FILE_PATH}. To leverage the bundled definition instead, remove the folder $HOME/.policy_sentry/"
273272
)
@@ -329,7 +328,7 @@ def query_condition_table(
329328
) -> list[str] | dict[str, str]:
330329
"""Query the condition table from the Policy Sentry database.
331330
Use this one when leveraging Policy Sentry as a library."""
332-
if os.path.exists(LOCAL_DATASTORE_FILE_PATH):
331+
if LOCAL_DATASTORE_FILE_PATH.exists():
333332
logger.info(
334333
f"Using the Local IAM definition: {LOCAL_DATASTORE_FILE_PATH}. To leverage the bundled definition instead, remove the folder $HOME/.policy_sentry/"
335334
)
@@ -373,7 +372,7 @@ def service_table(fmt: str, verbose: str | None) -> None:
373372
def query_service_table(fmt: str = "json") -> list[dict[str, str]]:
374373
"""Query the service table from the Policy Sentry database.
375374
Use this one when leveraging Policy Sentry as a library."""
376-
if os.path.exists(LOCAL_DATASTORE_FILE_PATH):
375+
if LOCAL_DATASTORE_FILE_PATH.exists():
377376
logger.info(
378377
f"Using the Local IAM definition: {LOCAL_DATASTORE_FILE_PATH}. To leverage the bundled definition instead, remove the folder $HOME/.policy_sentry/"
379378
)

policy_sentry/shared/awsdocs.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ def get_action_access_level_overrides_from_yml(
7777
return None
7878

7979

80-
def update_html_docs_directory(html_docs_destination: str) -> None:
80+
def update_html_docs_directory(html_docs_destination: Path) -> None:
8181
"""
8282
Updates the HTML docs from remote location to either:
8383
(1) local directory (i.e., this repository, or
@@ -131,9 +131,7 @@ def update_html_docs_directory(html_docs_destination: str) -> None:
131131
logger.warning(a_e)
132132
logger.warning(script)
133133

134-
with open(
135-
os.path.join(html_docs_destination, page), "w", encoding="utf-8"
136-
) as file:
134+
with open(html_docs_destination / page, "w", encoding="utf-8") as file:
137135
# file.write(str(soup.html))
138136
file.write(str(soup.prettify()))
139137
file.close()
@@ -158,7 +156,7 @@ def sanitize_service_name(action: str) -> str:
158156

159157

160158
def create_database(
161-
destination_directory: str, access_level_overrides_file: str
159+
destination_directory: str | Path, access_level_overrides_file: Path
162160
) -> None:
163161
"""
164162
Create the JSON Data source that holds the IAM data.

policy_sentry/shared/constants.py

Lines changed: 12 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -9,26 +9,24 @@
99
logger = logging.getLogger()
1010

1111
# General Folders
12-
HOME = str(Path.home())
13-
CONFIG_DIRECTORY = os.path.join(HOME, ".policy_sentry")
12+
HOME = Path.home()
13+
CONFIG_DIRECTORY = HOME / ".policy_sentry"
1414

1515
# HTML Docs
16-
BUNDLED_HTML_DIRECTORY_PATH = os.path.join(
17-
str(Path(os.path.dirname(__file__))), "data", "docs"
18-
)
19-
BUNDLED_DATA_DIRECTORY = os.path.join(str(Path(os.path.dirname(__file__))), "data")
16+
BUNDLED_HTML_DIRECTORY_PATH = Path(__file__).parent / "data/docs"
17+
BUNDLED_DATA_DIRECTORY = Path(__file__).parent / "data"
2018

21-
LOCAL_HTML_DIRECTORY_PATH = os.path.join(CONFIG_DIRECTORY, "data", "docs")
19+
LOCAL_HTML_DIRECTORY_PATH = CONFIG_DIRECTORY / "data/docs"
2220

2321
BASE_DOCUMENTATION_URL = "https://docs.aws.amazon.com/service-authorization/latest/reference/reference_policies_actions-resources-contextkeys.html"
2422
# BASE_DOCUMENTATION_URL = "https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_actions-resources-contextkeys.html"
2523

2624
# Data json file
2725
# On initialization, load the IAM data
28-
BUNDLED_DATASTORE_FILE_PATH = str(Path(__file__).parent / "data/iam-definition.json")
29-
LOCAL_DATASTORE_FILE_PATH = str(Path(CONFIG_DIRECTORY) / "iam-definition.json")
26+
BUNDLED_DATASTORE_FILE_PATH = Path(__file__).parent / "data/iam-definition.json"
27+
LOCAL_DATASTORE_FILE_PATH = CONFIG_DIRECTORY / "iam-definition.json"
3028
# Check for the existence of the local datastore first.
31-
if os.path.exists(LOCAL_DATASTORE_FILE_PATH):
29+
if LOCAL_DATASTORE_FILE_PATH.exists():
3230
# If it exists, leverage that datastore instead of the one bundled with the python package
3331
logger.info(
3432
f"Leveraging the local IAM definition at the path: {LOCAL_DATASTORE_FILE_PATH} "
@@ -43,18 +41,14 @@
4341
# Overrides
4442
if "CUSTOM_ACCESS_OVERRIDES_FILE" in os.environ:
4543
CUSTOM_ACCESS_OVERRIDES_FILE = os.environ["CUSTOM_ACCESS_OVERRIDES_FILE"]
46-
BUNDLED_ACCESS_OVERRIDES_FILE = os.path.join(
47-
os.path.abspath(os.path.dirname(__file__)), CUSTOM_ACCESS_OVERRIDES_FILE
48-
)
44+
BUNDLED_ACCESS_OVERRIDES_FILE = Path(__file__).parent / CUSTOM_ACCESS_OVERRIDES_FILE
4945

5046
else:
51-
BUNDLED_ACCESS_OVERRIDES_FILE = os.path.join(
52-
os.path.abspath(os.path.dirname(__file__)), "data", "access-level-overrides.yml"
47+
BUNDLED_ACCESS_OVERRIDES_FILE = (
48+
Path(__file__).parent / "data/access-level-overrides.yml"
5349
)
5450

55-
LOCAL_ACCESS_OVERRIDES_FILE = os.path.join(
56-
CONFIG_DIRECTORY, "access-level-overrides.yml"
57-
)
51+
LOCAL_ACCESS_OVERRIDES_FILE = CONFIG_DIRECTORY / "access-level-overrides.yml"
5852

5953
# Policy constants
6054
# https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_version.html

policy_sentry/shared/iam_data.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
import functools
66
import gc
77
import logging
8-
from pathlib import Path
98
from typing import Any, cast
109

1110
import orjson
@@ -27,7 +26,7 @@ def load_iam_definition() -> dict[str, Any]:
2726
# https://github.com/msgpack/msgpack-python?tab=readme-ov-file#performance-tips
2827
gc.disable()
2928

30-
data: dict[str, Any] = orjson.loads(Path(iam_definition_path).read_bytes())
29+
data: dict[str, Any] = orjson.loads(iam_definition_path.read_bytes())
3130

3231
if gc_enabled:
3332
gc.enable()

0 commit comments

Comments
 (0)