-
-
Notifications
You must be signed in to change notification settings - Fork 541
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
feat: New Python-based terraform_fmt
hook to better support Windows
#652
Open
ericfrederich
wants to merge
7
commits into
antonbabenko:master
Choose a base branch
from
ericfrederich:windows-support
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
18291bd
feat: new terraform_fmt_v2 with better Windows support
ericfrederich 9409f77
Merge remote-tracking branch 'upstream/master' into windows-support
MaxymVlasov ef844ce
Merge remote-tracking branch 'upstream/master' into windows-support
MaxymVlasov 806a87a
Add linters andd apply part which not requiers tests
MaxymVlasov 3f3fdd9
Apply suggestions from code review
MaxymVlasov a37971b
Apply suggestions from code review
MaxymVlasov 85269df
fix mypy andy pylint issues
ericfrederich File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1,4 @@ | ||
tests/results/* | ||
__pycache__/ | ||
*.py[cod] | ||
node_modules/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +0,0 @@ | ||
print( | ||
'`terraform_docs_replace` hook is DEPRECATED.' | ||
'For migration instructions see https://github.com/antonbabenko/pre-commit-terraform/issues/248#issuecomment-1290829226' | ||
) | ||
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,108 @@ | ||
""" | ||
Here located common functions for hooks. | ||
|
||
It not executed directly, but imported by other hooks. | ||
""" | ||
from __future__ import annotations | ||
|
||
import argparse | ||
import logging | ||
import os | ||
from collections.abc import Sequence | ||
|
||
logger = logging.getLogger(__name__) | ||
|
||
|
||
def setup_logging() -> None: | ||
""" | ||
Set up the logging configuration based on the value of the 'PCT_LOG' environment variable. | ||
|
||
The 'PCT_LOG' environment variable determines the logging level to be used. | ||
The available levels are: | ||
- 'error': Only log error messages. | ||
- 'warn' or 'warning': Log warning messages and above. | ||
- 'info': Log informational messages and above. | ||
- 'debug': Log debug messages and above. | ||
|
||
If the 'PCT_LOG' environment variable is not set or has an invalid value, | ||
the default logging level is 'warning'. | ||
|
||
Returns: | ||
None | ||
""" | ||
log_level = { | ||
'error': logging.ERROR, | ||
'warn': logging.WARNING, | ||
'warning': logging.WARNING, | ||
'info': logging.INFO, | ||
'debug': logging.DEBUG, | ||
}[os.environ.get('PCT_LOG', 'warning').lower()] | ||
|
||
logging.basicConfig(level=log_level) | ||
|
||
|
||
def parse_env_vars(env_var_strs: list[str]) -> dict[str, str]: | ||
""" | ||
Expand environment variables definition into their values in '--args'. | ||
|
||
Args: | ||
env_var_strs (list[str]): A list of environment variable strings in the format "name=value". | ||
|
||
Returns: | ||
dict[str, str]: A dictionary mapping variable names to their corresponding values. | ||
""" | ||
ret = {} | ||
for env_var_str in env_var_strs: | ||
name, env_var_value = env_var_str.split('=', 1) | ||
if env_var_value.startswith('"') and env_var_value.endswith('"'): | ||
env_var_value = env_var_value[1:-1] | ||
ret[name] = env_var_value | ||
return ret | ||
|
||
|
||
def parse_cmdline( | ||
argv: Sequence[str] | None = None, | ||
) -> tuple[list[str], list[str], list[str], list[str], dict[str, str]]: | ||
""" | ||
Parse the command line arguments and return a tuple containing the parsed values. | ||
|
||
Args: | ||
argv (Sequence[str] | None): The command line arguments to parse. | ||
If None, the arguments from sys.argv will be used. | ||
|
||
Returns: | ||
tuple[list[str], list[str], list[str], list[str], dict[str, str]]: | ||
A tuple containing the parsed values: | ||
- args (list[str]): The parsed arguments. | ||
- hook_config (list[str]): The parsed hook configurations. | ||
- files (list[str]): The parsed files. | ||
- tf_init_args (list[str]): The parsed Terraform initialization arguments. | ||
- env_var_dict (dict[str, str]): The parsed environment variables as a dictionary. | ||
""" | ||
|
||
parser = argparse.ArgumentParser( | ||
add_help=False, # Allow the use of `-h` for compatibility with the Bash version of the hook | ||
) | ||
parser.add_argument('-a', '--args', action='append', help='Arguments') | ||
parser.add_argument('-h', '--hook-config', action='append', help='Hook Config') | ||
parser.add_argument('-i', '--init-args', '--tf-init-args', action='append', help='Init Args') | ||
parser.add_argument('-e', '--envs', '--env-vars', action='append', help='Environment Variables') | ||
parser.add_argument('FILES', nargs='*', help='Files') | ||
|
||
parsed_args = parser.parse_args(argv) | ||
|
||
args = parsed_args.args or [] | ||
hook_config = parsed_args.hook_config or [] | ||
files = parsed_args.FILES or [] | ||
tf_init_args = parsed_args.init_args or [] | ||
env_vars = parsed_args.envs or [] | ||
|
||
env_var_dict = parse_env_vars(env_vars) | ||
|
||
if hook_config: | ||
raise NotImplementedError('TODO: implement: hook_config') | ||
|
||
if tf_init_args: | ||
raise NotImplementedError('TODO: implement: tf_init_args') | ||
|
||
return args, hook_config, files, tf_init_args, env_var_dict |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
""" | ||
Pre-commit hook for terraform fmt. | ||
""" | ||
from __future__ import annotations | ||
|
||
import logging | ||
import os | ||
import shlex | ||
import sys | ||
from subprocess import PIPE | ||
from subprocess import run | ||
from typing import Sequence | ||
|
||
from .common import parse_cmdline | ||
from .common import setup_logging | ||
|
||
logger = logging.getLogger(__name__) | ||
|
||
|
||
def main(argv: Sequence[str] | None = None) -> int: | ||
""" | ||
Main entry point for terraform_fmt_py pre-commit hook. | ||
Parses args and calls `terraform fmt` on list of files provided by pre-commit. | ||
""" | ||
|
||
setup_logging() | ||
|
||
logger.debug(sys.version_info) | ||
|
||
args, _hook_config, files, _tf_init_args, env_vars = parse_cmdline(argv) | ||
|
||
if os.environ.get('PRE_COMMIT_COLOR') == 'never': | ||
args.append('-no-color') | ||
|
||
cmd = ['terraform', 'fmt', *args, *files] | ||
|
||
logger.info('calling %s', shlex.join(cmd)) | ||
logger.debug('env_vars: %r', env_vars) | ||
logger.debug('args: %r', args) | ||
|
||
completed_process = run( | ||
cmd, env={**os.environ, **env_vars}, | ||
text=True, stdout=PIPE, check=False, | ||
) | ||
|
||
if completed_process.stdout: | ||
print(completed_process.stdout) | ||
|
||
return completed_process.returncode | ||
|
||
|
||
if __name__ == '__main__': | ||
raise SystemExit(main()) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Let's start a PR scope thread here:
How much do we want to be implemented in this PR?
1.1. Current
common
functional "as is"1.2. Full
common
functional parity2.1. Just
terraform_fmt
2.2. All hooks fully which fully based on
common
functionalChoose one from 1. and 2.
The current state is 1.1. + 2.1.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
1.1
+2.1
(+ each hook to be re-implemented with Python in scope of a separate PR)ps: I don't get the difference between
1.1
and1.2
to be honest... 🤷🏻There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
1.2 Means that
https://github.com/ericfrederich/pre-commit-terraform/blob/18291bd1e3105046592d221426704c2418c34b7c/hooks/common.py#L55-L59
should be implemented too in this PR