|
| 1 | +import argparse |
| 2 | +from pathlib import Path |
| 3 | +import sys |
| 4 | +import re |
| 5 | + |
| 6 | +VER_PATTERN = re.compile(r'^version = "(\d+)\.(\d+)\.(\d+)[^"]*" # auto', re.MULTILINE) |
| 7 | +VER_REPLACE = 'version = "%d.%d.%d" # auto' |
| 8 | +COMPONENTS = ("major", "minor", "patch") |
| 9 | + |
| 10 | + |
| 11 | +class Updater: |
| 12 | + component: str = "patch" |
| 13 | + |
| 14 | + @staticmethod |
| 15 | + def replace(match: re.Match[str]) -> str: |
| 16 | + ver = [int(x) for x in match.groups()[: len(COMPONENTS)]] |
| 17 | + for _ in range(len(ver) - 1, len(COMPONENTS)): |
| 18 | + ver.append(0) |
| 19 | + print("old version:", ".".join([str(x) for x in ver])) |
| 20 | + index = COMPONENTS.index(Updater.component) |
| 21 | + ver[index] += 1 |
| 22 | + for i in range(index + 1, 3): |
| 23 | + ver[i] = 0 |
| 24 | + print("new version:", ".".join([str(x) for x in ver])) |
| 25 | + return VER_REPLACE % tuple(ver) |
| 26 | + |
| 27 | + |
| 28 | +def main(): |
| 29 | + parser = argparse.ArgumentParser() |
| 30 | + parser.add_argument("component", default="patch", choices=COMPONENTS) |
| 31 | + parser.parse_args(namespace=Updater) |
| 32 | + cargo_path = Path("Cargo.toml") |
| 33 | + doc = cargo_path.read_text(encoding="utf-8") |
| 34 | + doc = VER_PATTERN.sub(Updater.replace, doc) |
| 35 | + cargo_path.write_text(doc, encoding="utf-8", newline="\n") |
| 36 | + print("Updated version in Cargo.toml") |
| 37 | + return 0 |
| 38 | + |
| 39 | + |
| 40 | +if __name__ == "__main__": |
| 41 | + sys.exit(main()) |
0 commit comments