Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

rewrite new toml-data will has a new whitespace line #352

Open
yanquer opened this issue May 17, 2024 · 0 comments
Open

rewrite new toml-data will has a new whitespace line #352

yanquer opened this issue May 17, 2024 · 0 comments

Comments

@yanquer
Copy link

yanquer commented May 17, 2024

rewrite toml data will has a new whitespace line.

eg toml:

toml

# xxx test


[env.pro1.rst]
    name = "x7"

[env2]
    name = 2

[env3]
    name = 3

modified with rewrite new tool data, like this

file_ = "test.toml"

def update_toml():
    with open(file_, "r") as f:
        t = tomlkit.load(f)

    t = merge_dicts(
        t,
        {'env': {'pro1': {'rst': {'name': "x7"}}}}
    )

    with open(file_, "w") as f:
        tomlkit.dump(t, f)

def merge_dicts(a: dict, b: dict):
    # ret = a.copy()
    ret = a

    for k, v in b.items():
        if k in a and isinstance(a[k], (dict, OrderedDict, Container)):
            ret[k] = merge_dicts(a[k], v)

    return ret

the result (has a new line after name = "x7")

# xxx test


[env.pro1.rst]
    name = "x7"


[env2]
    name = 2

[env3]
    name = 3

and if I edit in local with code

def merge_dicts(a: dict, b: dict):
    # ret = a.copy()
    return merge_dict_to_toml_local(a, b)


def merge_dict_to_toml_local(a: tomlkit.TOMLDocument, b: dict):

    for k, v in b.items():
        if k in a and isinstance(a[k], (dict, OrderedDict, Container)):
            merge_dict_to_toml_local(a[k], v)
        else:
            a[k] = v

There will be no more line.

I'm not sure if this is a bug, so I checked the source code.
in file tomlkit/container.py, line 703 with function _replace_at , it will add a whitespace-line where there is not has whitespace-line.
how check ? the end of tomlkit/container.py

def ends_with_whitespace(it: Any) -> bool:
    """Returns ``True`` if the given item ``it`` is a ``Table`` or ``AoT`` object
    ending with a ``Whitespace``.
    """
    return (
        isinstance(it, Table) and isinstance(it.value._previous_item(), Whitespace)
    ) or (isinstance(it, AoT) and len(it) > 0 and isinstance(it[-1], Whitespace))

ends_with_whitespace only check last and current without sub-tree.
Should subdata be checked ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant