Skip to content

Add resource file support to custom parser API #5666

Description

@Lakitna

Context

Born from this discussion on Slack: https://robotframework.slack.com/archives/C015KB1QSDN/p1775116818448659

Robot includes the Parser API:

Robot Framework supports external parsers that can handle custom data formats or even override Robot Framework's own parser.

Recently, I tried to use this API to centrally replace the import to a library. In doing so, I found out that the parser API only works for suite files (.robot files with tests/tasks) and init files (__init__.robot files). Any other filetype is unsupported by the Parser API. This includes:

  • Resource files (.robot/.resource files without tests/tasks)
  • Variable files (.json/.py/.yaml, ...)
  • Library files (.py)

Goal

Extend the parser API to also allow control over the following filetypes:

  • Resource files
  • Variable files Already controllable through Python logic using a .py file with get_variables function. Because of this, I see no need right now to add support for this to the Parser API. If someone disagrees, please open a separate issue for this.
  • Library files Already controllable through Python logic because these are Python files by definition. Because of this, I see no need right now to add support for this to the Parser API. If someone disagrees, please open a separate issue for this.

Possible design

The current parser API is implemented with a parse and parse_init method/function. See user guide for details. The parse function allows you to change suite files. The parse_init function allows you to change __init__.robot files.

Add a new function/method to the Parser API: parse_resource. Example:

from robot.running.resourcemodel import ResourceFile

class RobotPreParser:
    def parse_resource(self, source: Path) -> ResourceFile:
        resource = ResourceFile.from_file_system(source)
        # Do something interesting
        return resource

This would allow full control over both the raw and the parsed resource file before Robot does anything else with it. This approach builds out the existing parser API. This should be a non-breaking change.

Optionally, parse can be renamed to parse_suite. This would make it clear what the function applies to. This is a breaking change. A soft deprecation is possible here: Rename to parse_suite, make parse an alias for parse_suite, deprecate parse in subsequent major version(s). Renaming the parse function can be a separate issue.

