Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhancement | Catch and handle HCL parsing errors #296

Merged
merged 6 commits into from
Feb 10, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions leverage/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""
Binbash Leverage Command-line tool.
"""

# pylint: disable=wrong-import-position

__version__ = "0.0.0"
Expand Down
1 change: 1 addition & 0 deletions leverage/_internals.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""
Definitions for internal use of the cli.
"""

from functools import wraps

import click
Expand Down
18 changes: 18 additions & 0 deletions leverage/_utils.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
"""
General use utilities.
"""

from pathlib import Path
from subprocess import run
from subprocess import PIPE

import hcl2
import lark
from click.exceptions import Exit
from configupdater import ConfigUpdater
from docker import DockerClient
Expand Down Expand Up @@ -112,6 +116,20 @@ def __init__(self, exit_code: int, error_description: str):
super(ExitError, self).__init__(exit_code)


def parse_tf_file(file: Path):
"""
Open and parse an HCL file.
In case of a parsing error, raise a user-friendly error.
"""
with open(file) as f:
try:
parsed = hcl2.load(f)
except lark.exceptions.UnexpectedInput:
raise ExitError(1, f"There is a parsing error with the {f.name} file. Please review it.")
else:
return parsed
Comment on lines +119 to +130
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Improve error handling in parse_tf_file.

The error handling can be enhanced to:

  1. Catch FileNotFoundError for missing files
  2. Include the original error message for better debugging
  3. Chain exceptions using raise ... from err

Apply this diff to improve error handling:

 def parse_tf_file(file: Path):
     """
     Open and parse an HCL file.
     In case of a parsing error, raise a user-friendly error.
     """
     with open(file) as f:
         try:
             parsed = hcl2.load(f)
-        except lark.exceptions.UnexpectedInput:
-            raise ExitError(1, f"There is a parsing error with the {f.name} file. Please review it.")
+        except FileNotFoundError as err:
+            raise ExitError(1, f"The file {f.name} does not exist.") from err
+        except lark.exceptions.UnexpectedInput as err:
+            raise ExitError(1, f"There is a parsing error with the {f.name} file. Please review it.\nError: {err}") from err
         else:
             return parsed

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 Ruff (0.8.2)

127-127: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)



class ContainerSession:
"""
Handle the start/stop cycle of a container.
Expand Down
1 change: 1 addition & 0 deletions leverage/conf.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""
Env variables loading utility.
"""

from pathlib import Path

from yaenv.core import Env
Expand Down
1 change: 1 addition & 0 deletions leverage/leverage.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""
Binbash Leverage Command-line tool.
"""

import click

from leverage import __version__
Expand Down
1 change: 1 addition & 0 deletions leverage/logger.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""
Logging utilities.
"""

import logging
from functools import wraps

Expand Down
11 changes: 4 additions & 7 deletions leverage/modules/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,12 @@
from pathlib import Path
from configparser import NoSectionError, NoOptionError

import hcl2
import boto3
from configupdater import ConfigUpdater
from botocore.exceptions import ClientError
from configupdater import ConfigUpdater

from leverage import logger
from leverage._utils import key_finder, ExitError, get_or_create_section
from leverage._utils import key_finder, ExitError, get_or_create_section, parse_tf_file


class SkipProfile(Exception):
Expand Down Expand Up @@ -66,8 +65,7 @@ def get_profiles(cli):
# these are files from the layer we are currently on
for name in ("config.tf", "locals.tf"):
try:
with open(name) as tf_file:
tf_config = hcl2.load(tf_file)
tf_config = parse_tf_file(Path(name))
except FileNotFoundError:
continue

Expand All @@ -76,8 +74,7 @@ def get_profiles(cli):
raw_profiles.update(set(key_finder(tf_config, "profile", "lookup")))

# the profile value from <layer>/config/backend.tfvars
with open(cli.paths.local_backend_tfvars) as backend_config_file:
backend_config = hcl2.load(backend_config_file)
backend_config = parse_tf_file(cli.paths.local_backend_tfvars)
tf_profile = backend_config["profile"]
Comment on lines +77 to 78
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add error handling for backend configuration parsing.

