Skip to content

Commit

Permalink
Generate configuration file (#566)
Browse files Browse the repository at this point in the history
Generate configuration file command
  • Loading branch information
bhirsz authored Aug 28, 2023
1 parent ec09534 commit d8b9963
Show file tree
Hide file tree
Showing 8 changed files with 315 additions and 4 deletions.
57 changes: 57 additions & 0 deletions docs/releasenotes/unreleased/other.1.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
Generate configuration file (#563)
-----------------------------------

New option to generate configuration file with most important options and their default values::

robotidy --generate-config

It is only enabled after installing optional ``generate_config`` profile::

pip install robotidy[generate_config]

Generated configuration contains all transformers with their enabled status. Example of the file::

[tool.robotidy]
diff = false
overwrite = true
verbose = false
separator = "space"
spacecount = 4
line_length = 120
lineseparator = "native"
skip_gitignore = false
ignore_git_dir = false
configure = [
"AddMissingEnd:enabled=True",
"NormalizeSeparators:enabled=True",
"DiscardEmptySections:enabled=True",
"MergeAndOrderSections:enabled=True",
"RemoveEmptySettings:enabled=True",
"ReplaceEmptyValues:enabled=True",
"NormalizeAssignments:enabled=True",
"GenerateDocumentation:enabled=False",
"OrderSettings:enabled=True",
"OrderSettingsSection:enabled=True",
"NormalizeTags:enabled=True",
"OrderTags:enabled=False",
"RenameVariables:enabled=False",
"IndentNestedKeywords:enabled=False",
"AlignSettingsSection:enabled=True",
"AlignVariablesSection:enabled=True",
"AlignTemplatedTestCases:enabled=False",
"AlignTestCasesSection:enabled=False",
"AlignKeywordsSection:enabled=False",
"NormalizeNewLines:enabled=True",
"NormalizeSectionHeaderName:enabled=True",
"NormalizeSettingName:enabled=True",
"ReplaceRunKeywordIf:enabled=True",
"SplitTooLongLine:enabled=True",
"SmartSortKeywords:enabled=False",
"RenameTestCases:enabled=False",
"RenameKeywords:enabled=False",
"ReplaceReturns:enabled=True",
"ReplaceBreakContinue:enabled=True",
"InlineIf:enabled=True",
"Translate:enabled=False",
"NormalizeComments:enabled=True",
]
120 changes: 120 additions & 0 deletions docs/source/configuration/config_file.rst
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,126 @@ multiple configuration files, the source paths from other configurations than th
"NormalizeSeparators"
]
Generate configuration file
---------------------------

It is possible to generate configuration files that contains most important options with their default values.
First install ``robotidy`` with ``generate_config`` that contains module for writing TOML files::

pip install robotidy[generate_config]

You can generate configuration now::

robotidy --generate-config

.. dropdown:: Example of generated configuration file

.. code-block:: toml
[tool.robotidy]
diff = false
overwrite = true
verbose = false
separator = "space"
spacecount = 4
line_length = 120
lineseparator = "native"
skip_gitignore = false
ignore_git_dir = false
configure = [
"AddMissingEnd:enabled=True",
"NormalizeSeparators:enabled=True",
"DiscardEmptySections:enabled=True",
"MergeAndOrderSections:enabled=True",
"RemoveEmptySettings:enabled=True",
"ReplaceEmptyValues:enabled=True",
"NormalizeAssignments:enabled=True",
"GenerateDocumentation:enabled=False",
"OrderSettings:enabled=True",
"OrderSettingsSection:enabled=True",
"NormalizeTags:enabled=True",
"OrderTags:enabled=False",
"RenameVariables:enabled=False",
"IndentNestedKeywords:enabled=False",
"AlignSettingsSection:enabled=True",
"AlignVariablesSection:enabled=True",
"AlignTemplatedTestCases:enabled=False",
"AlignTestCasesSection:enabled=False",
"AlignKeywordsSection:enabled=False",
"NormalizeNewLines:enabled=True",
"NormalizeSectionHeaderName:enabled=True",
"NormalizeSettingName:enabled=True",
"ReplaceRunKeywordIf:enabled=True",
"SplitTooLongLine:enabled=True",
"SmartSortKeywords:enabled=False",
"RenameTestCases:enabled=False",
"RenameKeywords:enabled=False",
"ReplaceReturns:enabled=True",
"ReplaceBreakContinue:enabled=True",
"InlineIf:enabled=True",
"Translate:enabled=False",
"NormalizeComments:enabled=True",
]
By default configuration file will be save in the current working directory as ``pyproject.toml`` file. Default
filename can be configured::

robotidy --generate-config your_name.txt

Configuration is based on default values and configuration from the cli::

robotidy --transform ReplaceReturns --diff --generate-config

.. dropdown:: Generated file

.. code-block:: toml
[tool.robotidy]
diff = true
overwrite = true
verbose = false
separator = "space"
spacecount = 4
line_length = 120
lineseparator = "native"
skip_gitignore = false
ignore_git_dir = false
configure = [
"AddMissingEnd:enabled=False",
"NormalizeSeparators:enabled=False",
"DiscardEmptySections:enabled=False",
"MergeAndOrderSections:enabled=False",
"RemoveEmptySettings:enabled=False",
"ReplaceEmptyValues:enabled=False",
"NormalizeAssignments:enabled=False",
"GenerateDocumentation:enabled=False",
"OrderSettings:enabled=False",
"OrderSettingsSection:enabled=False",
"NormalizeTags:enabled=False",
"OrderTags:enabled=False",
"RenameVariables:enabled=False",
"IndentNestedKeywords:enabled=False",
"AlignSettingsSection:enabled=False",
"AlignVariablesSection:enabled=False",
"AlignTemplatedTestCases:enabled=False",
"AlignTestCasesSection:enabled=False",
"AlignKeywordsSection:enabled=False",
"NormalizeNewLines:enabled=False",
"NormalizeSectionHeaderName:enabled=False",
"NormalizeSettingName:enabled=False",
"ReplaceRunKeywordIf:enabled=False",
"SplitTooLongLine:enabled=False",
"SmartSortKeywords:enabled=False",
"RenameTestCases:enabled=False",
"RenameKeywords:enabled=False",
"ReplaceReturns:enabled=True",
"ReplaceBreakContinue:enabled=False",
"InlineIf:enabled=False",
"Translate:enabled=False",
"NormalizeComments:enabled=False",
]
Multiline configuration
------------------------
Transformers with multiple parameters can be configured in one line (each param delimited by ``:``) or in separate lines:
Expand Down
49 changes: 47 additions & 2 deletions robotidy/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

from robotidy import app
from robotidy import config as config_module
from robotidy import decorators, files, skip, utils, version
from robotidy import decorators, exceptions, files, skip, utils, version
from robotidy.config import RawConfig, csv_list_type, validate_target_version
from robotidy.rich_console import console
from robotidy.transformers import TransformConfigMap, TransformConfigParameter, load_transformers
Expand All @@ -37,7 +37,7 @@
},
{
"name": "Configuration",
"options": ["--configure", "--config", "--ignore-git-dir"],
"options": ["--configure", "--config", "--ignore-git-dir", "--generate-config"],
},
{
"name": "Global formatting settings",
Expand Down Expand Up @@ -186,6 +186,40 @@ def print_transformers_list(global_config: config_module.MainConfig):
)


