Skip to content

Commit 08e4b4b

Browse files
authored
Merge pull request #2 from jrwilk01/bug/fix_schema
Fix schema & add some docstrings
2 parents bd1ccef + 156a459 commit 08e4b4b

File tree

2 files changed

+75
-34
lines changed

2 files changed

+75
-34
lines changed

tofupy/schema.py

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ def __post_init__(self):
6060
self.schema_version = self.data.get("schema_version")
6161
self.provider_name = self.data.get("provider_name")
6262
self.values = self.data.get("values")
63+
self.sensitive_values = self.data.get("sensitive_values")
6364

6465

6566
@dataclass
@@ -146,12 +147,6 @@ class Change:
146147
def __post_init__(self):
147148
self.actions = self.data.get("actions", [])
148149

149-
before = self.data.get("before")
150-
if before is None:
151-
self.before = None
152-
else:
153-
self.before_root_module
154-
155150
self.before = self.data.get("before")
156151
self.after = self.data.get("after")
157152

tofupy/tofu.py

Lines changed: 74 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,23 @@ def raise_error(self) -> None:
2525

2626

2727
class Tofu:
28-
"""Tofu class to interact with Terraform."""
28+
"""A Python interface for interacting with OpenTofu (Terraform).
29+
30+
This class provides a high-level interface to interact with OpenTofu/Terraform
31+
commands, handling JSON output parsing and providing structured data objects.
32+
33+
Attributes:
34+
cwd (str | Path): Current working directory for OpenTofu operations.
35+
binary_path (str): Path to the OpenTofu/Terraform binary.
36+
log_level (str): Logging level for OpenTofu operations.
37+
env (Dict[str, str]): Environment variables to pass to OpenTofu.
38+
version (str): Version of OpenTofu/Terraform being used.
39+
platform (str): Platform identifier for the OpenTofu binary.
40+
41+
Raises:
42+
FileNotFoundError: If the specified OpenTofu/Terraform binary cannot be found.
43+
RuntimeError: If an incompatible version of OpenTofu/Terraform is detected.
44+
"""
2945

3046
cwd: str | Path
3147
"""Current working directory."""
@@ -43,17 +59,17 @@ def __init__(
4359
log_level: str = "ERROR",
4460
env: Dict[str, str] = {},
4561
):
46-
"""_summary_
62+
"""Initialize the Tofu interface.
4763
4864
Args:
49-
cwd (str | Path, optional): _description_. Defaults to os.getcwd().
50-
binary (str, optional): _description_. Defaults to "tofu".
51-
log_level (str, optional): _description_. Defaults to "ERROR".
52-
env (Dict[str, str], optional): _description_. Defaults to {}.
65+
cwd (str | Path, optional): Working directory for OpenTofu operations. Defaults to current directory.
66+
binary (str, optional): Name or path of the OpenTofu/Terraform binary. Defaults to "tofu".
67+
log_level (str, optional): Logging level for OpenTofu operations. Defaults to "ERROR".
68+
env (Dict[str, str], optional): Additional environment variables to pass to OpenTofu. Defaults to empty dict.
5369
5470
Raises:
55-
FileNotFoundError: _description_
56-
RuntimeError: _description_
71+
FileNotFoundError: If the specified binary cannot be found in PATH.
72+
RuntimeError: If an incompatible version of OpenTofu/Terraform is detected.
5773
"""
5874
self.cwd = str(cwd)
5975
self.log_level = log_level
@@ -82,14 +98,17 @@ def _run(
8298
args: List[str],
8399
raise_on_error: bool = True,
84100
) -> CommandResults:
85-
"""_summary_
101+
"""Execute an OpenTofu command and capture its output.
86102
87103
Args:
88-
args (List[str]): _description_
89-
raise_on_error (bool, optional): _description_. Defaults to True.
104+
args (List[str]): Command arguments to pass to OpenTofu.
105+
raise_on_error (bool, optional): Whether to raise an exception on command failure. Defaults to True.
90106
91107
Returns:
92-
CommandResults: _description_
108+
CommandResults: Object containing command execution results.
109+
110+
Raises:
111+
RuntimeError: If the command fails and raise_on_error is True.
93112
"""
94113
args = [self.binary_path] + [str(x) for x in args]
95114