While the layer configuration files have error handling (try-except), the backend configuration parsing lacks similar protection. A malformed backend.tfvars could lead to unclear errors.

Consider wrapping the backend configuration parsing in a try-except block:

-    backend_config = parse_tf_file(cli.paths.local_backend_tfvars)
-    tf_profile = backend_config["profile"]
+    try:
+        backend_config = parse_tf_file(cli.paths.local_backend_tfvars)
+        tf_profile = backend_config["profile"]
+    except FileNotFoundError:
+        raise ExitError(40, f"Backend configuration file not found: {cli.paths.local_backend_tfvars}")
+    except KeyError:
+        raise ExitError(40, "Missing 'profile' in backend configuration")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
backend_config = parse_tf_file(cli.paths.local_backend_tfvars)
tf_profile = backend_config["profile"]
try:
backend_config = parse_tf_file(cli.paths.local_backend_tfvars)
tf_profile = backend_config["profile"]
except FileNotFoundError:
raise ExitError(40, f"Backend configuration file not found: {cli.paths.local_backend_tfvars}")
except KeyError:
raise ExitError(40, "Missing 'profile' in backend configuration")


return tf_profile, raw_profiles
Expand Down
1 change: 1 addition & 0 deletions leverage/modules/credentials.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""
Credentials managing module.
"""

import csv
import json
import re
Expand Down
1 change: 1 addition & 0 deletions leverage/modules/project.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""
Module for managing Leverage projects.
"""

import re
from pathlib import Path
from shutil import copy2
Expand Down
1 change: 1 addition & 0 deletions leverage/modules/run.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""
Tasks running module.
"""

import re

import click
Expand Down
8 changes: 4 additions & 4 deletions leverage/modules/terraform.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import re
from pathlib import Path
from typing import Sequence

import click
import hcl2
from click.exceptions import Exit

from leverage import logger
from leverage._internals import pass_container, pass_state
from leverage._utils import ExitError
from leverage._utils import ExitError, parse_tf_file
from leverage.container import TerraformContainer
from leverage.container import get_docker_client
from leverage.modules.utils import env_var_option, mount_option, auth_mfa, auth_sso
Expand Down Expand Up @@ -512,8 +512,8 @@ def _validate_layout(tf: TerraformContainer):
logger.error("[red]✘ FAILED[/red]\n")
valid_layout = False

backend_tfvars = tf.paths.account_config_dir / tf.paths.BACKEND_TF_VARS # TODO use paths.backend_tfvars instead?
backend_tfvars = hcl2.loads(backend_tfvars.read_text()) if backend_tfvars.exists() else {}
backend_tfvars = Path(tf.paths.local_backend_tfvars)
backend_tfvars = parse_tf_file(backend_tfvars) if backend_tfvars.exists() else {}

logger.info("Checking [bold]backend.tfvars[/bold]:\n")
names_prefix = f"{tf.project}-{account_name}"
Expand Down
1 change: 1 addition & 0 deletions leverage/path.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""
Utilities to obtain relevant files' and directories' locations
"""

import os
from pathlib import Path
from subprocess import CalledProcessError
Expand Down
1 change: 1 addition & 0 deletions leverage/tasks.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""
Task loading, Task object definition and task creation decorator.
"""

import sys
import importlib
from pathlib import Path
Expand Down
5 changes: 3 additions & 2 deletions tests/test_modules/test_auth.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from collections import namedtuple
from pathlib import PosixPath
from unittest import mock
from unittest.mock import Mock, MagicMock, PropertyMock

Expand Down Expand Up @@ -190,8 +191,8 @@ def test_get_layer_profile(muted_click_context):
"""

data_dict = {
"config.tf": FILE_CONFIG_TF,
"locals.tf": FILE_LOCALS_TF,
PosixPath("config.tf"): FILE_CONFIG_TF,
PosixPath("locals.tf"): FILE_LOCALS_TF,
"~/config/backend.tfvars": FILE_BACKEND_TFVARS,
"~/.aws/test/config": FILE_AWS_CONFIG,
"~/.aws/test/credentials": FILE_AWS_CREDENTIALS,
Expand Down
Loading