def generate_config(global_config: config_module.MainConfig):
try:
import tomli_w
except ImportError:
raise exceptions.MissingOptionalTomliWDependencyError()
target_version = global_config.default.target_version
config = global_config.default_loaded
transformers = load_transformers(TransformConfigMap([], [], []), allow_disabled=True, target_version=target_version)
transformers.extend(_load_external_transformers(transformers, config.transformers_config, target_version))

toml_config = {
"tool": {
"robotidy": {
"diff": global_config.default_loaded.show_diff,
"overwrite": global_config.default_loaded.overwrite,
"verbose": global_config.default_loaded.verbose,
"separator": global_config.default.separator,
"spacecount": global_config.default_loaded.formatting.space_count,
"line_length": global_config.default.line_length,
"lineseparator": global_config.default.lineseparator,
"skip_gitignore": global_config.default.skip_gitignore,
"ignore_git_dir": global_config.default.ignore_git_dir,
}
}
}
configure_transformers = [
f"{transformer.name}:enabled={transformer.name in config.transformers_lookup}" for transformer in transformers
]
toml_config["tool"]["robotidy"]["configure"] = configure_transformers

with open(global_config.default.generate_config, "w") as fp:
fp.write(tomli_w.dumps(toml_config))


@click.command(context_settings=CONTEXT_SETTINGS)
@click.option(
"--transform",
Expand Down Expand Up @@ -367,6 +401,14 @@ def print_transformers_list(global_config: config_module.MainConfig):
help="List available transformers and exit. "
"Pass optional value **enabled** or **disabled** to filter out list by transformer status.",
)
@click.option(
"--generate-config",
is_flag=False,
default="",
flag_value="pyproject.toml",
help="Generate configuration file. Pass optional value to change default config filename.",
show_default="pyproject.toml",
)
@click.option(
"--desc",
"-d",
Expand Down Expand Up @@ -442,6 +484,9 @@ def cli(ctx: click.Context, **kwargs):
if global_config.default.desc is not None:
return_code = print_description(global_config.default.desc, global_config.default.target_version)
sys.exit(return_code)
if global_config.default.generate_config:
generate_config(global_config)
sys.exit(0)
tidy = app.Robotidy(global_config)
status = tidy.transform_files()
sys.exit(status)
3 changes: 2 additions & 1 deletion robotidy/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,7 @@ class RawConfig:
endline: int = None
line_length: int = 120
list_transformers: str = ""
generate_config: str = ""
desc: str = None
output: Path = None
force_order: bool = False
Expand Down Expand Up @@ -227,7 +228,7 @@ def __init__(self, cli_config: RawConfig):
self.sources = self.get_sources(self.default.src)

def validate_src_is_required(self):
if self.sources or self.default.list_transformers or self.default.desc:
if self.sources or self.default.list_transformers or self.default.desc or self.default.generate_config:
return
print("No source path provided. Run robotidy --help to see how to use robotidy")
sys.exit(1)
Expand Down
8 changes: 8 additions & 0 deletions robotidy/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,14 @@ def __init__(self):
super().__init__(msg)


class MissingOptionalTomliWDependencyError(RobotidyConfigError):
def __init__(self):
super().__init__(
f"Missing optional dependency: tomli_w. Install robotidy with extra `generate_config` "
f"profile:\n\npip install robotidy[generate_config]"
)


class NoSuchOptionError(NoSuchOption):
def __init__(self, option_name: str, allowed_options: List[str]):
rec_finder = utils.RecommendationFinder()
Expand Down
1 change: 1 addition & 0 deletions robotidy/transformers/ReplaceEmptyValues.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ class ReplaceEmptyValues(Transformer):
... value3
```
"""

HANDLES_SKIP = frozenset({"skip_sections"})

def __init__(self, skip: Skip = None):
Expand Down
2 changes: 2 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,13 +59,15 @@
"pylama",
"pytest",
"pre-commit",
"tomli_w==1.0.*",
],
"doc": [
"sphinx",
"furo",
"sphinx-design",
"sphinx-copybutton==0.5.2",
],
"generate_config": ["tomli_w==1.0.*"],
},
entry_points={"console_scripts": ["robotidy=robotidy.cli:cli"]},
)
Loading

0 comments on commit d8b9963

Please sign in to comment.