robotframework-plugins 2026.11.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (199) hide show
  1. robotframework_plugins/__init__.py +14 -0
  2. robotframework_plugins/_assets/catalog.json +143 -0
  3. robotframework_plugins/_assets/plugins/rf-agentskills/.claude-plugin/plugin.json +25 -0
  4. robotframework_plugins/_assets/plugins/rf-agentskills/CHANGELOG.md +198 -0
  5. robotframework_plugins/_assets/plugins/rf-agentskills/README.md +27 -0
  6. robotframework_plugins/_assets/plugins/rf-agentskills/catalog.yaml +25 -0
  7. robotframework_plugins/_assets/plugins/rf-api/.claude-plugin/plugin.json +25 -0
  8. robotframework_plugins/_assets/plugins/rf-api/CHANGELOG.md +9 -0
  9. robotframework_plugins/_assets/plugins/rf-api/README.md +27 -0
  10. robotframework_plugins/_assets/plugins/rf-api/catalog.yaml +27 -0
  11. robotframework_plugins/_assets/plugins/rf-api/skills/rf-requests/SKILL.md +113 -0
  12. robotframework_plugins/_assets/plugins/rf-api/skills/rf-requests/assets/examples/authentication-patterns.robot +39 -0
  13. robotframework_plugins/_assets/plugins/rf-api/skills/rf-requests/assets/examples/basic-crud.robot +46 -0
  14. robotframework_plugins/_assets/plugins/rf-api/skills/rf-requests/assets/examples/file-upload.robot +28 -0
  15. robotframework_plugins/_assets/plugins/rf-api/skills/rf-requests/assets/examples/session-handling.robot +48 -0
  16. robotframework_plugins/_assets/plugins/rf-api/skills/rf-requests/references/async-jobs.md +42 -0
  17. robotframework_plugins/_assets/plugins/rf-api/skills/rf-requests/references/authentication.md +58 -0
  18. robotframework_plugins/_assets/plugins/rf-api/skills/rf-requests/references/install.md +10 -0
  19. robotframework_plugins/_assets/plugins/rf-api/skills/rf-requests/references/loose-assertions.md +20 -0
  20. robotframework_plugins/_assets/plugins/rf-api/skills/rf-requests/references/request-options.md +90 -0
  21. robotframework_plugins/_assets/plugins/rf-api/skills/rf-requests/references/response-validation.md +64 -0
  22. robotframework_plugins/_assets/plugins/rf-api/skills/rf-requests/references/troubleshooting.md +64 -0
  23. robotframework_plugins/_assets/plugins/rf-api/skills/rf-restinstance/SKILL.md +120 -0
  24. robotframework_plugins/_assets/plugins/rf-api/skills/rf-restinstance/assets/examples/basic-rest.robot +51 -0
  25. robotframework_plugins/_assets/plugins/rf-api/skills/rf-restinstance/assets/examples/schema-validation.robot +38 -0
  26. robotframework_plugins/_assets/plugins/rf-api/skills/rf-restinstance/assets/examples/schemas/user.json +10 -0
  27. robotframework_plugins/_assets/plugins/rf-api/skills/rf-restinstance/references/authentication.md +61 -0
  28. robotframework_plugins/_assets/plugins/rf-api/skills/rf-restinstance/references/install.md +11 -0
  29. robotframework_plugins/_assets/plugins/rf-api/skills/rf-restinstance/references/json-handling.md +89 -0
  30. robotframework_plugins/_assets/plugins/rf-api/skills/rf-restinstance/references/loose-assertions.md +18 -0
  31. robotframework_plugins/_assets/plugins/rf-api/skills/rf-restinstance/references/migrate-from-requests.md +15 -0
  32. robotframework_plugins/_assets/plugins/rf-api/skills/rf-restinstance/references/schema-validation.md +85 -0
  33. robotframework_plugins/_assets/plugins/rf-api/skills/rf-restinstance/references/troubleshooting.md +68 -0
  34. robotframework_plugins/_assets/plugins/rf-core/.claude-plugin/plugin.json +19 -0
  35. robotframework_plugins/_assets/plugins/rf-core/CHANGELOG.md +13 -0
  36. robotframework_plugins/_assets/plugins/rf-core/README.md +38 -0
  37. robotframework_plugins/_assets/plugins/rf-core/agents/rf-debug-expert.md +120 -0
  38. robotframework_plugins/_assets/plugins/rf-core/agents/rf-migration-guide.md +73 -0
  39. robotframework_plugins/_assets/plugins/rf-core/agents/rf-test-architect.md +98 -0
  40. robotframework_plugins/_assets/plugins/rf-core/catalog.yaml +19 -0
  41. robotframework_plugins/_assets/plugins/rf-core/hooks/README.md +445 -0
  42. robotframework_plugins/_assets/plugins/rf-core/hooks/hooks.json +70 -0
  43. robotframework_plugins/_assets/plugins/rf-core/scripts/_hook_input.mjs +101 -0
  44. robotframework_plugins/_assets/plugins/rf-core/scripts/_pending_errors.mjs +65 -0
  45. robotframework_plugins/_assets/plugins/rf-core/scripts/_python_env.mjs +181 -0
  46. robotframework_plugins/_assets/plugins/rf-core/scripts/check_rf_environment.mjs +181 -0
  47. robotframework_plugins/_assets/plugins/rf-core/scripts/maybe_inject_rf_context.mjs +74 -0
  48. robotframework_plugins/_assets/plugins/rf-core/scripts/maybe_remind_robot_tests.mjs +128 -0
  49. robotframework_plugins/_assets/plugins/rf-core/scripts/report_pending_errors.mjs +72 -0
  50. robotframework_plugins/_assets/plugins/rf-core/scripts/rf_error_hints.mjs +126 -0
  51. robotframework_plugins/_assets/plugins/rf-core/scripts/validate_robot.mjs +517 -0
  52. robotframework_plugins/_assets/plugins/rf-core/scripts/validate_robot_project.mjs +103 -0
  53. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/SKILL.md +313 -0
  54. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/assets/examples/resources/api.resource +30 -0
  55. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/assets/examples/resources/calc.resource +23 -0
  56. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/assets/examples/resources/embedded.resource +20 -0
  57. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/assets/examples/resources/keywords.resource +26 -0
  58. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/assets/examples/resources/login.resource +10 -0
  59. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/assets/examples/tests/01__keyword_driven.robot +15 -0
  60. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/assets/examples/tests/02__data_driven.robot +10 -0
  61. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/assets/examples/tests/03__templates.robot +17 -0
  62. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/assets/examples/tests/04__bdd.robot +10 -0
  63. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/assets/examples/tests/05__embedded.robot +13 -0
  64. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/assets/examples/tests/__init__.robot +6 -0
  65. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/assets/examples/tests/api/__init__.robot +7 -0
  66. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/assets/examples/tests/api/users.robot +18 -0
  67. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/assets/examples/tests/env.robot +15 -0
  68. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/assets/examples/variables/common.py +11 -0
  69. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/assets/examples/variables/dev.yaml +3 -0
  70. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/assets/examples/variables/staging.yaml +3 -0
  71. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/references/arguments.md +139 -0
  72. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/references/control-structures.md +175 -0
  73. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/references/embedded-arguments.md +135 -0
  74. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/references/migration.md +90 -0
  75. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/references/resources-and-variable-files.md +127 -0
  76. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/references/styles.md +92 -0
  77. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/references/suites-and-init.md +96 -0
  78. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/references/tags-and-selection.md +104 -0
  79. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/references/templates.md +124 -0
  80. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/references/variables-and-scopes.md +129 -0
  81. robotframework_plugins/_assets/plugins/rf-core/skills/rf-language/scripts/rf_conventions.py +883 -0
  82. robotframework_plugins/_assets/plugins/rf-core/skills/rf-python-library/SKILL.md +216 -0
  83. robotframework_plugins/_assets/plugins/rf-core/skills/rf-python-library/assets/examples/ExampleLibrary.py +61 -0
  84. robotframework_plugins/_assets/plugins/rf-core/skills/rf-python-library/assets/examples/ResultListener.py +60 -0
  85. robotframework_plugins/_assets/plugins/rf-core/skills/rf-python-library/assets/examples/converters.py +48 -0
  86. robotframework_plugins/_assets/plugins/rf-core/skills/rf-python-library/assets/examples/converters.robot +20 -0
  87. robotframework_plugins/_assets/plugins/rf-core/skills/rf-python-library/assets/examples/example_library.robot +31 -0
  88. robotframework_plugins/_assets/plugins/rf-core/skills/rf-python-library/assets/examples/listener.robot +12 -0
  89. robotframework_plugins/_assets/plugins/rf-core/skills/rf-python-library/references/api-variants.md +291 -0
  90. robotframework_plugins/_assets/plugins/rf-core/skills/rf-python-library/references/communication.md +248 -0
  91. robotframework_plugins/_assets/plugins/rf-core/skills/rf-python-library/references/conversion.md +347 -0
  92. robotframework_plugins/_assets/plugins/rf-core/skills/rf-python-library/references/listeners.md +150 -0
  93. robotframework_plugins/_assets/plugins/rf-core/skills/rf-python-library/references/packaging-and-docs.md +155 -0
  94. robotframework_plugins/_assets/plugins/rf-core/skills/rf-python-library/scripts/check_library.py +842 -0
  95. robotframework_plugins/_assets/plugins/rf-core/skills/rf-setup/SKILL.md +159 -0
  96. robotframework_plugins/_assets/plugins/rf-core/skills/rf-setup/assets/examples/github-actions-robot.yml +32 -0
  97. robotframework_plugins/_assets/plugins/rf-core/skills/rf-setup/assets/examples/gitignore.txt +22 -0
  98. robotframework_plugins/_assets/plugins/rf-core/skills/rf-setup/assets/examples/pyproject.poetry.toml +28 -0
  99. robotframework_plugins/_assets/plugins/rf-core/skills/rf-setup/assets/examples/pyproject.uv.toml +20 -0
  100. robotframework_plugins/_assets/plugins/rf-core/skills/rf-setup/assets/examples/requirements.txt +9 -0
  101. robotframework_plugins/_assets/plugins/rf-core/skills/rf-setup/assets/examples/robot.toml +16 -0
  102. robotframework_plugins/_assets/plugins/rf-core/skills/rf-setup/assets/examples/smoke.robot +22 -0
  103. robotframework_plugins/_assets/plugins/rf-core/skills/rf-setup/references/ci.md +61 -0
  104. robotframework_plugins/_assets/plugins/rf-core/skills/rf-setup/references/cli-tools.md +33 -0
  105. robotframework_plugins/_assets/plugins/rf-core/skills/rf-setup/references/libraries.md +47 -0
  106. robotframework_plugins/_assets/plugins/rf-core/skills/rf-setup/references/poetry.md +77 -0
  107. robotframework_plugins/_assets/plugins/rf-core/skills/rf-setup/references/project-layout.md +86 -0
  108. robotframework_plugins/_assets/plugins/rf-core/skills/rf-setup/references/troubleshooting.md +73 -0
  109. robotframework_plugins/_assets/plugins/rf-core/skills/rf-setup/references/uv.md +108 -0
  110. robotframework_plugins/_assets/plugins/rf-core/skills/rf-setup/references/venv-pip.md +71 -0
  111. robotframework_plugins/_assets/plugins/rf-core/variants/codex/agents/rf-debug-expert.toml +119 -0
  112. robotframework_plugins/_assets/plugins/rf-core/variants/codex/agents/rf-migration-guide.toml +72 -0
  113. robotframework_plugins/_assets/plugins/rf-core/variants/codex/agents/rf-test-architect.toml +97 -0
  114. robotframework_plugins/_assets/plugins/rf-core/variants/opencode/agents/rf-debug-expert.md +123 -0
  115. robotframework_plugins/_assets/plugins/rf-core/variants/opencode/agents/rf-migration-guide.md +76 -0
  116. robotframework_plugins/_assets/plugins/rf-core/variants/opencode/agents/rf-test-architect.md +101 -0
  117. robotframework_plugins/_assets/plugins/rf-core/variants/opencode/plugins/rf-core.js +93 -0
  118. robotframework_plugins/_assets/plugins/rf-desktop/.claude-plugin/plugin.json +24 -0
  119. robotframework_plugins/_assets/plugins/rf-desktop/CHANGELOG.md +10 -0
  120. robotframework_plugins/_assets/plugins/rf-desktop/README.md +26 -0
  121. robotframework_plugins/_assets/plugins/rf-desktop/catalog.yaml +23 -0
  122. robotframework_plugins/_assets/plugins/rf-desktop/skills/rf-platynui/SKILL.md +268 -0
  123. robotframework_plugins/_assets/plugins/rf-desktop/skills/rf-platynui/assets/examples/calculator.robot +45 -0
  124. robotframework_plugins/_assets/plugins/rf-desktop/skills/rf-platynui/assets/examples/mock-deterministic.robot +33 -0
  125. robotframework_plugins/_assets/plugins/rf-desktop/skills/rf-platynui/references/cli-and-inspector.md +82 -0
  126. robotframework_plugins/_assets/plugins/rf-desktop/skills/rf-platynui/references/install.md +14 -0
  127. robotframework_plugins/_assets/plugins/rf-desktop/skills/rf-platynui/references/keywords-reference.md +102 -0
  128. robotframework_plugins/_assets/plugins/rf-desktop/skills/rf-platynui/references/locators-and-queries.md +95 -0
  129. robotframework_plugins/_assets/plugins/rf-desktop/skills/rf-platynui/references/platform-setup.md +65 -0
  130. robotframework_plugins/_assets/plugins/rf-desktop/skills/rf-platynui/references/status-and-migration.md +41 -0
  131. robotframework_plugins/_assets/plugins/rf-mobile/.claude-plugin/plugin.json +24 -0
  132. robotframework_plugins/_assets/plugins/rf-mobile/CHANGELOG.md +9 -0
  133. robotframework_plugins/_assets/plugins/rf-mobile/README.md +26 -0
  134. robotframework_plugins/_assets/plugins/rf-mobile/catalog.yaml +23 -0
  135. robotframework_plugins/_assets/plugins/rf-mobile/skills/rf-appium/SKILL.md +134 -0
  136. robotframework_plugins/_assets/plugins/rf-mobile/skills/rf-appium/assets/examples/android-basic.robot +60 -0
  137. robotframework_plugins/_assets/plugins/rf-mobile/skills/rf-appium/assets/examples/gestures-example.robot +59 -0
  138. robotframework_plugins/_assets/plugins/rf-mobile/skills/rf-appium/assets/examples/hybrid-app.robot +54 -0
  139. robotframework_plugins/_assets/plugins/rf-mobile/skills/rf-appium/assets/examples/ios-basic.robot +48 -0
  140. robotframework_plugins/_assets/plugins/rf-mobile/skills/rf-appium/references/capabilities.md +117 -0
  141. robotframework_plugins/_assets/plugins/rf-mobile/skills/rf-appium/references/gestures-touch.md +84 -0
  142. robotframework_plugins/_assets/plugins/rf-mobile/skills/rf-appium/references/install.md +21 -0
  143. robotframework_plugins/_assets/plugins/rf-mobile/skills/rf-appium/references/locators-mobile.md +74 -0
  144. robotframework_plugins/_assets/plugins/rf-mobile/skills/rf-appium/references/platform-specific.md +105 -0
  145. robotframework_plugins/_assets/plugins/rf-mobile/skills/rf-appium/references/troubleshooting.md +70 -0
  146. robotframework_plugins/_assets/plugins/rf-web/.claude-plugin/plugin.json +25 -0
  147. robotframework_plugins/_assets/plugins/rf-web/CHANGELOG.md +9 -0
  148. robotframework_plugins/_assets/plugins/rf-web/README.md +27 -0
  149. robotframework_plugins/_assets/plugins/rf-web/catalog.yaml +27 -0
  150. robotframework_plugins/_assets/plugins/rf-web/skills/rf-browser/SKILL.md +134 -0
  151. robotframework_plugins/_assets/plugins/rf-web/skills/rf-browser/assets/examples/authentication-flow.robot +34 -0
  152. robotframework_plugins/_assets/plugins/rf-web/skills/rf-browser/assets/examples/basic-web-test.robot +29 -0
  153. robotframework_plugins/_assets/plugins/rf-web/skills/rf-browser/assets/examples/form-handling.robot +49 -0
  154. robotframework_plugins/_assets/plugins/rf-web/skills/rf-browser/assets/examples/iframe-shadow-dom.robot +31 -0
  155. robotframework_plugins/_assets/plugins/rf-web/skills/rf-browser/references/assertion-engine.md +79 -0
  156. robotframework_plugins/_assets/plugins/rf-web/skills/rf-browser/references/authentication-storage.md +86 -0
  157. robotframework_plugins/_assets/plugins/rf-web/skills/rf-browser/references/browser-context-page.md +110 -0
  158. robotframework_plugins/_assets/plugins/rf-web/skills/rf-browser/references/downloads-uploads.md +51 -0
  159. robotframework_plugins/_assets/plugins/rf-web/skills/rf-browser/references/iframes-shadow-dom.md +67 -0
  160. robotframework_plugins/_assets/plugins/rf-web/skills/rf-browser/references/install.md +67 -0
  161. robotframework_plugins/_assets/plugins/rf-web/skills/rf-browser/references/locators.md +83 -0
  162. robotframework_plugins/_assets/plugins/rf-web/skills/rf-browser/references/migrate-from-selenium.md +22 -0
  163. robotframework_plugins/_assets/plugins/rf-web/skills/rf-browser/references/selector-drift.md +29 -0
  164. robotframework_plugins/_assets/plugins/rf-web/skills/rf-browser/references/troubleshooting.md +100 -0
  165. robotframework_plugins/_assets/plugins/rf-web/skills/rf-selenium/SKILL.md +123 -0
  166. robotframework_plugins/_assets/plugins/rf-web/skills/rf-selenium/assets/examples/basic-web-test.robot +64 -0
  167. robotframework_plugins/_assets/plugins/rf-web/skills/rf-selenium/assets/examples/multi-window.robot +55 -0
  168. robotframework_plugins/_assets/plugins/rf-web/skills/rf-selenium/assets/examples/wait-patterns.robot +53 -0
  169. robotframework_plugins/_assets/plugins/rf-web/skills/rf-selenium/references/browser-setup.md +103 -0
  170. robotframework_plugins/_assets/plugins/rf-web/skills/rf-selenium/references/frames-windows.md +84 -0
  171. robotframework_plugins/_assets/plugins/rf-web/skills/rf-selenium/references/install.md +12 -0
  172. robotframework_plugins/_assets/plugins/rf-web/skills/rf-selenium/references/javascript-execution.md +65 -0
  173. robotframework_plugins/_assets/plugins/rf-web/skills/rf-selenium/references/locators.md +86 -0
  174. robotframework_plugins/_assets/plugins/rf-web/skills/rf-selenium/references/troubleshooting.md +122 -0
  175. robotframework_plugins/_assets/plugins/rf-web/skills/rf-selenium/references/waiting-strategies.md +84 -0
  176. robotframework_plugins/_assets.py +120 -0
  177. robotframework_plugins/_catalog.py +123 -0
  178. robotframework_plugins/_snapshot.py +320 -0
  179. robotframework_plugins/adapters/__init__.py +53 -0
  180. robotframework_plugins/adapters/_base.py +400 -0
  181. robotframework_plugins/adapters/claude_code.py +312 -0
  182. robotframework_plugins/adapters/claude_desktop.py +129 -0
  183. robotframework_plugins/adapters/codex.py +276 -0
  184. robotframework_plugins/adapters/copilot.py +87 -0
  185. robotframework_plugins/adapters/cursor.py +295 -0
  186. robotframework_plugins/adapters/goose.py +240 -0
  187. robotframework_plugins/adapters/opencode.py +170 -0
  188. robotframework_plugins/bundle.py +85 -0
  189. robotframework_plugins/cli.py +1311 -0
  190. robotframework_plugins/detect.py +121 -0
  191. robotframework_plugins/manifest.py +338 -0
  192. robotframework_plugins/py.typed +0 -0
  193. robotframework_plugins/skillzip.py +39 -0
  194. robotframework_plugins/transforms.py +725 -0
  195. robotframework_plugins-2026.11.0.dist-info/METADATA +198 -0
  196. robotframework_plugins-2026.11.0.dist-info/RECORD +199 -0
  197. robotframework_plugins-2026.11.0.dist-info/WHEEL +4 -0
  198. robotframework_plugins-2026.11.0.dist-info/entry_points.txt +2 -0
  199. robotframework_plugins-2026.11.0.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,842 @@
