Skip to content

Commit

Permalink
Refactor utils imports to be more explicit
Browse files Browse the repository at this point in the history
  • Loading branch information
bhirsz committed Nov 18, 2023
1 parent 0092a6f commit ac0a6d5
Show file tree
Hide file tree
Showing 37 changed files with 174 additions and 159 deletions.
18 changes: 8 additions & 10 deletions robotidy/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@
from robot.api import get_model
from robot.errors import DataError

from robotidy import utils
from robotidy.config import MainConfig
from robotidy.disablers import RegisterDisablers
from robotidy.rich_console import console
from robotidy.utils import misc


class Robotidy:
Expand All @@ -23,7 +23,7 @@ def __init__(self, main_config: "MainConfig"):
self.config = main_config.default_loaded

def get_model(self, source):
if utils.rf_supports_lang():
if misc.rf_supports_lang():
return get_model(source, lang=self.config.language)
return get_model(source)

Expand Down Expand Up @@ -76,11 +76,11 @@ def transform_until_stable(self, model, disabler_finder):
return diff, old_model, new_model, model

def transform(self, model, disablers):
old_model = utils.StatementLinesCollector(model)
old_model = misc.StatementLinesCollector(model)
for transformer in self.config.transformers:
setattr(transformer, "disablers", disablers) # set dynamically to allow using external transformers
transformer.visit(model)
new_model = utils.StatementLinesCollector(model)
new_model = misc.StatementLinesCollector(model)
return new_model != old_model, old_model, new_model

@staticmethod
Expand All @@ -94,7 +94,7 @@ def print_to_stdout(self, collected_lines):
def save_model(self, source, model):
if self.config.overwrite:
output = self.config.output or source
utils.ModelWriter(output=output, newline=self.get_line_ending(source)).write(model)
misc.ModelWriter(output=output, newline=self.get_line_ending(source)).write(model)

def get_line_ending(self, path: str):
if self.config.formatting.line_sep == "auto":
Expand All @@ -108,9 +108,7 @@ def get_line_ending(self, path: str):
return f.newlines[0]
return self.config.formatting.line_sep

