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

feat: add support for setting array element #34

Merged
merged 4 commits into from
Jun 26, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ continuous development steps.
## Set a value

`toml set --toml-path pyproject.toml tool.poetry.version 0.2.0`
`toml set --toml-path pyproject.toml tool.poetry.authors[0] "Marc Rijken <[email protected]>"`
limaa marked this conversation as resolved.
Show resolved Hide resolved

## Add a section

Expand Down
5 changes: 5 additions & 0 deletions tests/toml_cli/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ def test_set_value(tmp_path: pathlib.Path):
name = "MyName"
happy = false
age = 12
skills = ["python", "pip"]

[person.education]
name = "University"
Expand Down Expand Up @@ -115,6 +116,10 @@ def test_set_value(tmp_path: pathlib.Path):
assert result.exit_code == 0
assert 'addresses = ["Amsterdam", "London"]' in test_toml_path.read_text()

result = runner.invoke(app, ["set", "--toml-path", str(test_toml_path), "person.skills[1]", "toml"])
assert result.exit_code == 0
assert 'skills = ["python", "toml"]' in test_toml_path.read_text()


def test_add_section(tmp_path: pathlib.Path):
test_toml_path = tmp_path / "test.toml"
Expand Down
9 changes: 8 additions & 1 deletion toml_cli/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,14 @@ def set_(
if to_array:
value = json.loads(value)

toml_part[key.split(".")[-1]] = value
last_key = key.split(".")[-1]
match = re.search(r"(?P<table>.*?)\[(?P<index>\d+)\]", last_key)
if match:
table = match.group("table")
index = int(match.group("index"))
toml_part[table][index] = value
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you a descriptive message to the user when the table or index does not exists and exit with exit code 1

else:
toml_part[last_key] = value

toml_path.write_text(tomlkit.dumps(toml_file))

Expand Down