Skip to content

Commit

Permalink
Merge branch 'release/0.0.2'
Browse files Browse the repository at this point in the history
  • Loading branch information
thelicato committed Jan 17, 2023
2 parents 4a1fb9d + a78132d commit b1e013d
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 12 deletions.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "ts2py"
version = "0.0.1"
version = "0.0.2"
description = "Python-Interoperability for Typescript-Interfaces"

license = "Apache-2.0"
Expand Down
4 changes: 2 additions & 2 deletions ts2py/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
__title__ = "ts2py"
__version__ = "0.0.1"
__description__ = "Python-Interoperability for Typescript-Interfaces"
__version__ = "0.0.2"
__description__ = "Python-Interoperability for Typescript-Interfaces"
13 changes: 8 additions & 5 deletions ts2py/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
"""

import os
from typing import List, Tuple, Any
from typing import List, Tuple, Optional, Any
import typer
from DHParser import (
compile_source,
Expand Down Expand Up @@ -76,13 +76,16 @@ def process_file(source: str, target: str) -> None:
returned in the terminal output.
"""
if os.path.isfile(target):
Logger().info(f"Target file '{target}' already exists, deleting it...")
os.remove(target)
result, errors = compile_src(source)
if not has_errors(errors, FATAL):
with open(target, "w", encoding="utf-8") as results_file:
results_file.write(serialize_result(result))
if errors:
Logger().error("\n".join(canonical_error_strings(errors)))
else:
Logger().success(f"Conversion for file '{source}' completed succesfully")


@app.command()
Expand All @@ -100,10 +103,10 @@ def convert(
False, "--verbose", "-v", help="Enable verbose output"
),
peps: List[types.args.PepArg] = typer.Option(
["655"], "--peps", "-p", help="Assume Python-PEPs, e.g. 655"
["655"], "--pep", "-p", help="Assume Python-PEPs, e.g. 655"
),
decorator: str = typer.Option(
"", "--decorator", "-d", help="Add the given decorator"
decorator: Optional[str] = typer.Option(
None, "--decorator", help="Add the given decorator"
),
debug: bool = typer.Option(False, "--debug", "-d", help="Enable debug mode"),
):
Expand Down Expand Up @@ -132,7 +135,7 @@ def convert(
if helper.use_type_union(compatibility):
set_preset_value("ts2py.UseTypeUnion", True, allow_new_key=True)
# Set decorator
if len(decorator) > 0:
if decorator:
set_preset_value("ts2py.ClassDecorator", decorator)
# Set debug mode
if debug:
Expand Down
30 changes: 26 additions & 4 deletions ts2py/syntax/compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,31 @@ def source_hash(source_text: str) -> str:
return " ".join([md5(source_text), script_hash])


DEFAULT_IMPORTS = """
from typing import TypedDict, GenericTypedDict, NotRequired, Literal, Union, Optional, Any, Generic, TypeVar, Callable, Coroutine, List, Tuple, Dict
"""
TYPING_TYPES = [
"NotRequired",
"Literal",
"Union",
"Optional",
"Any",
"Generic",
"TypeVar",
"Callable",
"Coroutine",
"List",
"Tuple",
"Dict",
]


def get_typing_imports(python_code: Any):
initial_import_line = "from typing import"
typing_types_to_add = ["TypedDict"]
for typing_type in TYPING_TYPES:
typing_match = re.search(rf"\b({typing_type})\b", python_code)
if typing_match:
typing_types_to_add.append(typing_type)
typing_types_str = ", ".join(typing_types_to_add)
return f"{initial_import_line} {typing_types_str}"


def to_typename(varname: str) -> str:
Expand Down Expand Up @@ -152,7 +174,7 @@ def prepare(self, root: Node) -> None:
def finalize(self, python_code: Any) -> Any:
code_blocks = []
if self.tree.name == "document":
code_blocks.append(DEFAULT_IMPORTS)
code_blocks.append(get_typing_imports(python_code))
code_blocks.append(python_code)
cooked = "\n\n".join(code_blocks)
cooked = re.sub(" +(?=\n)", "", cooked)
Expand Down

0 comments on commit b1e013d

Please sign in to comment.