def output_diff(
self, path: str, old_model: utils.StatementLinesCollector, new_model: utils.StatementLinesCollector
):
def output_diff(self, path: str, old_model: misc.StatementLinesCollector, new_model: misc.StatementLinesCollector):
if not self.config.show_diff:
return
old = [l + "\n" for l in old_model.text.splitlines()]
Expand All @@ -119,8 +117,8 @@ def output_diff(
if not lines:
return
if self.config.color:
output = utils.decorate_diff_with_color(lines)
output = misc.decorate_diff_with_color(lines)
else:
output = utils.escape_rich_markup(lines)
output = misc.escape_rich_markup(lines)
for line in output:
console.print(line, end="", highlight=False, soft_wrap=True)
9 changes: 5 additions & 4 deletions robotidy/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,11 @@

from robotidy import app
from robotidy import config as config_module
from robotidy import decorators, exceptions, files, skip, utils, version
from robotidy import decorators, exceptions, files, skip, 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
from robotidy.utils import misc

CLI_OPTIONS_LIST = [
{
Expand Down Expand Up @@ -89,7 +90,7 @@


def validate_regex_callback(ctx: click.Context, param: click.Parameter, value: Optional[str]) -> Optional[Pattern]:
return utils.validate_regex(value)
return misc.validate_regex(value)


def validate_target_version_callback(
Expand Down Expand Up @@ -131,7 +132,7 @@ def print_description(name: str, target_version: int):
elif name in transformer_by_names:
print_transformer_docs(transformer_by_names[name])
else:
rec_finder = utils.RecommendationFinder()
rec_finder = misc.RecommendationFinder()
similar = rec_finder.find_similar(name, transformer_by_names.keys())
click.echo(f"Transformer with the name '{name}' does not exist.{similar}")
return 1
Expand Down Expand Up @@ -433,7 +434,7 @@ def generate_config(global_config: config_module.MainConfig):
@click.option(
"--target-version",
"-tv",
type=click.Choice([v.name.lower() for v in utils.TargetVersion], case_sensitive=False),
type=click.Choice([v.name.lower() for v in misc.TargetVersion], case_sensitive=False),
callback=validate_target_version_callback,
help="Only enable transformers supported in set target version",
show_default="installed Robot Framework version",
Expand Down
15 changes: 8 additions & 7 deletions robotidy/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,9 @@
import click
from click.core import ParameterSource

from robotidy import exceptions, files, skip, utils
from robotidy import exceptions, files, skip
from robotidy.transformers import TransformConfig, TransformConfigMap, convert_transform_config, load_transformers
from robotidy.utils import misc


class FormattingConfig:
Expand Down Expand Up @@ -67,12 +68,12 @@ def get_line_sep(line_sep):

def validate_target_version(value: Optional[str]) -> Optional[int]:
if value is None:
return utils.ROBOT_VERSION.major
target_version = utils.TargetVersion[value.upper()].value
if target_version > utils.ROBOT_VERSION.major:
return misc.ROBOT_VERSION.major
target_version = misc.TargetVersion[value.upper()].value
if target_version > misc.ROBOT_VERSION.major:
raise click.BadParameter(
f"Target Robot Framework version ({target_version}) should not be higher than "
f"installed version ({utils.ROBOT_VERSION})."
f"installed version ({misc.ROBOT_VERSION})."
)
return target_version

Expand Down Expand Up @@ -142,7 +143,7 @@ class RawConfig:
desc: str = None
output: Path = None
force_order: bool = False
target_version: int = utils.ROBOT_VERSION.major
target_version: int = misc.ROBOT_VERSION.major
language: List[str] = field(default_factory=list)
reruns: int = 0
ignore_git_dir: bool = False
Expand Down Expand Up @@ -197,7 +198,7 @@ def from_config_file(self, config: Dict, config_path: Path) -> "RawConfig":
elif key == "src":
parsed_config[key] = tuple(value)
elif value_type == Pattern:
parsed_config[key] = utils.validate_regex(value)
parsed_config[key] = misc.validate_regex(value)
else:
parsed_config[key] = value
parsed_config["defined_in_config"].add(key)
Expand Down
4 changes: 2 additions & 2 deletions robotidy/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

from click import NoSuchOption

from robotidy import utils
from robotidy.utils import misc


class RobotidyConfigError(Exception):
Expand Down Expand Up @@ -52,6 +52,6 @@ def __init__(self):

class NoSuchOptionError(NoSuchOption):
def __init__(self, option_name: str, allowed_options: List[str]):
rec_finder = utils.RecommendationFinder()
rec_finder = misc.RecommendationFinder()
similar = rec_finder.find(option_name, allowed_options)
super().__init__(option_name, possibilities=similar)
2 changes: 1 addition & 1 deletion robotidy/skip.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import click
from robot.api import Token

from robotidy.utils import normalize_name
from robotidy.utils.misc import normalize_name


def parse_csv(value):
Expand Down
10 changes: 5 additions & 5 deletions robotidy/transformers/AlignSettingsSection.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

from robotidy.disablers import skip_section_if_disabled
from robotidy.transformers import Transformer
from robotidy.utils import is_blank_multiline, left_align, round_to_four, tokens_by_lines
from robotidy.utils import misc


class AlignSettingsSection(Transformer):
Expand Down Expand Up @@ -84,9 +84,9 @@ def visit_SettingSection(self, node): # noqa
if self.disablers.is_node_disabled(child):
statements.append(child)
elif child.type in (Token.EOL, Token.COMMENT):
statements.append(left_align(child))
statements.append(misc.left_align(child))
else:
statements.append(list(tokens_by_lines(child)))
statements.append(list(misc.tokens_by_lines(child)))
nodes_to_be_aligned = [st for st in statements if isinstance(st, list)]
if not nodes_to_be_aligned:
return node
Expand All @@ -110,7 +110,7 @@ def align_rows(self, statements, look_up):
is_library, indent_args = self.should_indent_arguments(st)
aligned_statement = []
for line in st:
if is_blank_multiline(line):
if misc.is_blank_multiline(line):
line[-1].value = line[-1].value.lstrip(" \t") # normalize eol from ' \n' to '\n'
aligned_statement.extend(line)
continue
Expand Down Expand Up @@ -163,4 +163,4 @@ def create_look_up(self, statements):
look_up[index] = max(look_up[index], len(token.value))
if self.min_width:
look_up = {index: max(length, self.min_width - 4) for index, length in look_up.items()}
return {index: round_to_four(length) for index, length in look_up.items()}
return {index: misc.round_to_four(length) for index, length in look_up.items()}
6 changes: 3 additions & 3 deletions robotidy/transformers/AlignTemplatedTestCases.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

from robotidy.disablers import skip_if_disabled, skip_section_if_disabled
from robotidy.transformers import Transformer
from robotidy.utils import is_suite_templated, round_to_four
from robotidy.utils import misc


class AlignTemplatedTestCases(Transformer):
Expand Down Expand Up @@ -61,7 +61,7 @@ def __init__(self, only_with_headers: bool = False, min_width: int = None):
self.indent = 0

def visit_File(self, node): # noqa
if not is_suite_templated(node):
if not misc.is_suite_templated(node):
return node
self.test_without_eol = False
return self.generic_visit(node)
Expand Down Expand Up @@ -166,7 +166,7 @@ def visit_TestCaseSection(self, node): # noqa
self.generic_visit(node)
if not self.header_with_cols and not self.any_one_line_test and self.widths:
self.widths[0] = 0
self.widths = [round_to_four(length) for length in self.widths]
self.widths = [misc.round_to_four(length) for length in self.widths]

def visit_TestCase(self, node): # noqa
for statement in node.body:
Expand Down
2 changes: 1 addition & 1 deletion robotidy/transformers/AlignTestCasesSection.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from robotidy.disablers import skip_if_disabled
from robotidy.skip import Skip
from robotidy.transformers.aligners_core import AlignKeywordsTestsSection
from robotidy.utils import is_suite_templated
from robotidy.utils.misc import is_suite_templated


class AlignTestCasesSection(AlignKeywordsTestsSection):
Expand Down
10 changes: 5 additions & 5 deletions robotidy/transformers/AlignVariablesSection.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from robotidy.disablers import skip_section_if_disabled
from robotidy.exceptions import InvalidParameterValueError
from robotidy.transformers import Transformer
from robotidy.utils import is_blank_multiline, left_align, round_to_four, tokens_by_lines
from robotidy.utils import misc


class AlignVariablesSection(Transformer):
Expand Down Expand Up @@ -79,9 +79,9 @@ def visit_VariableSection(self, node): # noqa
if self.disablers.is_node_disabled(child):
statements.append(child)
elif child.type in (Token.EOL, Token.COMMENT):
statements.append(left_align(child))
statements.append(misc.left_align(child))
elif self.should_parse(child):
statements.append(list(tokens_by_lines(child)))
statements.append(list(misc.tokens_by_lines(child)))
else:
statements.append(child)
nodes_to_be_aligned = [st for st in statements if isinstance(st, list)]
Expand All @@ -99,7 +99,7 @@ def align_rows(self, statements, look_up):
continue
aligned_statement = []
for line in st:
if is_blank_multiline(line):
if misc.is_blank_multiline(line):
line[-1].value = line[-1].value.lstrip(" \t") # normalize eol from ' \n' to '\n'
aligned_statement.extend(line)
continue
Expand Down Expand Up @@ -133,4 +133,4 @@ def create_look_up(self, statements):
look_up[index] = max(look_up[index], len(token.value))
if self.min_width:
look_up = {index: max(length, self.min_width - 4) for index, length in look_up.items()}
return {index: round_to_four(length) for index, length in look_up.items()}
return {index: misc.round_to_four(length) for index, length in look_up.items()}
Loading

0 comments on commit ac0a6d5

Please sign in to comment.