Skip to content

Commit 72c2743

Browse files
tunakasifLee-W
authored andcommitted
feat(providers): add support for Cargo.lock
If `Cargo.lock` file is present in the same path as the `Cargo.toml`, the version of the package will also be updated in the `Cargo.lock` file. The implementation is similar to the one used for `UvProvider`, which extends the `CargoProvider` to handle lock files. The change does not break any existing functionality, if the `Cargo.lock` file is not present, since it checks for the existence of the file before attempting a lock file update.
1 parent e177141 commit 72c2743

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

commitizen/providers/cargo_provider.py

+27
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
from __future__ import annotations
22

3+
from pathlib import Path
4+
35
import tomlkit
46

57
from commitizen.providers.base_provider import TomlProvider
@@ -13,6 +15,11 @@ class CargoProvider(TomlProvider):
1315
"""
1416

1517
filename = "Cargo.toml"
18+
lock_filename = "Cargo.lock"
19+
20+
@property
21+
def lock_file(self) -> Path:
22+
return Path() / self.lock_filename
1623

1724
def get(self, document: tomlkit.TOMLDocument) -> str:
1825
try:
@@ -28,3 +35,23 @@ def set(self, document: tomlkit.TOMLDocument, version: str):
2835
except tomlkit.exceptions.NonExistentKey:
2936
...
3037
document["package"]["version"] = version # type: ignore
38+
39+
def set_version(self, version: str) -> None:
40+
super().set_version(version)
41+
if self.lock_file.exists():
42+
self.set_lock_version(version)
43+
44+
def set_lock_version(self, version: str) -> None:
45+
cargo_toml_content = tomlkit.parse(self.file.read_text())
46+
try:
47+
package_name = cargo_toml_content["package"]["name"] # type: ignore
48+
except tomlkit.exceptions.NonExistentKey:
49+
package_name = cargo_toml_content["workspace"]["package"]["name"] # type: ignore
50+
51+
cargo_lock_content = tomlkit.parse(self.lock_file.read_text())
52+
packages: tomlkit.items.AoT = cargo_lock_content["package"] # type: ignore[assignment]
53+
for i, package in enumerate(packages):
54+
if package["name"] == package_name:
55+
cargo_lock_content["package"][i]["version"] = version # type: ignore[index]
56+
break
57+
self.lock_file.write_text(tomlkit.dumps(cargo_lock_content))

0 commit comments

Comments
 (0)