Exemple #1
0
def apply_before_dump(data: Any, rule: FormattingRule, text: str,
                      rules: dict) -> Any:
    forbid_in_block_mappings = DEFAULT.get("forbid-in-block-mappings")
    forbid_in_flow_mappings = DEFAULT.get("forbid-in-flow-mappings")
    if rule is not None:
        forbid_in_block_mappings = rule and rule.get(
            "forbid-in-block-mappings", forbid_in_block_mappings)
        forbid_in_flow_mappings = rule and rule.get("forbid-in-flow-mappings",
                                                    forbid_in_flow_mappings)

    if (rule is None or rule) and (forbid_in_block_mappings
                                   and forbid_in_flow_mappings):
        # no need to go through all of them
        # just represent them as `null`
        add_representer(type(None), represent_null, Dumper=RoundTripDumper)

        return data
    elif (rule is not None and not rule) or (not forbid_in_flow_mappings
                                             and not forbid_in_block_mappings):
        # no need to go through all of them
        # just represent them as ``
        add_representer(type(None),
                        represent_empty_null,
                        Dumper=RoundTripDumper)

        return data

    add_representer(Null, represent_null, Dumper=RoundTripDumper)
    add_representer(EmptyNull, represent_empty_null, Dumper=RoundTripDumper)

    return replace_empty_values(data, forbid_in_block_mappings,
                                forbid_in_flow_mappings)
Exemple #2
0
def apply_before_dump(data: Any, rule: FormattingRule, text: str,
                      rules: dict) -> Any:
    forbid_explicit_octal = DEFAULT.get("forbid-explicit-octal")
    forbid_implicit_octal = DEFAULT.get("forbid-implicit-octal")
    if rule is not None:
        forbid_explicit_octal = rule and rule.get("forbid-explicit-octal",
                                                  forbid_explicit_octal)
        forbid_implicit_octal = rule and rule.get("forbid-implicit-octal",
                                                  forbid_implicit_octal)

    if forbid_explicit_octal or forbid_implicit_octal:
        return format_octals(data, forbid_implicit_octal,
                             forbid_explicit_octal)
    return data
Exemple #3
0
def apply_on_result(result: str, original: str, rule: FormattingRule,
                    rules: dict) -> str:
    max_spaces_before = DEFAULT.get("max-spaces-before")
    max_spaces_after = DEFAULT.get("max-spaces-after")
    if rule:
        max_spaces_before = rule.get("max-spaces-before", max_spaces_before)
        max_spaces_after = rule.get("max-spaces-after", max_spaces_after)
    elif rule is not None:
        max_spaces_before = None
        max_spaces_after = None

    if max_spaces_before == 0 and max_spaces_after == 1:
        return result

    changes = False
    colon_map = {}

    for key, spaces_before, spaces_after, char_after in COLON_REGEX.findall(
            original):
        colon_map.setdefault(key, [])
        if max_spaces_before is None and max_spaces_after is None:
            count = SpaceCounts(len(spaces_before), len(spaces_after))
        else:
            count = SpaceCounts(
                min(max_spaces_before, len(spaces_before)),
                min(max_spaces_after, len(spaces_after)),
            )
        colon_map[key].append(count)
        if count[0] != 0 or count[1] > 1:
            changes = True
        else:
            has_line_break = char_after in ("\r", "\n")
            count_spaces_after = count[1]
            changes = (changes or (has_line_break and count_spaces_after != 0)
                       or (not has_line_break and count_spaces_after != 1))

    if not changes:
        return result

    for key, space_counts in colon_map.items():
        for count_spaces_before, count_spaces_after in space_counts:
            result = sub(
                r"(%s): ?([\r\n])?" % key,
                r"\g<1>%s:%s\g<2>" %
                (" " * count_spaces_before, " " * count_spaces_after),
                result,
                1,
            )

    return result
