Conghao97's picture tcftrees's picture
ProgramGen release
d086025
Raw History Blame Contribute Delete
20.4 kB
diff --git a/loafang/__init__.py b/loafang/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..1039d162b576cafc021c2abe9a4e5bd494df5eeb
--- /dev/null
+++ b/loafang/__init__.py
@@ -0,0 +1,4 @@
+from .methods import Methods # noqa: F401
+from .methods import MethodsError # noqa: F401
+from .parser import parse # noqa: F401
+from .query import QueryBuilder # noqa: F401
diff --git a/loafang/__main__.py b/loafang/__main__.py
new file mode 100644
index 0000000000000000000000000000000000000000..51d8b48cf6198e7ab88648ff4c61458030a63f66
--- /dev/null
+++ b/loafang/__main__.py
@@ -0,0 +1,4 @@
+from .main import main
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/loafang/_const.py b/loafang/_const.py
new file mode 100644
index 0000000000000000000000000000000000000000..fef40208d0bddabba131de8f480e63a308addfe1
--- /dev/null
+++ b/loafang/_const.py
@@ -0,0 +1,29 @@
+METHODS = [
+ "GET",
+ "POST",
+ "PUT",
+ "PATCH",
+ "DELETE"
+]
+
+PROPERTY_KEYS = [
+ "pe"
+]
+
+ERROR_CODES = {
+ 600: "Something went wrong.",
+ 601: "The header cannot be empty.",
+ 602: "Unrecognized method.",
+ 603: "Unrecognized property key.",
+ 604: "Missing ID.",
+ 605: "Invalid data type for the argument in the query.",
+ 606: "Invalid Data Type for the content container for the query.",
+ 607: "Parser does not exists for the given request method.",
+ 608: "Two Execution Blocks cannot have the same ID's.",
+ 609: "The after key must be a string",
+ 610: "The Execution block with the given ID does not exists",
+ 611: "Methods is not implemented",
+ 612: "Execution block with pe property key cannot have an after key",
+ 613: "Two queries in a block cannot have the same alias",
+ 614: "Parser Error"
+}
diff --git a/loafang/_dataclasses.py b/loafang/_dataclasses.py
new file mode 100644
index 0000000000000000000000000000000000000000..419a6e3afa14566a2146e45a4d3dddc4926abd8a
--- /dev/null
+++ b/loafang/_dataclasses.py
@@ -0,0 +1,49 @@
+from argparse import Namespace
+from dataclasses import dataclass
+from dataclasses import field
+from typing import Any
+from typing import Dict
+from typing import List
+from typing import Optional
+from typing import Union
+
+
+@dataclass
+class Header:
+ method: str
+ id: str
+ property_key: Optional[str] = None
+
+
+@dataclass
+class ListQuery:
+ # used when the method is get, delete
+ args: Namespace
+ query: str # the original query that was sent
+ contents: List[str] = field(default_factory=list)
+ alias: Optional[str] = None
+
+
+@dataclass
+class DictQuery:
+ # used when the values passed for methods are key value pairs
+ args: Namespace
+ query: str
+ contents: Dict[str, Any] = field(default_factory=dict)
+ alias: Optional[str] = None
+
+
+@dataclass
+class ExecutionBlock:
+ header: Header
+ after: Optional[str] = None
+ query: List[Union[ListQuery, DictQuery]] = field(default_factory=list)
+
+
+@dataclass
+class ParserState:
+ ids: List[str] = field(default_factory=list)
+ # list of all the execution blocks
+ ebs: List[ExecutionBlock] = field(default_factory=list)
+ # list all the execution block that pe as their property key
+ pes: List[ExecutionBlock] = field(default_factory=list)
diff --git a/loafang/_parsers.py b/loafang/_parsers.py
new file mode 100644
index 0000000000000000000000000000000000000000..6032c6c5bc46f5a7ce3d4f1fa2df9224121ded92
--- /dev/null
+++ b/loafang/_parsers.py
@@ -0,0 +1,178 @@
+from argparse import ArgumentError
+from typing import Any
+from typing import Dict
+from typing import List
+from typing import Optional
+from typing import Tuple
+from typing import Union
+
+from ._const import METHODS
+from ._const import PROPERTY_KEYS
+from ._dataclasses import DictQuery
+from ._dataclasses import ExecutionBlock
+from ._dataclasses import Header
+from ._dataclasses import ListQuery
+from .query import QueryBuilder
+from .query import QueryBuilderError
+from .utils import err_msg
+
+
+blockType = Dict[str, Dict[str, Union[List[str], Dict[str, Any], str]]]
+queryType = Dict[str, Union[List[str], Dict[str, Any], str]]
+queryContentType = Union[ListQuery, DictQuery]
+
+
+class HeaderParser:
+ """
+ This is whats called as the header of an 'execution block`
+ GET:get-user:pe
+
+ Here,
+ GET -> methods that the user likes to perform
+ get-user -> An unique ID / name that represents the block
+ pe -> An optional key that determines the property of an execution block.
+
+ """
+
+ def __init__(self, header: str) -> None:
+ self.header = header
+
+ def parse(self) -> Union[Tuple[Header, None, None], Tuple[None, int, str]]:
+ parts = [part for part in self.header.split(":") if part]
+ rv = Header("", "", "")
+
+ if len(parts) == 0:
+ return (None, 601, err_msg(601))
+
+ if len(parts) == 1:
+ return (None, 604, err_msg(604))
+
+ if len(parts) > 3:
+ return (None, 600, "The header cannot be more than 3 parts.")
+
+ if len(parts) >= 2:
+ if parts[0] in METHODS:
+ rv.method = parts[0]
+ rv.id = parts[1]
+ rv.property_key = None
+
+ else:
+ return (None, 602, f"The method {parts[0]!r} does not exists.")
+ if len(parts) == 3:
+ if parts[2]:
+ if parts[2] in PROPERTY_KEYS:
+ rv.property_key = parts[2]
+
+ else:
+ return (None, 603, f"The property key {parts[2]!r} does not exists.")
+
+ return (rv, None, None)
+
+
+class QueryParser:
+
+ def __init__(self, query: queryType, method: str, parser: QueryBuilder) -> None:
+ self.query = query
+ self.method = method
+ self.parser = parser
+
+ def parse(self) -> Union[Tuple[queryContentType, None, None], Tuple[None, int, str]]:
+
+ args_str = list(self.query)[0]
+ contents = list(self.query.values())[0]
+
+ if self.method in ["GET", "DELETE"]:
+ if not isinstance(contents, list):
+ return (None, 606, "The content container type must be a list for GET and DELETE")
+
+ else:
+ if not isinstance(contents, dict):
+ return (None, 606, "The content container type must be dict for POST, PUT, and PATCH")
+
+ # rpartition places the alias string on the right
+ # if there are no aliases given then the arg string is placed on the right
+ args_str, _, alias = args_str.rpartition("|")
+
+ if not args_str and alias:
+ args_str = alias
+ alias = ""
+
+ try:
+ args, _ = self.parser._inner_parser.parse_known_args(
+ args_str.split())
+ except QueryBuilderError as e:
+ return (None, 614, e.msg)
+ except ArgumentError as e:
+ return (None, 614, e.message)
+
+ if self.method in ["GET", "DELETE"]:
+ if isinstance(contents, list):
+ return (ListQuery(args=args, contents=contents, query=args_str, alias=alias.strip()), None, None)
+
+ else:
+ if isinstance(contents, dict):
+ return (DictQuery(args=args, contents=contents, query=args_str, alias=alias.strip()), None, None)
+
+ return (None, 600, err_msg(600))
+
+
+class BlockParser:
+
+ """
+ Uses the other two parsers to parser the block
+ """
+
+ def __init__(self, block: blockType, methods_dict: Dict[str, Optional[QueryBuilder]]) -> None:
+ self.block = block
+ self.methods_dict = methods_dict
+ self.block_query_aliases: List[str] = []
+
+ def parse(self) -> Union[Tuple[ExecutionBlock, None, None], Tuple[None, int, str]]:
+ header, err, msg = HeaderParser(list(self.block.keys())[0]).parse()
+
+ if not header and err and msg:
+ return (None, err, msg)
+
+ queries = []
+ after: Optional[str] = None
+
+ if header:
+
+ for q, c in list(self.block.values())[0].items():
+
+ if q == "after":
+
+ if header.property_key != "pe":
+
+ if not isinstance(c, str):
+ return (None, 609, err_msg(609))
+
+ else:
+ after = c
+ continue
+ else:
+ return (None, 612, err_msg(612))
+
+ curr_parser = self.methods_dict[header.method]
+
+ if curr_parser:
+
+ query, err, msg = QueryParser(
+ {q: c}, header.method, curr_parser).parse()
+ if query:
+ queries.append(query)
+
+ if query.alias:
+ if query.alias in self.block_query_aliases:
+ return (None, 613, err_msg(613) + f" id:{header.id}; alias: {query.alias}")
+ else:
+ self.block_query_aliases.append(query.alias)
+
+ else:
+ if err and msg:
+ return (None, err, msg)
+
+ else:
+ return (None, 607, f"Parser does not exists for {header.method!r}")
+ return (ExecutionBlock(header=header, after=after, query=queries), None, None)
+ return (None, 600, err_msg(600))
diff --git a/loafang/main.py b/loafang/main.py
new file mode 100644
index 0000000000000000000000000000000000000000..9938e1a8722b82d25945554849c9bdfcca5512c6
--- /dev/null
+++ b/loafang/main.py
@@ -0,0 +1,12 @@
+import argparse # noqa: F401
+from typing import Optional
+from typing import Sequence
+
+
+def main(argv: Optional[Sequence[str]] = None) -> int:
+ print("Loafang: https://Adwaith-Rajesh.github.io/loafang")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/loafang/methods.py b/loafang/methods.py
new file mode 100644
index 0000000000000000000000000000000000000000..159d69e092c7c06a1c59413f9d0f8c186024d90e
--- /dev/null
+++ b/loafang/methods.py
@@ -0,0 +1,45 @@
+from argparse import Namespace
+from typing import Any
+from typing import Dict
+from typing import List
+from typing import Optional
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from .query import QueryBuilder
+
+
+class MethodsError(Exception):
+
+ def __init__(self, code: int = 614, msg: str = "Some error occurred") -> None:
+ self.code = code
+ self.msg = msg
+
+ def __str__(self) -> str:
+ return f"{self.code} {self.msg}"
+
+
+# this class is what is used to generate the output for the each query in the execution block
+class Methods:
+
+ def __init__(self) -> None:
+ self.get_query_parser: Optional[QueryBuilder] = None
+ self.post_query_parser: Optional[QueryBuilder] = None
+ self.put_query_parser: Optional[QueryBuilder] = None
+ self.delete_query_parser: Optional[QueryBuilder] = None
+ self.patch_query_parser: Optional[QueryBuilder] = None
+
+ def get(self, args: Namespace, contents: List[str]) -> Any:
+ raise NotImplementedError("GET is not implemented")
+
+ def post(self, args: Namespace, contents: Dict[str, Any]) -> Any:
+ raise NotImplementedError("POST is not implemented")
+
+ def put(self, args: Namespace, contents: Dict[str, Any]) -> Any:
+ raise NotImplementedError("PUT is not implemented")
+
+ def delete(self, args: Namespace, contents: List[str]) -> Any:
+ raise NotImplementedError("DELETE is not implemented")
+
+ def patch(self, args: Namespace, contents: Dict[str, Any]) -> Any:
+ raise NotImplementedError("PATCH is not implemented")
diff --git a/loafang/parser.py b/loafang/parser.py
new file mode 100644
index 0000000000000000000000000000000000000000..06f234e9cf641f664f6285e8e160b9dc50100637
--- /dev/null
+++ b/loafang/parser.py
@@ -0,0 +1,109 @@
+from typing import Any
+from typing import Dict
+from typing import List
+from typing import Optional
+from typing import Tuple
+from typing import Union
+
+from ._const import METHODS
+from ._dataclasses import ExecutionBlock
+from ._dataclasses import ParserState
+from ._parsers import BlockParser
+from .methods import Methods
+from .methods import MethodsError
+
+
+dataType = Dict[str, Dict[str, Union[List[str], Dict[str, Any], str]]]
+returnDataType = Dict[str, Dict[str, Any]] # I'm not sure about this
+parserReturnType = Union[Tuple[returnDataType,
+ None, None], Tuple[None, int, str]]
+
+
+def verify_data_type(data: object) -> dataType:
+ # I'll implement this later
+ if isinstance(data, dict):
+ return data
+
+ return dict()
+
+
+def block_executor(ebs: List[ExecutionBlock], pes: List[ExecutionBlock], methods: Methods) -> parserReturnType:
+
+ pes_ids = {i.header.id: i for i in pes}
+ req_methods_dict = {i: getattr(methods, i.lower()) for i in METHODS}
+ block_output_err: Optional[Tuple[None, int, str]] = None
+
+ def block_output(block: ExecutionBlock) -> Any:
+ nonlocal block_output_err
+
+ q_data = {}
+
+ for q in block.query:
+ try:
+ q_data[q.alias if q.alias else q.query] = req_methods_dict[block.header.method](
+ q.args, q.contents)
+ except NotImplementedError:
+ block_output_err = (
+ None, 611, f"{block.header.method!r} is not implemented")
+ return None
+ except MethodsError as e:
+ block_output_err = (
+ None, e.code, e.msg
+ )
+ return None
+
+ if block.after:
+ q_data["after"] = block_output(pes_ids[block.after])
+
+ return q_data
+
+ temp_data = {}
+
+ for eb in ebs:
+ if eb.after:
+ if eb.after not in pes_ids:
+ return (None, 610,
+ f"The 'after' execution block {eb.after!r} does not exists for the block {eb.header.id!r}")
+
+ val = block_output(eb)
+
+ if val:
+ temp_data[eb.header.id] = val
+
+ else:
+ break
+
+ return (temp_data, None, None) if not block_output_err else block_output_err
+
+
+def parse(methods: Methods, data: object) -> parserReturnType:
+
+ curr_state = ParserState()
+
+ methods_dict = {i: getattr(
+ methods, f"{i.lower()}_query_parser", None) for i in METHODS}
+
+ data = verify_data_type(data)
+
+ if data:
+ for k, v in data.items():
+
+ eb, err, msg = BlockParser({k: v}, methods_dict).parse()
+
+ if eb:
+ if eb.header.id in curr_state.ids:
+ return (None, 607, "Two execution blocks cannot have the same ID")
+ else:
+ curr_state.ids.append(eb.header.id)
+
+ if eb.header.property_key == "pe":
+ curr_state.pes.append(eb)
+ else:
+ curr_state.ebs.append(eb)
+ else:
+ if err and msg:
+ return (None, err, msg)
+
+ return block_executor(ebs=curr_state.ebs, pes=curr_state.pes, methods=methods)
+
+ return (None, 600, "Invalid Data")
diff --git a/loafang/query.py b/loafang/query.py
new file mode 100644
index 0000000000000000000000000000000000000000..cf4a13776648f4bffcecf5dfce319387791332c9
--- /dev/null
+++ b/loafang/query.py
@@ -0,0 +1,47 @@
+import argparse
+from typing import Any
+from typing import Callable
+from typing import NoReturn
+
+
+def gen_arg_name(name: str) -> str:
+ """
+ adds double dashes as prefix
+
+ name -> --name
+ -name -> --name
+ """
+
+ return "--" + "-".join(i for i in name.split('-') if i)
+
+
+class QueryBuilderError(Exception):
+
+ def __init__(self, msg: str) -> None:
+ self.msg = msg
+
+ def __str__(self) -> str:
+ return self.msg
+
+
+class CArgumentParser(argparse.ArgumentParser):
+
+ def error(self, message: str) -> NoReturn:
+ raise QueryBuilderError(message)
+
+
+class QueryBuilder:
+
+ # the reason why this class is not inheriting from the argparse.ArgumentParser,
+ # is so that the methods given to the user can be limited.
+
+ def __init__(self, head: str) -> None:
+
+ self._head = str(head) # to be used during the final parsing
+
+ self._inner_parser = CArgumentParser(add_help=False)
+ self._inner_parser.add_argument(str(head), type=str)
+
+ def add_argument(self, name: str, type: Callable[[str], Any], default: Any = None) -> None:
+ self._inner_parser.add_argument(
+ gen_arg_name(name), type=type, default=default)
diff --git a/loafang/utils.py b/loafang/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..f503bcc7c8b15649b8e780aed8107b3e199e5684
--- /dev/null
+++ b/loafang/utils.py
@@ -0,0 +1,5 @@
+from ._const import ERROR_CODES
+
+
+def err_msg(code: int) -> str:
+ return ERROR_CODES.get(code, "")
diff --git a/tests/__init__.py b/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tests/test_main.py b/tests/test_main.py
new file mode 100644
index 0000000000000000000000000000000000000000..e6ef5c801fa38477c3c2c841537830bb359d9a1a
--- /dev/null
+++ b/tests/test_main.py
@@ -0,0 +1,2 @@
+def test_main():
+ assert True
diff --git a/tests/test_parsers.py b/tests/test_parsers.py
new file mode 100644
index 0000000000000000000000000000000000000000..77e8409c43f46d83610fb84800146b78101fbdd2
--- /dev/null
+++ b/tests/test_parsers.py
@@ -0,0 +1,34 @@
+import pytest
+
+from loafang._dataclasses import Header
+from loafang._parsers import HeaderParser
+
+
+@pytest.mark.parametrize(
+ 'input,output',
+ (
+ ("GET:test-id:pe", (Header("GET", "test-id", "pe"), None, None)),
+ ("GET:test-id:", (Header("GET", "test-id", None), None, None)),
+ ("GET:test-id", (Header("GET", "test-id", None), None, None)),
+ ("POST:add-user:", (Header("POST", "add-user", None), None, None)),
+ ("DELETE:remove-mail", (Header("DELETE", "remove-mail", None), None, None)),
+ )
+)
+def test_header_parser_pass(input, output):
+ assert HeaderParser(input).parse() == output
+
+
+@pytest.mark.parametrize(
+ 'input,output',
+ (
+ ("get", (None, 604, "Missing ID.")),
+ ("GETS", (None, 604, "Missing ID.")),
+ ("GETS:test-id", (None, 602, "The method 'GETS' does not exists.")),
+ ("get:test-id", (None, 602, "The method 'get' does not exists.")),
+ ("", (None, 601, "The header cannot be empty.")),
+ ("GET:id:pe:test", (None, 600, "The header cannot be more than 3 parts.")),
+ ("GET:id:p4", (None, 603, "The property key 'p4' does not exists.")),
+ )
+)
+def test_header_parser_error(input, output):
+ assert HeaderParser(input).parse() == output
diff --git a/tests/test_query.py b/tests/test_query.py
new file mode 100644
index 0000000000000000000000000000000000000000..50a85b0a2e9133fed918cdf7c81a7e29d0d5e7a9
--- /dev/null
+++ b/tests/test_query.py
@@ -0,0 +1,18 @@
+import pytest
+
+from loafang.query import gen_arg_name
+
+
+@pytest.mark.parametrize(
+ 'input,output',
+ (
+ ("name", "--name"),
+ ("-name", "--name"),
+ ("---name", "--name"),
+ ("c42", "--c42"),
+ ("42", "--42"),
+
+ )
+)
+def test_gen_arg_name(input, output):
+ assert gen_arg_name(input) == output
diff --git a/tests/test_utils.py b/tests/test_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..8bd1ee0e5c4442105d8608e41ce15269b0785853
--- /dev/null
+++ b/tests/test_utils.py
@@ -0,0 +1,16 @@
+import pytest
+
+from loafang.utils import err_msg
+
+
+@pytest.mark.parametrize(
+ ("input", "output"),
+ (
+ (600, "Something went wrong."),
+ (605, "Invalid data type for the argument in the query."),
+ (612, "Execution block with pe property key cannot have an after key"),
+ (500, "")
+ )
+)
+def test_err_msg(input, output):
+ assert err_msg(input) == output