From be386d244be0b9b85ca4fbe49597985652f066db Mon Sep 17 00:00:00 2001 From: Daniel Biehl Date: Tue, 8 Oct 2024 23:06:52 +0200 Subject: [PATCH] feat(cli): new command line interface tool - Robot Framework REPL interpreter The new CLI command `repl` introduces an interactive Robot Framework interpreter. You can install it by running `pip install robotcode[repl]` and start it via the command line using `robotcode repl`. With this interactive interpreter, you can execute Robot Framework keywords without the need to run a full test suite. By default, all BuiltIn keywords are immediately accessible. To load a library, you can use the `import library` keyword, and for resources or variable files, you can use the corresponding built-in commands `import resource` and `import variables`. The outcome of any keyword execution, along with relevant log details, is displayed directly in the console. You can exit the interpreter using the `exit` keyword or by pressing `CTRL`+`D` on Unix-like systems and `CTRL+Z` followed by `ENTER` on Windows. At this stage, the implementation is fairly basic, but additional features for the REPL command are planned. This also serves as the first step toward an exciting new feature (spoiler alert!): Robot Framework Notebooks. --- .gitignore | 2 + .../robotcode/plugin/click_helper/aliases.py | 5 +- packages/repl/LICENSE.txt | 73 ++++++ packages/repl/README.md | 21 ++ packages/repl/pyproject.toml | 60 +++++ .../repl/src/robotcode/repl/Repl/__init__.py | 3 + packages/repl/src/robotcode/repl/Repl/repl.py | 18 ++ packages/repl/src/robotcode/repl/__init__.py | 0 .../repl/src/robotcode/repl/__version__.py | 1 + .../repl/src/robotcode/repl/cli/__init__.py | 3 + packages/repl/src/robotcode/repl/cli/repl.py | 169 ++++++++++++++ packages/repl/src/robotcode/repl/hooks.py | 12 + .../repl/src/robotcode/repl/interpreter.py | 210 ++++++++++++++++++ packages/repl/src/robotcode/repl/py.typed | 1 + .../repl/src/robotcode/repl/repl_listener.py | 27 +++ packages/runner/pyproject.toml | 2 +- .../robotcode/runner/cli/discover/discover.py | 5 +- .../runner/src/robotcode/runner/cli/robot.py | 21 +- pyproject.toml | 2 + robot.toml | 4 + src/robotcode/cli/commands/config.py | 4 +- 21 files changed, 628 insertions(+), 15 deletions(-) create mode 100644 packages/repl/LICENSE.txt create mode 100644 packages/repl/README.md create mode 100644 packages/repl/pyproject.toml create mode 100644 packages/repl/src/robotcode/repl/Repl/__init__.py create mode 100644 packages/repl/src/robotcode/repl/Repl/repl.py create mode 100644 packages/repl/src/robotcode/repl/__init__.py create mode 100644 packages/repl/src/robotcode/repl/__version__.py create mode 100644 packages/repl/src/robotcode/repl/cli/__init__.py create mode 100644 packages/repl/src/robotcode/repl/cli/repl.py create mode 100644 packages/repl/src/robotcode/repl/hooks.py create mode 100644 packages/repl/src/robotcode/repl/interpreter.py create mode 100644 packages/repl/src/robotcode/repl/py.typed create mode 100644 packages/repl/src/robotcode/repl/repl_listener.py diff --git a/.gitignore b/.gitignore index f3c3b3621..dc2928876 100644 --- a/.gitignore +++ b/.gitignore @@ -282,6 +282,8 @@ playground/ test-results results.html report.html +log.html +output.xml # pyenv .python-version diff --git a/packages/plugin/src/robotcode/plugin/click_helper/aliases.py b/packages/plugin/src/robotcode/plugin/click_helper/aliases.py index 88b8c2bbd..ef23c752e 100644 --- a/packages/plugin/src/robotcode/plugin/click_helper/aliases.py +++ b/packages/plugin/src/robotcode/plugin/click_helper/aliases.py @@ -40,10 +40,9 @@ def format_commands(self, ctx: click.Context, formatter: click.HelpFormatter) -> limit = formatter.width - 6 - max(len(cmd[0]) for cmd in commands) rows = [] - for subcommand, cmd in commands: + for subcommand, cmd in sorted(commands): help = cmd.get_short_help_str(limit) - rows.append((subcommand, help)) - rows.append(("", f"(Alias for `{cmd.name}` command)")) + rows.append((subcommand, f"{help} (Alias for `{cmd.name}` command)")) if rows: with formatter.section("Aliases"): formatter.write_dl(rows) diff --git a/packages/repl/LICENSE.txt b/packages/repl/LICENSE.txt new file mode 100644 index 000000000..137069b82 --- /dev/null +++ b/packages/repl/LICENSE.txt @@ -0,0 +1,73 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + + (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + + You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + +To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/packages/repl/README.md b/packages/repl/README.md new file mode 100644 index 000000000..5d826701e --- /dev/null +++ b/packages/repl/README.md @@ -0,0 +1,21 @@ +# robotcode-repl + +[![PyPI - Version](https://img.shields.io/pypi/v/robotcode-repl.svg)](https://pypi.org/project/robotcode-repl) +[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/robotcode-repl.svg)](https://pypi.org/project/robotcode-repl) +[![License](https://img.shields.io/github/license/robotcodedev/robotcode?style=flat&logo=apache)](https://github.com/robotcodedev/robotcode/blob/master/LICENSE.txt) + +----- + +## Introduction + +Some classes for [RobotCode](https://robotcode.io) plugin management + +## Installation + +```console +pip install robotcode-repl +``` + +## License + +`robotcode-repl` is distributed under the terms of the [Apache-2.0](https://spdx.org/licenses/Apache-2.0.html) license. diff --git a/packages/repl/pyproject.toml b/packages/repl/pyproject.toml new file mode 100644 index 000000000..2561f2265 --- /dev/null +++ b/packages/repl/pyproject.toml @@ -0,0 +1,60 @@ +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[project] +name = "robotcode-repl" +description = 'RobotCode REPL for Robot Framework' +readme = { "file" = "README.md", "content-type" = "text/markdown" } +requires-python = ">=3.8" +license = {text = "Apache-2.0"} +keywords = [] +authors = [{ name = "Daniel Biehl", email = "dbiehl@live.de" }] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Programming Language :: Python", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", + "Operating System :: OS Independent", + "Topic :: Utilities", + "Typing :: Typed", + "Framework :: Robot Framework", + "Framework :: Robot Framework :: Tool", +] +dynamic = ["version"] +dependencies = [ + "robotcode-jsonrpc2==0.92.0", + "robotcode-runner==0.92.0" +] + +[project.entry-points.robotcode] +repl = "robotcode.repl.hooks" + +[project.urls] +Homepage = "https://robotcode.io" +Donate = "https://opencollective.com/robotcode" +Documentation = "https://github.com/robotcodedev/robotcode#readme" +Changelog = "https://github.com/robotcodedev/robotcode/blob/main/CHANGELOG.md" +Issues = "https://github.com/robotcodedev/robotcode/issues" +Source = "https://github.com/robotcodedev/robotcode" + +[tool.hatch.version] +path = "src/robotcode/repl/__version__.py" + +[tool.hatch.build] +dev-mode-dirs = ["src"] + +[tool.hatch.build.targets.wheel] +only-include = ["src/robotcode"] +sources = ["src"] + +[tool.hatch.build.targets.sdist] +only-include = ["src"] + +[tool.hatch.envs.build] +detached = true +python = "38" diff --git a/packages/repl/src/robotcode/repl/Repl/__init__.py b/packages/repl/src/robotcode/repl/Repl/__init__.py new file mode 100644 index 000000000..1ba2a39d5 --- /dev/null +++ b/packages/repl/src/robotcode/repl/Repl/__init__.py @@ -0,0 +1,3 @@ +from .repl import Repl + +__all__ = ["Repl"] diff --git a/packages/repl/src/robotcode/repl/Repl/repl.py b/packages/repl/src/robotcode/repl/Repl/repl.py new file mode 100644 index 000000000..144737438 --- /dev/null +++ b/packages/repl/src/robotcode/repl/Repl/repl.py @@ -0,0 +1,18 @@ +import sys +from typing import List + +from ..__version__ import __version__ + + +class Repl: + ROBOT_LIBRARY_SCOPE = "GLOBAL" + ROBOT_LIBRARY_VERSION = __version__ + + def repl(self) -> None: + pass + + def exit(self, exit_code: int = 0) -> None: + sys.exit(exit_code) + + def keywords(self) -> List[str]: + return ["repl", "exit"] diff --git a/packages/repl/src/robotcode/repl/__init__.py b/packages/repl/src/robotcode/repl/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/packages/repl/src/robotcode/repl/__version__.py b/packages/repl/src/robotcode/repl/__version__.py new file mode 100644 index 000000000..6b87b1429 --- /dev/null +++ b/packages/repl/src/robotcode/repl/__version__.py @@ -0,0 +1 @@ +__version__ = "0.92.0" diff --git a/packages/repl/src/robotcode/repl/cli/__init__.py b/packages/repl/src/robotcode/repl/cli/__init__.py new file mode 100644 index 000000000..77f8401c6 --- /dev/null +++ b/packages/repl/src/robotcode/repl/cli/__init__.py @@ -0,0 +1,3 @@ +from .repl import repl + +__all__ = ["repl"] diff --git a/packages/repl/src/robotcode/repl/cli/repl.py b/packages/repl/src/robotcode/repl/cli/repl.py new file mode 100644 index 000000000..0b67fcf94 --- /dev/null +++ b/packages/repl/src/robotcode/repl/cli/repl.py @@ -0,0 +1,169 @@ +import io +import sys +from pathlib import Path +from typing import Optional, Tuple + +import click +from robot.api import TestSuite, get_model +from robot.conf import RobotSettings +from robot.errors import DATA_ERROR, INFO_PRINTED, DataError, Information +from robot.output import LOGGER + +from robotcode.plugin import ( + Application, + pass_application, +) +from robotcode.plugin.click_helper.aliases import AliasedCommand +from robotcode.robot.utils import get_robot_version +from robotcode.runner.cli.robot import RobotFrameworkEx, handle_robot_options + +from ..interpreter import Interpreter +from ..repl_listener import ReplListener + +REPL_SUITE = """\ +*** Settings *** +Library robotcode.repl.Repl +*** Test Cases *** +RobotCode REPL + repl +""" + + +def run_repl( + app: Application, + inspect: bool, + variable: Tuple[str, ...], + variablefile: Tuple[str, ...], + pythonpath: Tuple[str, ...], + outputdir: Optional[str], + paths: Tuple[Path, ...], +) -> None: + robot_options_and_args: Tuple[str, ...] = () + + for var in variable: + robot_options_and_args += ("--variable", var) + for varfile in variablefile: + robot_options_and_args += ("--variablefile", varfile) + for pypath in pythonpath: + robot_options_and_args += ("--pythonpath", pypath) + if outputdir: + robot_options_and_args += ("--outputdir", outputdir) + + root_folder, profile, cmd_options = handle_robot_options(app, robot_options_and_args) + + try: + + options, arguments = RobotFrameworkEx( + app, + ( + [*(app.config.default_paths if app.config.default_paths else ())] + if profile.paths is None + else profile.paths if isinstance(profile.paths, list) else [profile.paths] + ), + app.config.dry, + root_folder, + ).parse_arguments((*cmd_options, *robot_options_and_args)) + + settings = RobotSettings( + options, + output=None, + log=None, + report=None, + quiet=True, + listener=[ + ReplListener(app, Interpreter(app, files=list(paths), inspect=inspect)), + ], + ) + + if app.show_diagnostics: + LOGGER.register_console_logger(**settings.console_output_config) + else: + LOGGER.unregister_console_logger() + + LOGGER.unregister_console_logger() + + if get_robot_version() >= (5, 0): + if settings.pythonpath: + sys.path = settings.pythonpath + sys.path + + with io.StringIO(REPL_SUITE) as output: + model = get_model(output) + + suite = TestSuite.from_model(model) + suite.configure(**settings.suite_config) + suite.run(settings) + + except Information as err: + app.echo(str(err)) + app.exit(INFO_PRINTED) + except DataError as err: + app.error(str(err)) + app.exit(DATA_ERROR) + + +@click.command( + cls=AliasedCommand, + aliases=["shell"], + context_settings={"allow_extra_args": True, "ignore_unknown_options": True}, + add_help_option=True, +) +@click.option( + "-v", + "--variable", + metavar="name:value", + type=str, + multiple=True, + help="Set variables in the test data. see `robot --variable` option.", +) +@click.option( + "-V", + "--variablefile", + metavar="path", + type=str, + multiple=True, + help="Python or YAML file file to read variables from. see `robot --variablefile` option.", +) +@click.option( + "-P", + "--pythonpath", + metavar="path", + type=str, + multiple=True, + help="Additional locations (directories, ZIPs, JARs) where to search test libraries" + " and other extensions when they are imported. see `robot --pythonpath` option.", +) +@click.option( + "-d", + "--outputdir", + metavar="dir", + type=str, + help="Where to create output files. see `robot --outputdir` option.", +) +@click.option( + "-i", + "--inspect", + is_flag=True, + default=False, + help="Activate inspection mode. This forces a prompt to appear after the REPL script is executed.", +) +@click.argument( + "paths", + type=click.Path(exists=True, path_type=Path), + nargs=-1, + required=False, +) +@pass_application +def repl( + app: Application, + variable: Tuple[str, ...], + variablefile: Tuple[str, ...], + pythonpath: Tuple[str, ...], + outputdir: Optional[str], + inspect: bool, + paths: Tuple[Path, ...], +) -> None: + """\ + Run Robot Framework interactively. + """ + + run_repl(app, inspect, variable, variablefile, pythonpath, outputdir, paths) diff --git a/packages/repl/src/robotcode/repl/hooks.py b/packages/repl/src/robotcode/repl/hooks.py new file mode 100644 index 000000000..4affae954 --- /dev/null +++ b/packages/repl/src/robotcode/repl/hooks.py @@ -0,0 +1,12 @@ +from typing import List + +import click + +from robotcode.plugin import hookimpl + +from .cli import repl + + +@hookimpl +def register_cli_commands() -> List[click.Command]: + return [repl] diff --git a/packages/repl/src/robotcode/repl/interpreter.py b/packages/repl/src/robotcode/repl/interpreter.py new file mode 100644 index 000000000..b3d419c08 --- /dev/null +++ b/packages/repl/src/robotcode/repl/interpreter.py @@ -0,0 +1,210 @@ +import sys +from pathlib import Path +from typing import Any, Iterator, List, Optional, Tuple, Union, cast + +import click +from robot.api import get_model +from robot.output import LOGGER +from robot.output import Message as OutputMessage +from robot.running import Keyword, TestCase, TestSuite +from robot.running.context import EXECUTION_CONTEXTS +from robot.running.signalhandler import _StopSignalMonitor + +from robotcode.plugin import Application +from robotcode.robot.utils import get_robot_version +from robotcode.robot.utils.ast import iter_nodes + + +def _register_signal_handler(self: Any, exsignum: Any) -> None: + pass + + +# Monkey patching the _register_signal_handler method to disable robot's signal handling +_StopSignalMonitor._register_signal_handler = _register_signal_handler + + +if get_robot_version() >= (7, 0): + + def _run_keyword(kw: Keyword, context: Any) -> Any: + return kw.run(context.steps[-1][1], context) + +else: + + def _run_keyword(kw: Keyword, context: Any) -> Any: + return kw.run(context) + + +TRUE_STRINGS = {"TRUE", "YES", "ON", "1"} + + +def is_true(value: Union[str, bool]) -> bool: + if isinstance(value, str): + return value.upper() in TRUE_STRINGS + return bool(value) + + +class Interpreter: + def __init__(self, app: Application, files: Optional[List[Path]] = None, inspect: Optional[bool] = False) -> None: + self.app = app + self.files = files + self.inspect = inspect + + self.executed_files: List[Path] = [] + + def check_for_errors(self, node: Any) -> List[str]: + if hasattr(node, "tokens"): + for token in node.tokens: + if hasattr(token, "error") and token.error: + raise SyntaxError(token.error) + + if hasattr(node, "error") and node.error: + return [node.error] + + if hasattr(node, "errors") and node.errors: + return list(node.errors) + + return [] + + def get_test_body_from_string(self, command: str) -> Tuple[TestCase, List[str]]: + suite_str = ( + "*** Test Cases ***\nDummyTestCase423141592653589793\n " + + ("\n ".join(command.split("\n")) if "\n" in command else command) + ) + "\n" + + model = get_model(suite_str) + suite: TestSuite = TestSuite.from_model(model) + + errors: List[str] = [] + + for node in iter_nodes(model): + errors.extend(self.check_for_errors(node)) + + return cast(TestCase, suite.tests[0]), errors + + def get_input(self) -> Iterator[Optional[Keyword]]: + if self.executed_files and not self.files and not self.inspect: + yield None + return + + if self.files: + file = self.files.pop(0) + + self.executed_files.append(file) + + text = file.read_text(encoding="utf-8") + + test, errors = self.get_test_body_from_string(text) + if errors: + return + + for kw in test.body: + yield kw + else: + + lines: List[str] = [] + last_one = False + while True: + + prompt = "" + if sys.stdin.isatty(): + prompt = ">>> " if not lines else "... " + + try: + text = input(prompt) + if len(lines) == 0 and text == "": + break + except KeyboardInterrupt: + print() + if len(lines) > 0: + lines = [] + last_one = False + continue + raise + + lines.append(text) + + test, errors = self.get_test_body_from_string("\n".join(lines)) + + if len(lines) > 1 and lines[-1] == "" and text == "": + last_one = True + + if errors: + if not last_one: + continue + + for kw in test.body: + yield kw + + break + + def run_keyword(self, kw: Keyword) -> Any: + with LOGGER.delayed_logging: + kw_result = None + try: + context = EXECUTION_CONTEXTS.current + kw_result = _run_keyword(kw, context) + except (SystemExit, KeyboardInterrupt): + raise + except BaseException: + pass + finally: + messages: List[OutputMessage] = LOGGER._log_message_cache or [] + for msg in messages or (): + # hack to get and evaluate log level + listener: Any = next(iter(LOGGER), None) + if listener is None or listener._is_logged(msg.level): + self.log_message(msg.message, msg.level, msg.html, msg.timestamp) + LOGGER._log_message_cache = [] + + return kw_result + + def run(self) -> Any: + has_input = True + while has_input: + try: + for kw in self.get_input(): + if kw is None: + has_input = False + break + self.set_last_result(self.run_keyword(kw)) + except EOFError: + break + except (SystemExit, KeyboardInterrupt): + break + except BaseException as e: + self.log_message(str(e), "ERROR") + break + + def set_last_result(self, result: Any) -> None: + if result is None: + return + self.app.echo_via_pager(f"{result}") + + def log_message( + self, message: str, level: str, html: Union[str, bool] = False, timestamp: Optional[str] = None + ) -> None: + level_msg = None + + if level == "INFO": + level_msg = click.style("INFO", fg="green") + elif level == "WARN": + level_msg = click.style("WARN", fg="yellow") + elif level == "ERROR": + level_msg = click.style("ERROR", fg="red") + elif level == "FAIL": + level_msg = click.style("FAIL", fg="red", bold=True) + elif level == "SKIP": + level_msg = click.style("SKIP", dim=True) + elif level == "DEBUG": + level_msg = click.style("DEBUG", fg="bright_black") + elif level == "TRACE": + level_msg = click.style("TRACE", fg="bright_black", dim=True) + + msg = message if not is_true(html) else f"*HTML*{message}" + self.app.echo_via_pager(f"[ {level_msg} ] {msg}" if level_msg else msg) + + def message( + self, message: str, level: str, html: Union[str, bool] = False, timestamp: Optional[str] = None + ) -> None: + if self.app.config.verbose: + self.log_message(message, level, html, timestamp) diff --git a/packages/repl/src/robotcode/repl/py.typed b/packages/repl/src/robotcode/repl/py.typed new file mode 100644 index 000000000..1242d4327 --- /dev/null +++ b/packages/repl/src/robotcode/repl/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. diff --git a/packages/repl/src/robotcode/repl/repl_listener.py b/packages/repl/src/robotcode/repl/repl_listener.py new file mode 100644 index 000000000..69ee35f23 --- /dev/null +++ b/packages/repl/src/robotcode/repl/repl_listener.py @@ -0,0 +1,27 @@ +from typing import Any, ClassVar, Dict, Optional + +from robotcode.plugin import Application + +from .interpreter import Interpreter + + +class ReplListener: + ROBOT_LISTENER_API_VERSION = 2 + instance: ClassVar["ReplListener"] + + def __init__(self, app: Application, interpreter: Optional[Interpreter] = None) -> None: + ReplListener.instance = self + self.app = app + self.interpreter = interpreter or Interpreter(app) + + def start_keyword(self, name: str, _attributes: Dict[str, Any]) -> None: + if name != "robotcode.repl.Repl.Repl": + return + + self.interpreter.run() + + def log_message(self, message: Dict[str, Any]) -> None: + self.interpreter.log_message(message["message"], message["level"], message["html"], message.get("timestamp")) + + def message(self, message: Dict[str, Any]) -> None: + self.interpreter.message(message["message"], message["level"], message["html"], message.get("timestamp")) diff --git a/packages/runner/pyproject.toml b/packages/runner/pyproject.toml index ae353cc87..96f5dd86c 100644 --- a/packages/runner/pyproject.toml +++ b/packages/runner/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "robotcode-runner" -description = 'RobotCode runner plugin for Robot Framework' +description = 'RobotCode runner for Robot Framework' readme = { "file" = "README.md", "content-type" = "text/markdown" } requires-python = ">=3.8" license = {text = "Apache-2.0"} diff --git a/packages/runner/src/robotcode/runner/cli/discover/discover.py b/packages/runner/src/robotcode/runner/cli/discover/discover.py index 8e991af99..473919c7b 100644 --- a/packages/runner/src/robotcode/runner/cli/discover/discover.py +++ b/packages/runner/src/robotcode/runner/cli/discover/discover.py @@ -50,7 +50,7 @@ from robotcode.plugin.click_helper.types import add_options from robotcode.robot.utils import get_robot_version -from ..robot import ROBOT_OPTIONS, RobotFrameworkEx, handle_robot_options +from ..robot import ROBOT_OPTIONS, ROBOT_VERSION_OPTIONS, RobotFrameworkEx, handle_robot_options class ErroneousTestSuite(running_model.TestSuite): @@ -372,6 +372,7 @@ def visit_test(self, test: TestCase) -> None: help="Read file contents from stdin. This is an internal option.", hidden=show_hidden_arguments(), ) +@add_options(*ROBOT_VERSION_OPTIONS) @pass_application def discover(app: Application, show_diagnostics: bool, read_from_stdin: bool) -> None: """\ @@ -942,7 +943,7 @@ def files(app: Application, full_paths: bool, paths: Iterable[Path]) -> None: ``` """ - root_folder, profile, cmd_options = handle_robot_options(app, ()) + root_folder, profile, _cmd_options = handle_robot_options(app, ()) search_paths = set( ( diff --git a/packages/runner/src/robotcode/runner/cli/robot.py b/packages/runner/src/robotcode/runner/cli/robot.py index f513f5d04..affad3cdf 100644 --- a/packages/runner/src/robotcode/runner/cli/robot.py +++ b/packages/runner/src/robotcode/runner/cli/robot.py @@ -212,6 +212,19 @@ def parse_arguments(self, cli_args: Any) -> Any: # mypy: disable-error-code="arg-type" +ROBOT_VERSION_OPTIONS = { + click.version_option( + version=__version__, + package_name="robotcode.runner", + prog_name="RobotCode Runner", + message=f"%(prog)s %(version)s\n{USAGE.splitlines()[0].split(' -- ')[0].strip()} {get_full_version()}", + ), +} + +ROBOT_SIMPLE_OPTIONS: Set[click.Command] = { + *ROBOT_VERSION_OPTIONS, + click.argument("robot_options_and_args", nargs=-1, type=click.Path()), +} ROBOT_OPTIONS: Set[click.Command] = { click.option( @@ -226,13 +239,7 @@ def parse_arguments(self, cli_args: Any) -> Any: multiple=True, help="Excludes tests/tasks or suites by longname.", ), - click.version_option( - version=__version__, - package_name="robotcode.runner", - prog_name="RobotCode Runner", - message=f"%(prog)s %(version)s\n{USAGE.splitlines()[0].split(' -- ')[0].strip()} {get_full_version()}", - ), - click.argument("robot_options_and_args", nargs=-1, type=click.Path()), + *ROBOT_SIMPLE_OPTIONS, } diff --git a/pyproject.toml b/pyproject.toml index 80b71071e..3fa457e60 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -78,12 +78,14 @@ yaml = ["PyYAML>=5.4"] lint = ["robotframework-robocop>=2.0.0"] tidy = ["robotframework-tidy>=2.0.0"] rest = ["docutils"] +repl = ["robotcode-repl==0.92.0"] colored = ["rich"] all = [ "robotcode-debugger==0.92.0", "robotcode-language-server==0.92.0", "robotcode-runner==0.92.0", "robotcode-analyze==0.92.0", + "robotcode-repl==0.92.0", "PyYAML>=5.4", "robotframework-robocop>=2.0.0", "robotframework-tidy>=2.0.0", diff --git a/robot.toml b/robot.toml index 64f159524..f940a7ef0 100644 --- a/robot.toml +++ b/robot.toml @@ -3,6 +3,10 @@ python-path = [ "tests/robotcode/language_server/robotframework/parts/data/resources", ] paths = "tests/robotcode/language_server/robotframework/parts/data" +#log-level = "TRACE:TRACE" + +[variables] +a_robot_toml_variable = "a_robot_toml_value" [tool.robotcode-analyze] diff --git a/src/robotcode/cli/commands/config.py b/src/robotcode/cli/commands/config.py index 807bced74..b21d55918 100644 --- a/src/robotcode/cli/commands/config.py +++ b/src/robotcode/cli/commands/config.py @@ -2,7 +2,7 @@ import os from fnmatch import fnmatchcase from pathlib import Path -from typing import Any, Callable, Dict, Iterable, List, Optional, Type, Union, get_args, get_origin +from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Type, Union, get_args, get_origin import click @@ -165,7 +165,7 @@ def files(app: Application, paths: List[Path], user: bool = False) -> None: required=False, ) @pass_application -def root(app: Application, paths: List[Path]) -> None: +def root(app: Application, paths: Tuple[Path, ...]) -> None: """\ Searches for the root folder of the project and prints them.