Activity

  1. pekkaklarck commented on May 5, 2026

    @pekkaklarck
    Member

    Enhancing custom parsers so that they can parse resource files is certainly a good idea. That was left out originally because there were no reported use cases and because it would have increased complexity of the custom parser implementation. Now we have a concrete request for this functionality and based on quick prototyping this isn't overly complicated to implement either.

    When the custom parser API was originally implemented, a big part of the work was designing the API. Now that the API exists, it is logical to extend it with new, optional parse_resource(source: Path) -> ResourceFile method as the description already explained. I don't see big enough benefits in renaming the existing parse method to parse_suite, though.

  2. pekkaklarck commented on May 5, 2026

    @pekkaklarck
    Member

    As I hinted above, I did little prototyping and got the basic functionality working. My main motivation was to see is it feasible to implement this in RF 7.5 scope and based on the prototype the answer is yes. The code needs cleanup, lacks error handling, doesn't have tests or documentation, probably breaks some existing functionality and is in general very much in prototype level. I don't have time to finish it in the near future, so I'll paste the code here in case @Lakitna or someone else is interested to continue the work. That would also be the best way to make sure this actually gets implemented in RF 7.5. There are other issues that I consider more important and/or that need my expertise more, and I will concentrate on them first.

    diff --git a/src/robot/running/builder/builders.py b/src/robot/running/builder/builders.py
    index 2eaf31025..8e70da7e8 100644
    --- a/src/robot/running/builder/builders.py
    +++ b/src/robot/running/builder/builders.py
    @@ -181,6 +181,7 @@ class TestSuiteBuilder:
             if not self.allow_empty_suite:
                 self._validate_not_empty(suite, multi_source=len(paths) > 1)
             suite.remove_empty_suites(preserve_direct_children=len(paths) > 1)
    +        suite.custom_parsers = self.custom_parsers
             return suite
     
         def _normalize_paths(self, paths: "Sequence[Path|str]") -> "tuple[Path, ...]":
    @@ -304,8 +305,11 @@ class SuiteStructureParser(SuiteStructureVisitor):
     
     class ResourceFileBuilder:
     
    -    def __init__(self, lang: LanguagesLike = None, process_curdir: bool = True):
    +    def __init__(
    +        self, parsers=None, lang: LanguagesLike = None, process_curdir: bool = True
    +    ):
             self.lang = lang
    +        self.parsers = parsers
             self.process_curdir = process_curdir
     
         def build(self, source: Path) -> ResourceFile:
    @@ -321,12 +325,14 @@ class ResourceFileBuilder:
             return resource
     
         def _parse(self, source: Path) -> ResourceFile:
    -        suffix = source.suffix.lower()
    -        if suffix in (".rst", ".rest"):
    +        suffix = source.suffix.lower()[1:]
    +        if suffix in self.parsers:
    +            parser = self.parsers[suffix]
    +        elif suffix in ("rst", "rest"):
                 parser = RestParser(self.lang, self.process_curdir)
    -        elif suffix in (".json", ".rsrc"):
    +        elif suffix in ("json", "rsrc"):
                 parser = JsonParser()
    -        elif suffix in (".md", ".markdown"):
    +        elif suffix in ("md", "markdown"):
                 parser = MarkdownParser(self.lang, self.process_curdir)
             else:
                 parser = RobotParser(self.lang, self.process_curdir)
    diff --git a/src/robot/running/builder/parsers.py b/src/robot/running/builder/parsers.py
    index 22bb38703..81f906f5f 100644
    --- a/src/robot/running/builder/parsers.py
    +++ b/src/robot/running/builder/parsers.py
    @@ -211,6 +211,10 @@ class CustomParser(Parser):
             except NotImplementedError:
                 return super().parse_init_file(source, defaults)  # Raises DataError
     
    +    def parse_resource_file(self, source: Path) -> ResourceFile:
    +        parse_resource = getattr(self.parser, "parse_resource", None)
    +        return parse_resource(source)
    +
         def _parse(self, method, source, defaults, init=False) -> TestSuite:
             if not method:
                 raise NotImplementedError
    diff --git a/src/robot/running/importer.py b/src/robot/running/importer.py
    index 39328f6de..23db4089d 100644
    --- a/src/robot/running/importer.py
    +++ b/src/robot/running/importer.py
    @@ -74,21 +74,22 @@ class Importer:
                 LOGGER.info(f"Imported library '{name}' with name '{alias}'.")
             return lib
     
    -    def import_resource(self, path, lang=None):
    -        self._validate_resource_extension(path)
    +    def import_resource(self, path, custom_parsers=None, lang=None):
    +        self._validate_resource_extension(path, custom_parsers)
             if path in self._resource_cache:
                 LOGGER.info(f"Found resource file '{path}' from cache.")
             else:
    -            resource = ResourceFileBuilder(lang=lang).build(path)
    +            resource = ResourceFileBuilder(custom_parsers, lang).build(path)
                 self._resource_cache[path] = resource
             return self._resource_cache[path]
     
    -    def _validate_resource_extension(self, path):
    +    def _validate_resource_extension(self, path, parsers):
             extension = os.path.splitext(path)[1]
    -        if extension.lower() not in RESOURCE_EXTENSIONS:
    +        supported = RESOURCE_EXTENSIONS | {f".{ext}" for ext in parsers}
    +        if extension.lower() not in supported:
                 raise DataError(
                     f"Invalid resource file extension '{extension}'. "
    -                f"Supported extensions are {seq2str(sorted(RESOURCE_EXTENSIONS))}."
    +                f"Supported extensions are {seq2str(sorted(supported))}."
                 )
     
         def _log_imported_library(self, name, args_str, lib):
    diff --git a/src/robot/running/model.py b/src/robot/running/model.py
    index 09501d165..48bda02ee 100644
    --- a/src/robot/running/model.py
    +++ b/src/robot/running/model.py
    @@ -691,7 +691,7 @@ class TestSuite(model.TestSuite[Keyword, TestCase]):
     
         test_class = TestCase  #: Internal usage only.
         fixture_class = Keyword  #: Internal usage only.
    -    __slots__ = ()
    +    __slots__ = ("custom_parsers",)
     
         def __init__(
             self,
    diff --git a/src/robot/running/namespace.py b/src/robot/running/namespace.py
    index ee828b3cd..8cb8659ab 100644
    --- a/src/robot/running/namespace.py
    +++ b/src/robot/running/namespace.py
    @@ -42,10 +42,11 @@ class Namespace:
             ".json",
         )
     
    -    def __init__(self, variables, suite, resource, languages):
    +    def __init__(self, variables, suite, resource, languages, resource_parsers):
             LOGGER.info(f"Initializing namespace for suite '{suite.full_name}'.")
             self.variables = variables
             self.languages = languages
    +        self.resource_parsers = resource_parsers
             self._imports = resource.imports
             self._kw_store = KeywordStore(resource, languages)
             self._imported_variable_files = ImportCache()
    @@ -97,7 +98,9 @@ class Namespace:
             path = self._resolve_name(import_)
             self._validate_not_importing_init_file(path)
             if overwrite or path not in self._kw_store.resources:
    -            resource = IMPORTER.import_resource(path, self.languages)
    +            resource = IMPORTER.import_resource(
    +                path, self.resource_parsers, self.languages
    +            )
                 self.variables.set_from_variable_section(resource.variables, overwrite)
                 self._kw_store.resources[path] = resource
                 self._handle_imports(resource.imports)
    diff --git a/src/robot/running/suiterunner.py b/src/robot/running/suiterunner.py
    index 1a71d776c..98534c8f7 100644
    --- a/src/robot/running/suiterunner.py
    +++ b/src/robot/running/suiterunner.py
    @@ -83,7 +83,13 @@ class SuiteRunner(SuiteVisitor):
                 self.settings.exit_on_error,
                 self.settings.skip_teardown_on_exit,
             )
    -        ns = Namespace(self.variables, result, data.resource, self.settings.languages)
    +        ns = Namespace(
    +            self.variables,
    +            result,
    +            data.resource,
    +            self.settings.languages,
    +            data.custom_parsers,
    +        )
             ns.start_suite()
             ns.variables.set_from_variable_section(data.resource.variables)
             EXECUTION_CONTEXTS.start_suite(result, ns, self.output, self.settings.dry_run)
  3. added this to the v7.5 milestone on May 5, 2026
  4. added theissue type on May 5, 2026
  5. changed the issue type fromtoon May 5, 2026
  6. changed the title [-]Make preparser work for resource files[/-] [+]Add resource file support to custom parser API[/+] on May 5, 2026
  7. Lakitna commented on May 10, 2026

    @Lakitna
    Author

    I gave it a look. Your implementation seems to to require the parser to include resource as an extension:

    class RobotPreParser:
        extension = ("robot", "resource")

    Doing this will make it call the parse function for all .resource files. Because it's in the list of extensions. It will then try to parse the resource file as a suite file which is problematic.

    Do you think that parse should never call .resource, or that a second list of extensions is better? Something like:

    class RobotPreParser:
        extension = ("robot", "custom_robot")
        resource_extension = ("resource", "custom_resource")

    Or do you have another approach that'd work better?

  8. pekkaklarck commented on May 12, 2026

    @pekkaklarck
    Member

    Good catch. It's probably best to add separate resource_extension. Special casing .resource would fix that particular case, but the same problem would occur with other extensions.

    Other things that came to my mind:

    • We probably should support parsers that only implement parse_resource. Currently parse is required, but we could make it optional. We could then validate that at least one of parse, parse_init and parse_resource exists, but I don't think that's necessary. We don't, for example, validate that a listener has any listener methods (but that could be a good idea now that I think about it).
    • My implementation adds the custom parser information to TestSuite.custom_parsers during parsing time. That feels a bit like a hack and storing this information to some context object would be much better. We unfortunately don't have such a context object available and adding one as part of this enhancement isn't worth the effort. Probably storing the information in TestSuite is fine, but perhaps we should use TestSuite._custom_parsers to indicate this isn't part of the public API.
  9. Lakitna commented on May 15, 2026

    @Lakitna
    Author

    We don't, for example, validate that a listener has any listener methods (but that could be a good idea now that I think about it).

    For the parser, this seems easy enough. Making all parser methods optional (but 1 required) sounds like a good idea.

    I did see that it should be part of TestSuite, but so far I've only gotten custom resource parsers working on directory suites and not yet on file suites. I've been trying to trace where TestSuite is created, but this seems to be in quite a few places. And all those places need to get a list of custom resource parsers. It's been quite the puzzle, probably because I'm also familiarizing myself with the codebase at the same time :)

  10. pekkaklarck commented on May 15, 2026

    @pekkaklarck
    Member

    It's certainly a puzzle. Some of the stuff is fairly complicated and some of the old code is just bad. Getting familiar with the code base certainly helps if if are interested to contribute!

  11. Lakitna commented on May 17, 2026

    @Lakitna
    Author

    I've got a working version! 🎉🎉

    It's still pretty rough. It still needs at least:

    • Adding tests
    • Changing existing tests
    • Discussion on adding things to the public API (robot.api)
    • Resolving TODOs
    • Fix custom parsers that extend the Parser interface

    That being said, initial comments are much appreciated :)

    #5678

  12. pekkaklarck commented on May 17, 2026

    @pekkaklarck
    Member

    Awesome! I'm currently at our cottage fixing things and have only limited time for my real work until I'm home. It may thus take several days until I can look at this properly.

  13. Lakitna commented on May 17, 2026

    @Lakitna
    Author

    No problem! In the meantime, I'll keep chipping away at it. There are 30 atests to fix and 2 utests to fix and I also have to familiarize myself with the testing setup. That should give you plenty of time to check it out when you have more time :)

  14. pekkaklarck commented on Sep 1, 2026

    @pekkaklarck
    Member

    Unfortunately I have been busy with other RF 7.5 features and haven't had time to look at this. Now RF 7.5 is getting ready, but it's been delayed so much (the target was to get it out in early July) that I want to get it released ASAP. I looked at the PR implementing this quickly and noticed that the PR is still draft, there are some TODOs in the code and that there are some conflicts to be fixed. In this situation I believe it's best to move this issue to RF 7.6 and look at it again a bit later when we have more time.

  15. modified the milestones: v7.5, v7.6 on Sep 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions