|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import ast |
| 4 | +from typing import TYPE_CHECKING, Any, List, Optional, Union, cast |
| 5 | + |
| 6 | +from ....utils.logging import LoggingDescriptor |
| 7 | +from ...common.decorators import code_action_kinds, command, language_id |
| 8 | +from ...common.lsp_types import ( |
| 9 | + AnnotatedTextEdit, |
| 10 | + ChangeAnnotation, |
| 11 | + CodeAction, |
| 12 | + CodeActionContext, |
| 13 | + CodeActionKinds, |
| 14 | + CodeActionTriggerKind, |
| 15 | + Command, |
| 16 | + DocumentUri, |
| 17 | + OptionalVersionedTextDocumentIdentifier, |
| 18 | + Position, |
| 19 | + Range, |
| 20 | + TextDocumentEdit, |
| 21 | + WorkspaceEdit, |
| 22 | +) |
| 23 | +from ...common.text_document import TextDocument |
| 24 | +from ..utils.ast_utils import Token, get_node_at_position, range_from_node |
| 25 | +from ..utils.async_ast import AsyncVisitor |
| 26 | +from .model_helper import ModelHelperMixin |
| 27 | + |
| 28 | +if TYPE_CHECKING: |
| 29 | + from ..protocol import RobotLanguageServerProtocol # pragma: no cover |
| 30 | + |
| 31 | +from string import Template |
| 32 | + |
| 33 | +from .protocol_part import RobotLanguageServerProtocolPart |
| 34 | + |
| 35 | +CODEACTIONKINDS_QUICKFIX_CREATEKEYWORD = f"{CodeActionKinds.QUICKFIX}.createKeyword" |
| 36 | + |
| 37 | + |
| 38 | +KEYWORD_WITH_ARGS_TEMPLATE = Template( |
| 39 | + """\n |
| 40 | +${name} |
| 41 | + [Arguments] ${args} |
| 42 | + Fail Not implemented |
| 43 | +""" |
| 44 | +) |
| 45 | + |
| 46 | +KEYWORD_TEMPLATE = Template( |
| 47 | + """\n |
| 48 | +${name} |
| 49 | + Fail Not implemented |
| 50 | +""" |
| 51 | +) |
| 52 | + |
| 53 | + |
| 54 | +class FindKeywordSectionVisitor(AsyncVisitor): |
| 55 | + def __init__(self) -> None: |
| 56 | + self.keyword_sections: List[ast.AST] = [] |
| 57 | + |
| 58 | + async def visit_KeywordSection(self, node: ast.AST) -> None: # noqa: N802 |
| 59 | + self.keyword_sections.append(node) |
| 60 | + |
| 61 | + |
| 62 | +async def find_keyword_sections(node: ast.AST) -> Optional[List[ast.AST]]: |
| 63 | + visitor = FindKeywordSectionVisitor() |
| 64 | + await visitor.visit(node) |
| 65 | + return visitor.keyword_sections if visitor.keyword_sections else None |
| 66 | + |
| 67 | + |
| 68 | +class RobotCodeActionFixesProtocolPart(RobotLanguageServerProtocolPart, ModelHelperMixin): |
| 69 | + _logger = LoggingDescriptor() |
| 70 | + |
| 71 | + def __init__(self, parent: RobotLanguageServerProtocol) -> None: |
| 72 | + super().__init__(parent) |
| 73 | + |
| 74 | + parent.code_action.collect.add(self.collect) |
| 75 | + |
| 76 | + self.parent.commands.register_all(self) |
| 77 | + |
| 78 | + @language_id("robotframework") |
| 79 | + @code_action_kinds( |
| 80 | + [ |
| 81 | + CODEACTIONKINDS_QUICKFIX_CREATEKEYWORD, |
| 82 | + ] |
| 83 | + ) |
| 84 | + @_logger.call |
| 85 | + async def collect( |
| 86 | + self, sender: Any, document: TextDocument, range: Range, context: CodeActionContext |
| 87 | + ) -> Optional[List[Union[Command, CodeAction]]]: |
| 88 | + |
| 89 | + kw_not_found_in_diagnostics = next((d for d in context.diagnostics if d.code == "KeywordNotFoundError"), None) |
| 90 | + |
| 91 | + if kw_not_found_in_diagnostics and ( |
| 92 | + (context.only and CodeActionKinds.QUICKFIX in context.only) |
| 93 | + or context.trigger_kind in [CodeActionTriggerKind.INVOKED, CodeActionTriggerKind.AUTOMATIC] |
| 94 | + ): |
| 95 | + return [ |
| 96 | + CodeAction( |
| 97 | + "Create Keyword", |
| 98 | + kind=CodeActionKinds.QUICKFIX + ".createKeyword", |
| 99 | + command=Command( |
| 100 | + "Create Keyword", |
| 101 | + self.parent.commands.get_command_name(self.create_keyword), |
| 102 | + [document.document_uri, range, context], |
| 103 | + ), |
| 104 | + diagnostics=[kw_not_found_in_diagnostics], |
| 105 | + ) |
| 106 | + ] |
| 107 | + |
| 108 | + return None |
| 109 | + |
| 110 | + @command("robotcode.createKeyword") |
| 111 | + async def create_keyword(self, document_uri: DocumentUri, range: Range, context: CodeActionContext) -> None: |
| 112 | + from robot.parsing.lexer import Token as RobotToken |
| 113 | + from robot.parsing.model.statements import ( |
| 114 | + Fixture, |
| 115 | + KeywordCall, |
| 116 | + Template, |
| 117 | + TestTemplate, |
| 118 | + ) |
| 119 | + from robot.utils.escaping import split_from_equals |
| 120 | + |
| 121 | + document = await self.parent.documents.get(document_uri) |
| 122 | + if document is None: |
| 123 | + return |
| 124 | + |
| 125 | + namespace = await self.parent.documents_cache.get_namespace(document) |
| 126 | + if namespace is None: |
| 127 | + return None |
| 128 | + |
| 129 | + model = await self.parent.documents_cache.get_model(document, False) |
| 130 | + node = await get_node_at_position(model, range.start) |
| 131 | + |
| 132 | + if isinstance(node, (KeywordCall, Fixture, TestTemplate, Template)): |
| 133 | + keyword = ( |
| 134 | + node.value |
| 135 | + if isinstance(node, (TestTemplate, Template)) |
| 136 | + else node.keyword |
| 137 | + if isinstance(node, KeywordCall) |
| 138 | + else node.name |
| 139 | + ) |
| 140 | + |
| 141 | + arguments = [] |
| 142 | + |
| 143 | + for t in node.get_tokens(RobotToken.ARGUMENT): |
| 144 | + name, value = split_from_equals(cast(Token, t).value) |
| 145 | + if value is not None: |
| 146 | + arguments.append(f"${{{name}}}") |
| 147 | + else: |
| 148 | + arguments.append(f"${{arg{len(arguments)+1}}}") |
| 149 | + |
| 150 | + insert_text = ( |
| 151 | + KEYWORD_WITH_ARGS_TEMPLATE.substitute(name=keyword, args=" ".join(arguments)) |
| 152 | + if arguments |
| 153 | + else KEYWORD_TEMPLATE.substitute(name=keyword) |
| 154 | + ) |
| 155 | + |
| 156 | + keyword_sections = await find_keyword_sections(model) |
| 157 | + keyword_section = keyword_sections[-1] if keyword_sections else None |
| 158 | + |
| 159 | + if keyword_section is not None: |
| 160 | + node_range = range_from_node(keyword_section) |
| 161 | + |
| 162 | + insert_range = Range(node_range.end, node_range.end) |
| 163 | + else: |
| 164 | + insert_text = f"\n\n\n*** Keywords ***\n{insert_text}" |
| 165 | + doc_pos = Position(len(document.get_lines()), 0) |
| 166 | + insert_range = Range(doc_pos, doc_pos) |
| 167 | + |
| 168 | + we = WorkspaceEdit( |
| 169 | + document_changes=[ |
| 170 | + TextDocumentEdit( |
| 171 | + OptionalVersionedTextDocumentIdentifier(str(document.uri), document.version), |
| 172 | + [AnnotatedTextEdit(insert_range, insert_text, annotation_id="create_keyword")], |
| 173 | + ) |
| 174 | + ], |
| 175 | + change_annotations={"create_keyword": ChangeAnnotation("Create Keyword", False)}, |
| 176 | + ) |
| 177 | + |
| 178 | + await self.parent.workspace.apply_edit(we, "Rename Keyword") |
0 commit comments