@@ -123,13 +142,13 @@ def _run_stream(
123142
self,
124143
args: List[str],
125144
) -> Generator[Dict[str, Any], None, None]:
126-
"""_summary_
145+
"""Execute an OpenTofu command and stream its JSON output.
127146
128147
Args:
129-
args (List[str]): _description_
148+
args (List[str]): Command arguments to pass to OpenTofu.
130149
131150
Yields:
132-
Generator[str, None, None]: _description_
151+
Generator[Dict[str, Any], None, None]: JSON events from the command output.
133152
"""
134153
args = [self.binary_path] + [str(x) for x in args]
135154

@@ -164,15 +183,15 @@ def init(
164183
backend_conf: Path | None = None,
165184
extra_args: List[str] = [],
166185
) -> bool:
167-
"""_summary_
186+
"""Initialize a new OpenTofu working directory.
168187
169188
Args:
170-
disable_backends (bool, optional): _description_. Defaults to False.
171-
backend_conf (Path | None, optional): _description_. Defaults to None.
172-
extra_args (List[str], optional): _description_. Defaults to [].
189+
disable_backends (bool, optional): Whether to disable backend initialization. Defaults to False.
190+
backend_conf (Path | None, optional): Path to backend configuration file. Defaults to None.
191+
extra_args (List[str], optional): Additional arguments to pass to init command. Defaults to empty list.
173192
174193
Returns:
175-
bool: _description_
194+
bool: True if initialization was successful, False otherwise.
176195
"""
177196
args = ["init", "-json"] + extra_args
178197
if disable_backends:
@@ -184,10 +203,10 @@ def init(
184203
return res.returncode == 0
185204

186205
def validate(self) -> Validate:
187-
"""_summary_
206+
"""Validate the current OpenTofu configuration.
188207
189208
Returns:
190-
Validate: _description_
209+
Validate: Object containing validation results and diagnostics.
191210
"""
192211
res = self._run(["validate", "-json"], raise_on_error=False)
193212
return Validate(res.json())
@@ -199,16 +218,16 @@ def plan(
199218
event_handlers: Dict[str, Callable[[Dict[str, Any]], bool]] = {},
200219
extra_args: List[str] = [],
201220
) -> Tuple[PlanLog, Plan | None]:
202-
"""_summary_
221+
"""Generate an execution plan for the current configuration.
203222
204223
Args:
205-
variables (Dict[str, str], optional): _description_. Defaults to {}.
206-
plan_file (Path | None, optional): _description_. Defaults to None.
207-
event_handlers (Dict[str, Callable[[Dict[str, Any]], bool]], optional): _description_. Defaults to {}.
208-
extra_args (List[str], optional): _description_. Defaults to [].
224+
variables (Dict[str, str], optional): Variables to pass to the plan command. Defaults to empty dict.
225+
plan_file (Path | None, optional): Path to save the plan file. If None, uses a temporary file. Defaults to None.
226+
event_handlers (Dict[str, Callable[[Dict[str, Any]], bool]], optional): Event handlers for plan output. Defaults to empty dict.
227+
extra_args (List[str], optional): Additional arguments to pass to plan command. Defaults to empty list.
209228
210229
Returns:
211-
Tuple[PlanLog, Plan | None]: _description_
230+
Tuple[PlanLog, Plan | None]: Tuple containing the plan log and the parsed plan object (if available).
212231
"""
213232
try:
214233
temp_dir = None
@@ -249,6 +268,18 @@ def apply(
249268
event_handlers: Dict[str, Callable[[Dict[str, Any]], bool]] = {},
250269
extra_args: List[str] = [],
251270
) -> ApplyLog:
271+
"""Apply the current configuration or a saved plan.
272+
273+
Args:
274+
plan_file (Path | None, optional): Path to a saved plan file to apply. Defaults to None.
275+
variables (Dict[str, str], optional): Variables to pass to the apply command. Defaults to empty dict.
276+
destroy (bool, optional): Whether to destroy all resources. Defaults to False.
277+
event_handlers (Dict[str, Callable[[Dict[str, Any]], bool]], optional): Event handlers for apply output. Defaults to empty dict.
278+
extra_args (List[str], optional): Additional arguments to pass to apply command. Defaults to empty list.
279+
280+
Returns:
281+
ApplyLog: Object containing the apply operation results.
282+
"""
252283
args = ["apply", "-auto-approve", "-json"] + extra_args
253284
if plan_file:
254285
args += [str(plan_file)]
@@ -270,6 +301,11 @@ def apply(
270301
return ApplyLog(output)
271302

272303
def state(self) -> State:
304+
"""Retrieve the current state of the OpenTofu configuration.
305+
306+
Returns:
307+
State: Object containing the current state information.
308+
"""
273309
pull_res = self._run(["state", "pull"])
274310
state_pull = pull_res.json()
275311

@@ -285,9 +321,19 @@ def state(self) -> State:
285321
)
286322

287323
def destroy(self) -> ApplyLog:
324+
"""Destroy all resources managed by the current configuration.
325+
326+
Returns:
327+
ApplyLog: Object containing the destroy operation results.
328+
"""
288329
return self.apply(destroy=True)
289330

290331
def output(self) -> Dict[str, Output]:
332+
"""Retrieve the outputs from the current configuration.
333+
334+
Returns:
335+
Dict[str, Output]: Dictionary mapping output names to their values.
336+
"""
291337
res = self._run(["output", "-json"])
292338
ret = {}
293339
for key, value in res.json().items():

0 commit comments

Comments
 (0)