Skip to content

Commit

Permalink
working version
Browse files Browse the repository at this point in the history
  • Loading branch information
joseph-wortmann committed Dec 2, 2023
1 parent b9fded5 commit 423e0c1
Show file tree
Hide file tree
Showing 2 changed files with 83 additions and 15 deletions.
96 changes: 82 additions & 14 deletions analysis2template/__init__.py
Original file line number Diff line number Diff line change
@@ -1,32 +1,95 @@
from argh import arg, dispatch_command, wrap_errors, CommandError
from termcolor import colored
from boto3 import client
from boto3.compat import filter_python_deprecation_warnings
from logging import getLogger, ERROR
import json
from typing import TYPE_CHECKING
import re
from collections.abc import Iterable, Mapping
from logging import ERROR, getLogger
from numbers import Number
from string import Template
from time import sleep
from typing import TYPE_CHECKING, Any
from uuid import uuid4

from argh import CommandError, arg, dispatch_command, wrap_errors
from boto3 import client
from boto3.compat import filter_python_deprecation_warnings
from termcolor import colored

if TYPE_CHECKING:
from mypy_boto3_quicksight.type_defs import (
TemplateSourceEntityTypeDef,
TemplateSourceAnalysisTypeDef,
DataSetReferenceTypeDef,
TemplateSourceAnalysisTypeDef,
TemplateSourceEntityTypeDef,
)
else:
DataSetReferenceTypeDef = dict
TemplateSourceAnalysisTypeDef = dict
TemplateSourceEntityTypeDef = dict



filter_python_deprecation_warnings()

getLogger('boto3').setLevel(ERROR)
getLogger("boto3").setLevel(ERROR)

def main():
dispatch_command(analysis2template)
AWS_QUICKSIGHT_TEMPLATE = Template(
"""
resource "aws_quicksight_template" "example" {
template_id = "example_id"
name = "example_name"
version_description = "Initial version"
$definition
}
"""
)
CAMEL_TO_SNAKE = re.compile(r"(?<!^)(?=[A-Z])")


def escape_strings(s: str) -> str:
if "\n" in s:
return f"<<EOT\n{s}\nEOT"
if '"' in s:
s = s.replace('"', '\\"')
return f'"{s}"'


def to_terraform(key: str, value: Any) -> str:
if not value:
return ""
if isinstance(value, Mapping):
return (
f'{CAMEL_TO_SNAKE.sub("_", key).lower()} {{\n'
+ "\n".join([to_terraform(k, v) for k, v in value.items()])
+ "\n}"
)
if isinstance(value, Iterable) and not isinstance(value, str):
value = list(value)
if isinstance(value[0], Mapping):
return "\n".join([to_terraform(key, v) for v in value])
if isinstance(value[0], str):
return (
f'{CAMEL_TO_SNAKE.sub("_", key).lower()} = ['
+ ",".join([f"{escape_strings(v)}" for v in value])
+ "]"
)
if isinstance(value[0], bool):
return (
f'{CAMEL_TO_SNAKE.sub("_", key).lower()} = ['
+ ",".join(["true" if v else "false" for v in value])
+ "]"
)
if isinstance(value[0], Number):
return (
f'{CAMEL_TO_SNAKE.sub("_", key).lower()} = ['
+ ",".join([v for v in value])
+ "]"
)
raise ValueError(f"Unknown type {type(value[0])} for {key}")
if isinstance(value, str):
return f'{CAMEL_TO_SNAKE.sub("_", key).lower()} = {escape_strings(value)}'
if isinstance(value, bool):
return (
f'{CAMEL_TO_SNAKE.sub("_", key).lower()} = {"true" if value else "false"}'
)
if isinstance(value, Number):
return f'{CAMEL_TO_SNAKE.sub("_", key).lower()} = {value}'
raise ValueError(f"Unknown type {type(value)} for {key}")


@wrap_errors(processor=lambda err: colored(str(err), "red"))
Expand Down Expand Up @@ -99,7 +162,9 @@ def analysis2template(
template = quicksight.describe_template_definition(
AwsAccountId=aws_account_id, TemplateId=template_id
)
yield json.dumps(template, indent=2)
return AWS_QUICKSIGHT_TEMPLATE.substitute(
definition=to_terraform("Definition", template["Definition"])
)
finally:
quicksight.delete_template(
AwsAccountId=aws_account_id, TemplateId=template_id
Expand All @@ -108,3 +173,6 @@ def analysis2template(
except Exception as error:
raise CommandError(error)


def main():
dispatch_command(analysis2template)
2 changes: 1 addition & 1 deletion analysis2template/__main__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from . import main

if __name__ == "__main__":
main()
main()

0 comments on commit 423e0c1

Please sign in to comment.