diff --git a/autohooks/config.py b/autohooks/config.py index a6f80fc6..eaa30b3e 100644 --- a/autohooks/config.py +++ b/autohooks/config.py @@ -134,6 +134,20 @@ def from_dict(config_dict: Dict[str, Any]) -> "AutohooksConfig": ) return AutohooksConfig(settings=settings, config=config) + @staticmethod + def from_string(content: str) -> "AutohooksConfig": + """ + Load an AutohooksConfig from a string + + Args: + content: The content of the config + + Returns: + A new AutohooksConfig + """ + config_dict = tomlkit.loads(content) + return AutohooksConfig.from_dict(config_dict) + @staticmethod def from_toml(toml_file: Path) -> "AutohooksConfig": """ @@ -145,8 +159,7 @@ def from_toml(toml_file: Path) -> "AutohooksConfig": Returns: A new AutohooksConfig """ - config_dict = tomlkit.loads(toml_file.read_text()) - return AutohooksConfig.from_dict(config_dict) + return AutohooksConfig.from_string(toml_file.read_text()) def load_config_from_pyproject_toml( diff --git a/tests/test_config.py b/tests/test_config.py index 90281078..51326885 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -42,6 +42,27 @@ def test_load_from_non_existing_toml_file(self): self.assertEqual(len(config.get_pre_commit_script_names()), 0) + def test_load_from_string(self): + config = AutohooksConfig.from_string( + """ + [tool.autohooks] + pre-commit = ["foo", "bar"] + """ + ) + + self.assertTrue(config.has_autohooks_config()) + + self.assertListEqual( + config.get_pre_commit_script_names(), ["foo", "bar"] + ) + + def test_load_from_empty_string(self): + config = AutohooksConfig.from_string("") + + self.assertFalse(config.has_autohooks_config()) + + self.assertEqual(config.get_pre_commit_script_names(), []) + def test_empty_config(self): config = AutohooksConfig()