Exemple #4
0
def get_options(rule: FormattingRule) -> QuotedStringOptions:
    return QuotedStringOptions(
        quote_type=QUOTE_TYPES.get(
            rule.get("quote-type", DEFAULT.get("quote-type", "any")), ANY
        ),
        required=REQUIRED_MAP.get(rule.get("required", DEFAULT.get("required")), FALSE),
        extra_required=[
            compile(value)
            for value in rule.get("extra-required", DEFAULT.get("extra-required", []))
        ],
        extra_allowed=[
            compile(value)
            for value in rule.get("extra-allowed", DEFAULT.get("extra-allowed", []))
        ],
    )
Exemple #5
0
def apply_on_result(result: str, original: str, rule: FormattingRule,
                    rules: dict) -> str:
    min_spaces_after = DEFAULT.get("min-spaces-after")
    max_spaces_before = DEFAULT.get("max-spaces-before")
    max_spaces_after = DEFAULT.get("max-spaces-after")
    if rule:
        min_spaces_after = rule.get("min-spaces-after", min_spaces_after)
        max_spaces_before = rule.get("max-spaces-before", max_spaces_before)
        max_spaces_after = rule.get("max-spaces-after", max_spaces_after)
    elif rule is not None:
        min_spaces_after = None
        max_spaces_before = None
        max_spaces_after = None

    if max_spaces_before == 0 and min_spaces_after == 1 and max_spaces_after == 1:
        return result

    changes = False
    comma_map = {}
    for key, spaces_before, spaces_after in COMMA_REGEX.findall(original):
        comma_map.setdefault(key, [])
        if max_spaces_before is None and max_spaces_after is None:
            count = SpaceCounts(len(spaces_before), len(spaces_after))
        else:
            count = SpaceCounts(
                min(max_spaces_before, len(spaces_before)),
                max(min_spaces_after, min(max_spaces_after,
                                          len(spaces_after))),
            )

        comma_map[key].append(count)
        changes = changes or count != (0, 1)

    if not changes:
        return result

    for key, space_counts in comma_map.items():
        for count_spaces_before, count_spaces_after in space_counts:
            result = sub(
                r"(\"%s\"|'%s'|%s), " % (key, key, key),
                r"\g<1>%s,%s" %
                (" " * count_spaces_before, " " * count_spaces_after),
                result,
                1,
            )

    return result
Exemple #6
0
def apply_on_result(result: str, original: str, rule: FormattingRule,
                    rules: dict) -> str:
    original_line_break = "\r\n" if "\r\n" in original else "\n"
    line_break = "\r\n" if "\r\n" in result else "\n"
    original_prefix = extract_prefix(original).replace(original_line_break,
                                                       line_break)
    original_suffix = extract_suffix(original).replace(original_line_break,
                                                       line_break)

    if rule is not None and not rule:
        if original_prefix or original_suffix:
            length_end = count_newline_chars(reversed(result))
            if length_end:
                return replace_linebreaks(
                    original_prefix + result[:-length_end] + original_suffix,
                    line_break)

            return replace_linebreaks(
                original_prefix + result + original_suffix, line_break)

        return replace_linebreaks(result, line_break)

    max_start = DEFAULT.get("max-start")
    max_end = DEFAULT.get("max-end")
    max_all = DEFAULT.get("max")
    if rule is not None:
        max_start = rule.get("max-start", max_start)
        max_end = rule.get("max-end", max_end)
        max_all = rule.get("max")

    if max_start is None:
        max_start = max_all

    if max_end is None:
        max_end = max_all

    if original_prefix or original_suffix:
        length_end = count_newline_chars(reversed(result))
        return replace_linebreaks(
            original_prefix[:max_start * len(line_break)] +
            result[:-length_end] +
            original_suffix[:(max_end + 1) * len(line_break)],
            line_break,
        )
    return replace_linebreaks(result, line_break)
Exemple #7
0
def apply_before_load(text: str, rule: FormattingRule,
                      rules: dict) -> FormattingResult:
    width = DEFAULT.get("max", maxsize)
    if rule is not None:
        width = rule.get("max", width) if rule else maxsize

    return FormattingResult(text=text,
                            dumping_config={"width": width},
                            loading_config={})