1
+ #!/usr/bin/env python3
2
+ # /// script
3
+ # requires-python = ">=3.10"
4
+ # dependencies = ["robotframework>=7"]
5
+ # ///
6
+ """Robot Framework Python library checker for the rf-python-library skill.
7
+
8
+ Loads each project keyword library the way Robot Framework's libdoc does and
9
+ prints one JSON object (``schema_version`` 1) with, per library, its metadata
10
+ (name, source, scope, version, doc format, API style), its keywords (name,
11
+ arguments in libdoc form, line number, has documentation) and findings for
12
+ Robot Framework-specific defects: import/init failures, rejected keywords,
13
+ "contains no keywords", leaked keywords, public methods hidden by ``@library``,
14
+ exposed listener methods, lost signatures, ``str`` in unions, state kept in a
15
+ TEST-scope library, output during import, broad ``except``, untyped or
16
+ positional-only arguments and missing documentation.
17
+
18
+ Run it in the project environment:
19
+ ``uv run python scripts/check_library.py libraries/<Name>.py``.
20
+
21
+ Safety: loading a library executes its import and ``__init__`` code. The
22
+ checker therefore only accepts libraries inside the project root (the working
23
+ directory or ``--project-root``), loads each one in a child process of the same
24
+ interpreter with a timeout, captures everything that process prints, makes no
25
+ network calls itself and writes no files except the ``--json-out`` target. Use
26
+ it on your own project code only. Libdoc leaves ``BuiltIn().robot_running``
27
+ false, so side effects guarded by it stay inactive.
28
+
29
+ Exit codes: 0 every library was checked (findings and partial load failures
30
+ included), 1 internal error, 2 usage, 3 environment (robotframework>=7 not
31
+ importable), 4 input missing or outside the project root, or every library
32
+ failed to load. stdout carries only the JSON result; diagnostics go to stderr
33
+ as ``error:`` / ``warning:`` / ``hint:`` lines.
34
+ """
35
+ from __future__ import annotations
36
+
37
+ import argparse
38
+ import ast
39
+ import json
40
+ import os
41
+ import re
42
+ import subprocess
43
+ import sys
44
+ import tempfile
45
+ import traceback
46
+ from importlib.machinery import PathFinder
47
+ from pathlib import Path
48
+ from typing import Any, Dict, List, NoReturn, Optional, Tuple
49
+
50
+ SCHEMA_VERSION = 1
51
+ MIN_RF_MAJOR = 7
52
+ EXIT_OK, EXIT_INTERNAL, EXIT_USAGE, EXIT_ENV, EXIT_INPUT = 0, 1, 2, 3, 4
53
+ DEFAULT_TIMEOUT = 30
54
+ DEFAULT_MAX_KEYWORDS = 100
55
+ DEFAULT_MAX_FINDINGS = 50
56
+ MAX_MESSAGE = 300
57
+ MAX_OUTPUT_FINDINGS = 5
58
+ SCRIPT_PATH = os.path.abspath(__file__)
59
+ SEVERITY_ORDER = {"error": 0, "warning": 1, "info": 2}
60
+
61
+ #: The finding ids this checker can report (the contract; messages are not).
62
+ FINDING_IDS: Tuple[str, ...] = (
63
+ "import_failed",
64
+ "keyword_creation_failed",
65
+ "no_keywords",
66
+ "leaked_keyword",
67
+ "public_method_not_keyword",
68
+ "listener_method_exposed",
69
+ "signature_lost",
70
+ "union_with_str",
71
+ "state_in_test_scope",
72
+ "output_during_import",
73
+ "broad_except",
74
+ "untyped_argument",
75
+ "positional_only_argument",
76
+ "missing_doc",
77
+ "library_doc_missing",
78
+ "internal",
79
+ )
80
+
81
+ #: Listener API v3 method names (RF 7.x), incl. the start_/end_ body-item methods.
82
+ LISTENER_METHODS = frozenset(
83
+ ["start_suite", "end_suite", "start_test", "end_test", "start_keyword", "end_keyword",
84
+ "start_library_keyword", "end_library_keyword", "start_user_keyword", "end_user_keyword",
85
+ "start_invalid_keyword", "end_invalid_keyword", "start_body_item", "end_body_item",
86
+ "log_message", "message", "library_import", "resource_import", "variables_import",
87
+ "output_file", "log_file", "report_file", "xunit_file", "debug_file", "close"]
88
+ + [f"{p}_{item}" for p in ("start", "end") for item in (
89
+ "for", "for_iteration", "while", "while_iteration", "group", "if", "if_branch",
90
+ "try", "try_branch", "var", "break", "continue", "return", "error")]
91
+ )
92
+
93
+ #: RF's own messages while importing a library (not user output).
94
+ RF_INTERNAL = re.compile(
95
+ r"^(Imported library |Imported test library |Created keyword |In library '|"
96
+ r"Keyword '.*' could not be run on failure|Library '.*' is a listener)"
97
+ )
98
+ ADDING_KEYWORD_FAILED = re.compile(r"(Error in|In) library '.*': Adding keyword '.*' failed")
99
+ DEFAULT_LIBRARY_DOC = re.compile(r"^Documentation for library ``.*``\.?$")
100
+
101
+ INPUT_HINT = ("the checker loads project libraries only: pass a .py file or package directory "
102
+ "inside the project root (or --project-root), or an import name found on --pythonpath")
103
+ FALLBACK_HINT = ("not using uv? use the project's interpreter (.venv/bin/python or poetry run python); "
104
+ "see the rf-setup skill")
105
+
106
+
107
+ # ---------------------------------------------------------------------------
108
+ # Diagnostics
109
+ # ---------------------------------------------------------------------------
110
+
111
+ def _fail(code: int, error: str, *hints: str) -> NoReturn:
112
+ print(f"error: {error}", file=sys.stderr)
113
+ for hint in hints:
114
+ print(f"hint: {hint}", file=sys.stderr)
115
+ sys.exit(code)
116
+
117
+
118
+ def _warn(message: str) -> None:
119
+ print(f"warning: {message}", file=sys.stderr)
120
+
121
+
122
+ def _cap(text: str, limit: int = MAX_MESSAGE) -> str:
123
+ text = " ".join(str(text).split()) if "\n" in str(text) else str(text)
124
+ return text if len(text) <= limit else text[: limit - 3] + "..."
125
+
126
+
127
+ def _require_robot() -> str:
128
+ """Return the Robot Framework version or exit 3 with hints."""
129
+ try:
130
+ from robot.version import VERSION
131
+ except ImportError as exc:
132
+ _fail(EXIT_ENV, f"Robot Framework is not importable by {sys.executable} ({exc})",
133
+ f"run it through the project environment: uv run python {SCRIPT_PATH} ...",
134
+ "add Robot Framework to the project: uv add robotframework",
135
+ FALLBACK_HINT)
136
+ try:
137
+ major = int(str(VERSION).split(".")[0])
138
+ except ValueError:
139
+ major = 0
140
+ if major < MIN_RF_MAJOR:
141
+ _fail(EXIT_ENV, f"Robot Framework {VERSION} found in {sys.executable}; "
142
+ f"robotframework>={MIN_RF_MAJOR} is required",
143
+ f"run it through the project environment: uv run python {SCRIPT_PATH} ...",
144
+ 'upgrade Robot Framework in the project: uv add "robotframework>=7"',
145
+ FALLBACK_HINT)
146
+ return str(VERSION)
147
+
148
+
149
+ # ---------------------------------------------------------------------------
150
+ # Input resolution (parent; never imports user code)
151
+ # ---------------------------------------------------------------------------
152
+
153
+ class InputError(RuntimeError):
154
+ def __init__(self, message: str, hint: str = INPUT_HINT) -> None:
155
+ super().__init__(message)
156
+ self.hint = hint
157
+
158
+
159
+ def _inside(path: Path, root: Path) -> bool:
160
+ try:
161
+ path.resolve().relative_to(root)
162
+ return True
163
+ except ValueError:
164
+ return False
165
+
166
+
167
+ def _looks_like_path(value: str) -> bool:
168
+ return ("/" in value or "\\" in value or value.endswith(".py")
169
+ or value in (".", "..") or Path(value).exists())
170
+
171
+
172
+ def _find_module(name: str, search: List[str]) -> Optional[Path]:
173
+ """Origin of module ``name`` found on ``search`` without importing anything."""
174
+ locations: Optional[List[str]] = list(search)
175
+ spec = None
176
+ for part in name.split("."):
177
+ if locations is None:
178
+ return None
179
+ spec = PathFinder.find_spec(part, locations)
180
+ if spec is None:
181
+ return None
182
+ locations = list(spec.submodule_search_locations or []) or None
183
+ if spec is None or not spec.origin or spec.origin in ("built-in", "frozen"):
184
+ return None
185
+ return Path(spec.origin)
186
+
187
+
188
+ def resolve_name(name: str, pythonpath: List[str], root: Path) -> Tuple[Path, str]:
189
+ """Resolve an import name (``Inventory``, ``pkg.mod``, ``pkg.mod.Class``) to its file.
190
+
191
+ Only ``pythonpath`` entries (all inside the project root) are searched. A
192
+ name found elsewhere (site-packages, stdlib) is refused.
193
+ """
194
+ parts = name.split(".")
195
+ if not all(p.isidentifier() for p in parts):
196
+ raise InputError(f"not a library path or import name: {name}")
197
+ for cut in (len(parts), len(parts) - 1):
198
+ if cut < 1:
199
+ break
200
+ origin = _find_module(".".join(parts[:cut]), pythonpath)
201
+ if origin is not None:
202
+ if not _inside(origin, root):
203
+ break
204
+ return origin.resolve(), name
205
+ elsewhere = None
206
+ for cut in (len(parts), len(parts) - 1):
207
+ if cut >= 1:
208
+ elsewhere = elsewhere or _find_module(".".join(parts[:cut]), sys.path)
209
+ if elsewhere is not None and not _inside(elsewhere, root):
210
+ raise InputError(
211
+ f"'{name}' resolves to {elsewhere}, outside the project root {root}; "
212
+ "only project libraries are checked",
213
+ "for installed third-party libraries use `robotcode doc keywords <Library>` instead",
214
+ )
215
+ raise InputError(
216
+ f"cannot find module '{name}' on the python-path {pythonpath or '[]'}",
217
+ "pass the library file (libraries/<Name>.py) or add its directory with --pythonpath",
218
+ )
219
+
220
+
221
+ def resolve_inputs(inputs: List[str], pythonpath: List[str], root: Path) -> List[Dict[str, Any]]:
222
+ resolved: List[Dict[str, Any]] = []
223
+ for value in inputs:
224
+ if _looks_like_path(value):
225
+ path = Path(value).expanduser()
226
+ if not path.exists():
227
+ raise InputError(f"library not found: {value}",
228
+ "check the path; project libraries usually live in libraries/")
229
+ path = path.resolve()
230
+ if not _inside(path, root):
231
+ raise InputError(
232
+ f"{value} is outside the project root {root}; only project libraries are checked "
233
+ "(loading a library runs its code)",
234
+ "run the checker from the project root or pass --project-root; for installed "
235
+ "libraries use `robotcode doc keywords <Library>`",
236
+ )
237
+ if path.is_dir():
238
+ init = path / "__init__.py"
239
+ if not init.is_file():
240
+ raise InputError(f"{value} is a directory without __init__.py (not a library package)")
241
+ origin, own = init, path
242
+ elif path.suffix != ".py":
243
+ raise InputError(f"{value} is not a Python file (.py) or package directory")
244
+ else:
245
+ origin, own = path, path
246
+ resolved.append({"input": value, "spec": str(path), "origin": str(origin),
247
+ "own": str(own), "extra_path": str(path.parent)})
248
+ else:
249
+ origin, spec = resolve_name(value, pythonpath, root)
250
+ own = origin.parent if origin.name == "__init__.py" else origin
251
+ resolved.append({"input": value, "spec": spec, "origin": str(origin),
252
+ "own": str(own), "extra_path": None})
253
+ return resolved
254
+
255
+
256
+ # ---------------------------------------------------------------------------
257
+ # Worker (child process): load one library and analyse it
258
+ # ---------------------------------------------------------------------------
259
+
260
+ class _Capture:
261
+ """Robot Framework logger that records messages instead of printing them."""
262
+
263
+ def __init__(self) -> None:
264
+ self.messages: List[Tuple[str, str]] = []
265
+
266
+ def message(self, msg: Any) -> None:
267
+ self.messages.append((str(getattr(msg, "level", "INFO")), str(getattr(msg, "message", msg))))
268
+
269
+ log_message = message
270
+
271
+
272
+ def _finding(fid: str, severity: str, message: str, hint: Optional[str] = None,
273
+ keyword: Optional[str] = None) -> Dict[str, Any]:
274
+ return {"id": fid, "severity": severity, "keyword": keyword, "message": _cap(message), "hint": hint}
275
+
276
+
277
+ def _import_failed_hint(message: str) -> str:
278
+ if "ModuleNotFoundError" in message or "No module named" in message:
279
+ return ("add the missing package to the project with its tool (uv add <package>; see rf-setup), "
280
+ "or fix the import / --pythonpath")
281
+ if "RobotNotRunningError" in message:
282
+ return ("BuiltIn() is not usable while libdoc or the checker loads the library: "
283
+ "call BuiltIn() inside keywords, not in __init__ or at import time")
284
+ if message.startswith("Initializing library"):
285
+ return ("__init__ failed: keep __init__ cheap and guard side effects with "
286
+ "BuiltIn().robot_running and not BuiltIn().dry_run_active, or pass --init-arg")
287
+ return "fix the import error; run the module with python to see the full traceback"
288
+
289
+
290
+ def _function_index(tree: ast.Module) -> Dict[int, Tuple[str, Optional[str], ast.AST]]:
291
+ """Line number (def and decorator lines) -> (function name, class name, node)."""
292
+ index: Dict[int, Tuple[str, Optional[str], ast.AST]] = {}
293
+
294
+ def add(fn: Any, cls: Optional[str]) -> None:
295
+ for line in [fn.lineno] + [d.lineno for d in fn.decorator_list]:
296
+ index.setdefault(line, (fn.name, cls, fn))
297
+
298
+ for node in tree.body:
299
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
300
+ add(node, None)
301
+ elif isinstance(node, ast.ClassDef):
302
+ for sub in node.body:
303
+ if isinstance(sub, (ast.FunctionDef, ast.AsyncFunctionDef)):
304
+ add(sub, node.name)
305
+ return index
306
+
307
+
308
+ def _self_attr(target: ast.AST) -> Optional[str]:
309
+ """``self.x`` / ``self.x[...]`` / ``self.x.y`` assignment target -> ``x``."""
310
+ node = target
311
+ while isinstance(node, (ast.Subscript, ast.Attribute)):
312
+ if isinstance(node, ast.Attribute) and isinstance(node.value, ast.Name) and node.value.id == "self":
313
+ return node.attr
314
+ node = node.value
315
+ return None
316
+
317
+
318
+ def _state_mutations(cls_node: ast.ClassDef) -> List[Tuple[str, str, int]]:
319
+ out: List[Tuple[str, str, int]] = []
320
+ for fn in cls_node.body:
321
+ if not isinstance(fn, (ast.FunctionDef, ast.AsyncFunctionDef)) or fn.name.startswith("_"):
322
+ continue
323
+ for sub in ast.walk(fn):
324
+ targets: List[ast.AST] = []
325
+ if isinstance(sub, ast.Assign):
326
+ targets = list(sub.targets)
327
+ elif isinstance(sub, (ast.AugAssign, ast.AnnAssign)):
328
+ targets = [sub.target]
329
+ hit = next((a for a in (_self_attr(t) for t in targets) if a), None)
330
+ if hit:
331
+ out.append((fn.name, hit, sub.lineno))
332
+ break
333
+ return out
334
+
335
+
336
+ def _is_broad(handler: ast.ExceptHandler) -> bool:
337
+ names: List[ast.AST] = []
338
+ if handler.type is None:
339
+ return True
340
+ names = list(handler.type.elts) if isinstance(handler.type, ast.Tuple) else [handler.type]
341
+ return any(isinstance(n, ast.Name) and n.id in ("Exception", "BaseException") for n in names)
342
+
343
+
344
+ def _broad_excepts(fn: ast.AST) -> List[int]:
345
+ lines = []
346
+ for sub in ast.walk(fn):
347
+ if isinstance(sub, ast.ExceptHandler) and _is_broad(sub):
348
+ if not any(isinstance(n, ast.Raise) for stmt in sub.body for n in ast.walk(stmt)):
349
+ lines.append(sub.lineno)
350
+ return lines
351
+
352
+
353
+ def _library_object(module: Any, requested: str) -> Tuple[Any, Optional[type]]:
354
+ """Mirror RF's selection: named class, class with the module's name, or the single @library class."""
355
+ import inspect
356
+ parts = requested.split(".")
357
+ for name in (parts[-1], module.__name__.split(".")[-1]):
358
+ cls = getattr(module, name, None)
359
+ if inspect.isclass(cls):
360
+ return cls, cls
361
+ from robot.version import VERSION
362
+ if tuple(int(p) for p in re.findall(r"\d+", VERSION)[:2]) < (7, 2):
363
+ return module, None # before RF 7.2 a module without a same-named class is a module library
364
+ decorated = [c for _, c in inspect.getmembers(module, inspect.isclass)
365
+ if c.__module__ == module.__name__ and "ROBOT_AUTO_KEYWORDS" in vars(c)]
366
+ if len(decorated) == 1:
367
+ return decorated[0], decorated[0]
368
+ return module, None
369
+
370
+
371
+ def _declares_listener(cls: type, cls_node: Optional[ast.ClassDef]) -> bool:
372
+ if getattr(cls, "ROBOT_LIBRARY_LISTENER", None) is not None:
373
+ return True
374
+ if cls_node is not None:
375
+ for sub in ast.walk(cls_node):
376
+ if isinstance(sub, ast.Assign) and any(
377
+ (isinstance(t, ast.Attribute) and t.attr == "ROBOT_LIBRARY_LISTENER")
378
+ or (isinstance(t, ast.Name) and t.id == "ROBOT_LIBRARY_LISTENER")
379
+ for t in sub.targets):
380
+ return True
381
+ return False
382
+
383
+
384
+ def _norm(name: str) -> str:
385
+ return name.lower().replace(" ", "_")
386
+
387
+
388
+ def _type_is_union_with_str(type_info: Any) -> bool:
389
+ if not type_info or not getattr(type_info, "is_union", False):
390
+ return False
391
+ nested = list(getattr(type_info, "nested", None) or [])
392
+ has_str = any(getattr(n, "type", None) is str for n in nested)
393
+ others = [n for n in nested if getattr(n, "type", None) not in (str, type(None))
394
+ and str(getattr(n, "name", "")) != "None"]
395
+ return has_str and bool(others)
396
+
397
+
398
+ def _analyse(doc: Any, cfg: Dict[str, Any], messages: List[Tuple[str, str]]) -> Dict[str, Any]:
399
+ import inspect
400
+ own = Path(cfg["own"])
401
+ root = Path(cfg["root"])
402
+ findings: List[Dict[str, Any]] = []
403
+ raw_doc = (doc.doc or "").strip()
404
+ has_doc = bool(raw_doc) and not DEFAULT_LIBRARY_DOC.match(raw_doc)
405
+
406
+ module = None
407
+ origin = Path(cfg["origin"]).resolve()
408
+ for mod in list(sys.modules.values()):
409
+ f = getattr(mod, "__file__", None)
410
+ if f and Path(f).resolve() == origin:
411
+ module = mod
412
+ break
413
+ obj, cls = (_library_object(module, cfg["spec"]) if module is not None else (None, None))
414
+ if obj is not None and hasattr(obj, "get_keyword_names"):
415
+ api = "dynamic" if hasattr(obj, "run_keyword") else "hybrid"
416
+ else:
417
+ api = "static"
418
+
419
+ tree = None
420
+ try:
421
+ tree = ast.parse(origin.read_text(encoding="utf-8"))
422
+ except (OSError, SyntaxError, UnicodeDecodeError):
423
+ tree = None
424
+ index = _function_index(tree) if tree is not None else {}
425
+ cls_node = None
426
+ if tree is not None and cls is not None:
427
+ cls_node = next((n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == cls.__name__), None)
428
+
429
+ library = {
430
+ "name": doc.name,
431
+ "source": str(doc.source) if doc.source else None,
432
+ "scope": doc.scope,
433
+ "version": doc.version or None,
434
+ "doc_format": doc.doc_format,
435
+ "api": api,
436
+ "has_doc": has_doc,
437
+ "keyword_count": len(doc.keywords),
438
+ "init_args": list(cfg["init_args"]),
439
+ }
440
+
441
+ for level, text in messages:
442
+ if level in ("ERROR", "WARN") and ADDING_KEYWORD_FAILED.search(text):
443
+ findings.append(_finding(
444
+ "keyword_creation_failed", "error", text,
445
+ "fix the keyword definition; library embedded-argument names take no inline types "
446
+ "(use Python type hints on the function arguments)"))
447
+ if not doc.keywords:
448
+ findings.append(_finding(
449
+ "no_keywords", "error", f"library '{doc.name}' contains no keywords",
450
+ "with @library, decorate each keyword method with @keyword (automatic discovery is off); "
451
+ "check keyword_creation_failed findings"))
452
+ if not has_doc:
453
+ findings.append(_finding("library_doc_missing", "info", f"library '{doc.name}' has no documentation",
454
+ "add a class or module docstring (libdoc shows it as the introduction)"))
455
+
456
+ keywords: List[Dict[str, Any]] = []
457
+ for kw in doc.keywords:
458
+ method = None
459
+ if kw.lineno and kw.source and Path(str(kw.source)).resolve() == origin:
460
+ hit = index.get(kw.lineno)
461
+ method = hit[0] if hit else None
462
+ entry = {"name": kw.name, "args": [str(a) for a in kw.args], "lineno": kw.lineno,
463
+ "has_doc": bool((kw.doc or "").strip())}
464
+ keywords.append(entry)
465
+ try:
466
+ src = str(kw.source) if kw.source else ""
467
+ known = bool(src) and not src.startswith("<") and Path(src).exists()
468
+ if api == "static":
469
+ leaked = not known or not (Path(src).resolve() == own or _inside(Path(src), own))
470
+ else:
471
+ leaked = bool(src) and (not known or not _inside(Path(src), root))
472
+ if leaked:
473
+ findings.append(_finding(
474
+ "leaked_keyword", "warning",
475
+ f"'{kw.name}' is defined in {src or 'an unknown source'}, not in {own.name}",
476
+ "import modules instead of functions (import os, not from os.path import join), prefix "
477
+ "helpers with _, or use @library so only @keyword methods become keywords", kw.name))
478
+ if not entry["has_doc"]:
479
+ findings.append(_finding("missing_doc", "info", f"keyword '{kw.name}' has no documentation",
480
+ "add a docstring; its first line becomes the short doc", kw.name))
481
+ kinds = [str(a.kind) for a in kw.args]
482
+ if kinds == ["VAR_POSITIONAL", "VAR_NAMED"]:
483
+ findings.append(_finding(
484
+ "signature_lost", "warning", f"'{kw.name}' only takes *args, **kwargs",
485
+ "a decorator without functools.wraps hides the real signature (and type conversion)",
486
+ kw.name))
487
+ if "POSITIONAL_ONLY" in kinds:
488
+ findings.append(_finding(
489
+ "positional_only_argument", "info",
490
+ f"'{kw.name}' has positional-only arguments; tests cannot pass them by name",
491
+ "drop the / marker unless the positional-only form is intended", kw.name))
492
+ for arg in kw.args:
493
+ if str(arg.kind) in ("VAR_POSITIONAL", "VAR_NAMED", "POSITIONAL_ONLY_MARKER",
494
+ "NAMED_ONLY_MARKER"):
495
+ continue
496
+ if _type_is_union_with_str(arg.type):
497
+ findings.append(_finding(
498
+ "union_with_str", "warning",
499
+ f"'{kw.name}' argument '{arg}' contains str: string arguments are never converted",
500
+ "drop str from the union (or put the converting types only), or convert explicitly",
501
+ kw.name))
502
+ if not arg.type and arg.required:
503
+ findings.append(_finding(
504
+ "untyped_argument", "info", f"'{kw.name}' argument '{arg.name}' has no type hint",
505
+ "add a type hint to get automatic conversion and documented types", kw.name))
506
+ names = {_norm(kw.name)} | ({method} if method else set())
507
+ if names & LISTENER_METHODS:
508
+ findings.append(_finding(
509
+ "listener_method_exposed", "warning",
510
+ f"listener method '{method or kw.name}' is exposed as keyword '{kw.name}'",
511
+ "register the listener with @library(listener='SELF') / ROBOT_LIBRARY_LISTENER and use "
512
+ "@library so listener methods are not keywords, or move the listener to its own class",
513
+ kw.name))
514
+ if method and api == "static" and tree is not None:
515
+ fn = index[kw.lineno][2]
516
+ for line in _broad_excepts(fn):
517
+ findings.append(_finding(
518
+ "broad_except", "info",
519
+ f"'{kw.name}' catches Exception/BaseException (line {line}) without re-raising",
520
+ "catch specific exceptions; a broad except swallows Robot Framework timeouts "
521
+ "(robot.errors.TimeoutExceeded on RF >= 7.3, TimeoutError before)", kw.name))
522
+ except Exception as exc: # RF API differences must not crash the checker
523
+ findings.append(_finding("internal", "info", f"check of '{kw.name}' failed: {type(exc).__name__}: {exc}",
524
+ "report this with the Robot Framework version", kw.name))
525
+
526
+ if cls is not None and api == "static":
527
+ try:
528
+ findings.extend(_class_checks(cls, cls_node, doc.scope, origin, inspect))
529
+ except Exception as exc:
530
+ findings.append(_finding("internal", "info", f"class checks failed: {type(exc).__name__}: {exc}",
531
+ "report this with the Robot Framework version"))
532
+
533
+ for level, text in messages:
534
+ if level in ("TRACE", "DEBUG") or RF_INTERNAL.search(text) or ADDING_KEYWORD_FAILED.search(text):
535
+ continue
536
+ findings.append(_output_finding(f"[{level}] {text}"))
537
+ return {"library": library, "keywords": keywords, "findings": findings}
538
+
539
+
540
+ def _output_finding(text: str) -> Dict[str, Any]:
541
+ return _finding(
542
+ "output_during_import", "warning", f"output while importing or initialising the library: {text}",
543
+ "libdoc, --dryrun and every new instance run this code: move it into a keyword or guard it with "
544
+ "BuiltIn().robot_running and not BuiltIn().dry_run_active")
545
+
546
+
547
+ def _class_checks(cls: type, cls_node: Optional[ast.ClassDef], scope: str, origin: Path,
548
+ inspect: Any) -> List[Dict[str, Any]]:
549
+ findings: List[Dict[str, Any]] = []
550
+ listener = _declares_listener(cls, cls_node)
551
+ if vars(cls).get("ROBOT_AUTO_KEYWORDS", True) is False or getattr(cls, "ROBOT_AUTO_KEYWORDS", True) is False:
552
+ for name, member in inspect.getmembers(cls):
553
+ if name.startswith("_") or inspect.isclass(member) or not callable(member):
554
+ continue
555
+ try:
556
+ if Path(inspect.getsourcefile(member) or "").resolve() != origin:
557
+ continue
558
+ except TypeError:
559
+ continue
560
+ if hasattr(member, "robot_name") or getattr(member, "robot_not_keyword", False):
561
+ continue
562
+ if listener and name in LISTENER_METHODS:
563
+ continue
564
+ findings.append(_finding(
565
+ "public_method_not_keyword", "warning",
566
+ f"public method '{name}' is not a keyword: @library turns off automatic keyword discovery",
567
+ "add @keyword to expose it; mark helpers with @not_keyword or a leading underscore", name))
568
+ if scope == "TEST" and cls_node is not None:
569
+ for method, attr, line in _state_mutations(cls_node):
570
+ findings.append(_finding(
571
+ "state_in_test_scope", "warning",
572
+ f"'{method}' changes self.{attr} (line {line}) but the scope is TEST: a new instance is "
573
+ "created for every test, so this state does not survive to the next test",
574
+ "state that must span tests needs @library(scope='SUITE') or 'GLOBAL' plus a cleanup keyword; "
575
+ "if the state is meant to reset for every test, keep TEST and say so (heuristic warning)", method))
576
+ return findings
577
+
578
+
579
+ def run_worker(cfg_path: str) -> int:
580
+ """Child process entry point: load one library, write the result JSON to cfg['result']."""
581
+ sys.dont_write_bytecode = True
582
+ with open(cfg_path, encoding="utf-8") as fh:
583
+ cfg = json.load(fh)
584
+ result: Dict[str, Any] = {"ok": False}
585
+ try:
586
+ for entry in reversed(cfg["pythonpath"]):
587
+ if entry not in sys.path:
588
+ sys.path.insert(0, entry)
589
+ from robot.output import LOGGER
590
+ LOGGER.unregister_console_logger()
591
+ capture = _Capture()
592
+ LOGGER.register_logger(capture)
593
+ start = len(capture.messages)
594
+ from robot.libdocpkg import LibraryDocumentation
595
+ spec = cfg["spec"] + "".join("::" + a for a in cfg["init_args"])
596
+ try:
597
+ doc = LibraryDocumentation(spec)
598
+ except Exception as exc:
599
+ text = str(exc).strip()
600
+ first = text.splitlines()[0] if text else type(exc).__name__
601
+ result = {"ok": False, "error": first, "hint": _import_failed_hint(first)}
602
+ else:
603
+ result = {"ok": True, **_analyse(doc, cfg, capture.messages[start:])}
604
+ except BaseException as exc: # noqa: BLE001 - the worker must always report
605
+ result = {"ok": False, "error": f"checker worker failed: {type(exc).__name__}: {exc}",
606
+ "hint": "re-run with --debug for a traceback", "internal": True,
607
+ "traceback": traceback.format_exc() if cfg.get("debug") else None}
608
+ with open(cfg["result"], "w", encoding="utf-8") as fh:
609
+ json.dump(result, fh)
610
+ return 0
611
+
612
+
613
+ # ---------------------------------------------------------------------------
614
+ # Parent: run one worker per library
615
+ # ---------------------------------------------------------------------------
616
+
617
+ def _load_one(item: Dict[str, Any], pythonpath: List[str], root: Path, init_args: List[str],
618
+ timeout: float, debug: bool) -> Dict[str, Any]:
619
+ with tempfile.TemporaryDirectory(prefix="rf-check-library-") as tmp:
620
+ cfg_file = Path(tmp) / "config.json"
621
+ result_file = Path(tmp) / "result.json"
622
+ extra = [item["extra_path"]] if item["extra_path"] else []
623
+ cfg = {"spec": item["spec"], "origin": item["origin"], "own": item["own"], "root": str(root),
624
+ "init_args": init_args, "pythonpath": pythonpath + [p for p in extra if p not in pythonpath],
625
+ "result": str(result_file), "debug": debug}
626
+ cfg_file.write_text(json.dumps(cfg), encoding="utf-8")
627
+ env = {**os.environ, "PYTHONDONTWRITEBYTECODE": "1", "PYTHONIOENCODING": "utf-8"}
628
+ try:
629
+ proc = subprocess.run([sys.executable, SCRIPT_PATH, "--_worker", str(cfg_file)],
630
+ cwd=str(root), capture_output=True, text=True, timeout=timeout,
631
+ env=env, stdin=subprocess.DEVNULL)
632
+ except subprocess.TimeoutExpired:
633
+ return {"ok": False,
634
+ "error": f"loading the library timed out after {timeout:g} s (import or __init__ hangs)",
635
+ "hint": "move slow work (connections, waits) out of import and __init__ into keywords, "
636
+ "or raise --timeout"}
637
+ data: Dict[str, Any]
638
+ if result_file.is_file():
639
+ data = json.loads(result_file.read_text(encoding="utf-8"))
640
+ else:
641
+ tail = (proc.stderr or proc.stdout or "").strip().splitlines()[-1:]
642
+ data = {"ok": False,
643
+ "error": f"the library process exited with code {proc.returncode} before reporting"
644
+ + (f": {_cap(tail[0], 200)}" if tail else ""),
645
+ "hint": "the library ends the interpreter at import or __init__ (sys.exit/os._exit or a "
646
+ "crash in a native extension)"}
647
+ return data
648
+ raw = "\n".join(t for t in (proc.stdout.strip(), proc.stderr.strip()) if t)
649
+ if data.get("ok") and raw:
650
+ data["raw_output"] = raw
651
+ if debug and data.get("traceback"):
652
+ sys.stderr.write("".join(f"hint: {ln}\n" for ln in data["traceback"].splitlines()))
653
+ return data
654
+
655
+
656
+ def _bounded(entry: Dict[str, Any], max_keywords: int, max_findings: int) -> Dict[str, Any]:
657
+ findings = sorted(entry["findings"], key=lambda f: SEVERITY_ORDER[f["severity"]])
658
+ keywords = entry["keywords"]
659
+ entry["omitted"] = {"keywords": max(0, len(keywords) - max_keywords),
660
+ "findings": max(0, len(findings) - max_findings)}
661
+ entry["keywords"] = keywords[:max_keywords]
662
+ entry["findings"] = findings[:max_findings]
663
+ return entry
664
+
665
+
666
+ def check(inputs: List[str], *, init_args: Optional[List[str]] = None, pythonpath: Optional[List[str]] = None,
667
+ project_root: Optional[str] = None, timeout: float = DEFAULT_TIMEOUT,
668
+ max_keywords: int = DEFAULT_MAX_KEYWORDS, max_findings: int = DEFAULT_MAX_FINDINGS,
669
+ debug: bool = False) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]:
670
+ """Check ``inputs``; return (JSON result, list of load failures). Raises InputError."""
671
+ version = _require_robot()
672
+ root = Path(project_root or os.getcwd()).expanduser()
673
+ if not root.is_dir():
674
+ raise InputError(f"project root not found or not a directory: {root}",
675
+ "pass the directory that holds libraries/ and tests/ with --project-root")
676
+ root = root.resolve()
677
+ if pythonpath:
678
+ paths: List[str] = []
679
+ for entry in pythonpath:
680
+ p = Path(entry).expanduser()
681
+ p = (p if p.is_absolute() else Path.cwd() / p).resolve()
682
+ if not p.is_dir():
683
+ raise InputError(f"--pythonpath entry not found: {entry}")
684
+ if not _inside(p, root):
685
+ raise InputError(f"--pythonpath entry {entry} is outside the project root {root}",
686
+ "only project directories may be added to the python-path")
687
+ paths.append(str(p))
688
+ else:
689
+ paths = [str(root / d) for d in ("libraries", "resources") if (root / d).is_dir()]
690
+ items = resolve_inputs(inputs, paths, root)
691
+ libraries: List[Dict[str, Any]] = []
692
+ failures: List[Dict[str, Any]] = []
693
+ counts: Dict[str, int] = {}
694
+ for item in items:
695
+ data = _load_one(item, paths, root, list(init_args or []), timeout, debug)
696
+ if data.get("ok"):
697
+ entry = {"input": item["input"], "library": data["library"], "keywords": data["keywords"],
698
+ "findings": list(data["findings"])}
699
+ raw = data.get("raw_output")
700
+ if raw:
701
+ seen = {f["message"] for f in entry["findings"] if f["id"] == "output_during_import"}
702
+ for line in [ln for ln in raw.splitlines() if ln.strip()]:
703
+ f = _output_finding(line.strip())
704
+ if f["message"] not in seen and not any(line.strip() in s for s in seen):
705
+ entry["findings"].append(f)
706
+ seen.add(f["message"])
707
+ outs = [f for f in entry["findings"] if f["id"] == "output_during_import"]
708
+ if len(outs) > MAX_OUTPUT_FINDINGS:
709
+ drop = {id(f) for f in outs[MAX_OUTPUT_FINDINGS:]}
710
+ entry["findings"] = [f for f in entry["findings"] if id(f) not in drop]
711
+ else:
712
+ entry = {"input": item["input"], "library": None, "keywords": [],
713
+ "findings": [_finding("import_failed", "error", data["error"], data.get("hint"))]}
714
+ failures.append({"input": item["input"], "error": _cap(data["error"]), "hint": data.get("hint")})
715
+ for f in entry["findings"]:
716
+ counts[f["severity"]] = counts.get(f["severity"], 0) + 1
717
+ libraries.append(_bounded(entry, max_keywords, max_findings))
718
+ summary: Dict[str, int] = {"libraries": len(libraries),
719
+ "loaded": sum(1 for lib in libraries if lib["library"])}
720
+ summary.update({sev: counts.get(sev, 0) for sev in SEVERITY_ORDER})
721
+ result = {"schema_version": SCHEMA_VERSION, "robot_version": version, "libraries": libraries,
722
+ "summary": summary}
723
+ return result, failures
724
+
725
+
726
+ # ---------------------------------------------------------------------------
727
+ # CLI
728
+ # ---------------------------------------------------------------------------
729
+
730
+ EPILOG = """\
731
+ examples:
732
+ uv run python scripts/check_library.py libraries/Inventory.py
733
+ uv run python scripts/check_library.py libraries/*.py --pretty
734
+ uv run python scripts/check_library.py Client --init-arg https://staging.example.com --pythonpath libraries
735
+ uv run python scripts/check_library.py libraries/Inventory.py --json-out results/check_library.json
736
+
737
+ The script path is relative to the rf-python-library skill directory; library
738
+ paths are relative to the project root (the working directory). Not using uv?
739
+ Run it with the project's interpreter (.venv/bin/python or poetry run python);
740
+ see rf-setup. Loading a library runs its import and __init__ code: check your
741
+ own project libraries only.
742
+ exit codes: 0 checked (findings do not change it), 1 internal error, 2 usage,
743
+ 3 environment (robotframework>=7 missing), 4 input missing or outside the
744
+ project root, or every library failed to load.
745
+ """
746
+
747
+
748
+ class _Parser(argparse.ArgumentParser):
749
+ """argparse with ``error:``/``hint:`` stderr lines and exit code 2."""
750
+
751
+ def error(self, message: str) -> NoReturn: # type: ignore[override]
752
+ _fail(EXIT_USAGE, message, f"see the options and examples: uv run python {SCRIPT_PATH} --help")
753
+
754
+
755
+ def build_parser() -> argparse.ArgumentParser:
756
+ parser = _Parser(
757
+ description="Check Robot Framework keyword libraries written in Python and print JSON on stdout.",
758
+ epilog=EPILOG,
759
+ formatter_class=argparse.RawDescriptionHelpFormatter,
760
+ )
761
+ parser.add_argument("inputs", nargs="+", metavar="LIBRARY",
762
+ help="library .py file, package directory or import name (e.g. Inventory)")
763
+ parser.add_argument("--init-arg", action="append", default=[], metavar="VALUE",
764
+ help="library init argument (repeatable; only with a single LIBRARY)")
765
+ parser.add_argument("--pythonpath", action="append", default=[], metavar="DIR",
766
+ help="python-path entry inside the project (repeatable; default: libraries/ and "
767
+ "resources/ if they exist, plus the library file's directory)")
768
+ parser.add_argument("--project-root", metavar="DIR",
769
+ help="only libraries inside DIR are loaded (default: the working directory)")
770
+ parser.add_argument("--timeout", type=float, default=DEFAULT_TIMEOUT, metavar="SECONDS",
771
+ help=f"per-library load timeout (default {DEFAULT_TIMEOUT})")
772
+ parser.add_argument("--max-keywords", type=int, default=DEFAULT_MAX_KEYWORDS, metavar="N",
773
+ help=f"keywords listed per library (default {DEFAULT_MAX_KEYWORDS}; cut -> omitted.keywords)")
774
+ parser.add_argument("--max-findings", type=int, default=DEFAULT_MAX_FINDINGS, metavar="N",
775
+ help=f"findings per library (default {DEFAULT_MAX_FINDINGS}; cut -> omitted.findings)")
776
+ parser.add_argument("--json-out", metavar="FILE",
777
+ help="write the JSON result to FILE; stdout gets {written, bytes, mode}")
778
+ parser.add_argument("--pretty", action="store_true", help="indent the JSON output")
779
+ parser.add_argument("--debug", action="store_true", help="print a traceback on internal errors")
780
+ return parser
781
+
782
+
783
+ def emit(data: Dict[str, Any], *, pretty: bool, json_out: Optional[str]) -> None:
784
+ text = json.dumps(data, indent=2) if pretty else json.dumps(data, separators=(",", ":"))
785
+ if not json_out:
786
+ print(text)
787
+ return
788
+ os.makedirs(os.path.dirname(os.path.abspath(json_out)), exist_ok=True)
789
+ payload = (text + "\n").encode("utf-8")
790
+ with open(json_out, "wb") as fh:
791
+ fh.write(payload)
792
+ print(json.dumps({"written": json_out, "bytes": len(payload), "mode": "check_library"}))
793
+
794
+
795
+ def _run_cli(args: argparse.Namespace, parser: argparse.ArgumentParser) -> int:
796
+ if args.max_keywords < 0:
797
+ parser.error("--max-keywords must be >= 0")
798
+ if args.max_findings < 0:
799
+ parser.error("--max-findings must be >= 0")
800
+ if args.timeout <= 0:
801
+ parser.error("--timeout must be > 0")
802
+ if args.init_arg and len(args.inputs) > 1:
803
+ parser.error("--init-arg applies to a single LIBRARY; check libraries with init arguments one by one")
804
+ try:
805
+ data, failures = check(args.inputs, init_args=args.init_arg, pythonpath=args.pythonpath,
806
+ project_root=args.project_root, timeout=args.timeout,
807
+ max_keywords=args.max_keywords, max_findings=args.max_findings,
808
+ debug=args.debug)
809
+ except InputError as exc:
810
+ _fail(EXIT_INPUT, str(exc), exc.hint)
811
+ if failures and len(failures) == len(data["libraries"]):
812
+ for fail in failures:
813
+ print(f"error: {fail['input']}: {fail['error']}", file=sys.stderr)
814
+ hints = list(dict.fromkeys(f["hint"] for f in failures if f.get("hint")))
815
+ for hint in hints or [INPUT_HINT]:
816
+ print(f"hint: {hint}", file=sys.stderr)
817
+ return EXIT_INPUT
818
+ for fail in failures:
819
+ _warn(f"{fail['input']}: {fail['error']}")
820
+ emit(data, pretty=args.pretty, json_out=args.json_out)
821
+ return EXIT_OK
822
+
823
+
824
+ def main(argv: Optional[List[str]] = None) -> None:
825
+ argv = list(sys.argv[1:] if argv is None else argv)
826
+ if argv[:1] == ["--_worker"] and len(argv) == 2:
827
+ sys.exit(run_worker(argv[1]))
828
+ parser = build_parser()
829
+ args = parser.parse_args(argv)
830
+ try:
831
+ code = _run_cli(args, parser)
832
+ except SystemExit:
833
+ raise
834
+ except Exception as exc:
835
+ if args.debug:
836
+ traceback.print_exc(file=sys.stderr)
837
+ _fail(EXIT_INTERNAL, f"internal: {type(exc).__name__}: {exc}", "re-run with --debug for a traceback")
838
+ sys.exit(code)
839
+
840
+
841
+ if __name__ == "__main__":
842
+ main()