Exemple #8
0
def apply_before_dump(data: Any, rule: FormattingRule, text: str,
                      rules: dict) -> Any:
    comment_starting_space = DEFAULT.get("require-starting-space")
    if rule is not None:
        comment_starting_space = rule and rule.get("require-starting-space",
                                                   comment_starting_space)

    if comment_starting_space:
        return format_comments(data)
    return data
Exemple #9
0
def get_line_break(text: str, rule: FormattingRule) -> str:
    new_line_type = DEFAULT.get("type")
    if rule is not None:
        new_line_type = rule.get("type", new_line_type) if rule else None

    if new_line_type == "unix":
        return "\n"
    elif new_line_type == "dos" or "\r\n" in text:
        return "\r\n"

    return "\n"
Exemple #10
0
def get_config(text: str, rule: FormattingRule) -> dict:
    indent = DEFAULT.get("spaces")
    block_seq_indent = DEFAULT.get("indent-sequences")
    if rule is not None:
        if not rule:
            indent = "consistent"
            block_seq_indent = True
        else:
            indent = rule.get("spaces", indent)
            block_seq_indent = rule.get("indent-sequences", block_seq_indent)

    if indent == "consistent":
        indent = find_first_indent(text) or 2

    if block_seq_indent:
        if indent:
            block_seq_indent = indent
        else:
            block_seq_indent = 2
    else:
        block_seq_indent = None

    return {"block_seq_indent": block_seq_indent, "indent": indent}
Exemple #11
0
def apply_before_dump(data: Any, rule: FormattingRule, text: str,
                      rules: dict) -> Any:
    if rule is not None and not rule:
        return data

    max_length = DEFAULT.get("max")
    if rule is not None:
        max_length = rule and rule.get("max", max_length)

    if max_length is not None:
        return fix_empty_lines(
            data, max_length,
            new_lines.get_line_break(text, rules.get(new_lines.ID)))
    return data
Exemple #12
0
def apply_before_load(text: str, rule: FormattingRule, rules: dict) -> FormattingResult:
    explicit_end = DEFAULT.get("present")
    if rule is not None:
        if not rule:
            explicit_end = None
        else:
            explicit_end = rule.get("present", explicit_end)

        # rule is disabled, leave current state
        if explicit_end is None:
            explicit_end = text.strip().endswith("...")

    return FormattingResult(
        text=text, dumping_config={"explicit_end": explicit_end}, loading_config={}
    )
Exemple #13
0
def apply_on_result(result: str, original: str, rule: FormattingRule,
                    rules: dict) -> str:
    max_spaces_after = DEFAULT.get("max-spaces-after")
    if rule:
        max_spaces_after = rule.get("max-spaces-after", max_spaces_after)
        if max_spaces_after == 1:
            return result
    elif rule is not None:
        max_spaces_after = 0

    changes = False
    hyphen_map = {}
    for line in original.replace("\r\n", "\n").split("\n"):
        match = CLEAN_UP_REGEX.search(line)
        if match:
            content = match.group(1)
            hyphen_map.setdefault(content, [])
            count = count_spaces_after_hyphens(line, max_spaces_after)
            hyphen_map[content].append(count)
            changes = changes or count > 1

    if not changes:
        return result

    fixed_lines = []
    line_break = get_line_break(original, rules.get(new_lines.ID))
    for line in result.replace("\r\n", "\n").split("\n"):
        match = CLEAN_UP_REGEX.search(line)
        if match:
            content = match.group(1)
            counts = hyphen_map.get(content, [])
            if counts and counts[0] > 1:
                fixed_lines.append(
                    REPLACEMENT_REGEX.sub(
                        r"\g<0>" + ((counts.pop(0) - 1) * " "), line))
            else:
                fixed_lines.append(line)
        else:
            fixed_lines.append(line)

    return line_break.join(fixed_lines)
Exemple #14
0
def get_options(rule: FormattingRule, rules: dict) -> BracketsOptions:
    return BracketsOptions(
        forbid=FORBID_MAP.get(rule.get("forbid", DEFAULT.get("forbid")), FALSE),
    )