|
| 1 | +import argparse |
| 2 | +import glob |
| 3 | +import os |
| 4 | + |
| 5 | +import toml |
| 6 | + |
| 7 | + |
| 8 | +def dir_path(path): |
| 9 | + if os.path.isdir(path): |
| 10 | + return path |
| 11 | + else: |
| 12 | + raise NotADirectoryError(path) |
| 13 | + |
| 14 | + |
| 15 | +def append_label_to_cargo_toml_version(cargo_toml_path, label: str, dry_run: bool): |
| 16 | + cargo_toml = toml.load(cargo_toml_path) |
| 17 | + print(f"Editing {cargo_toml_path} ...") |
| 18 | + |
| 19 | + if 'package' not in cargo_toml: |
| 20 | + print("No package section (probably a workspace file), skipping this Cargo.toml") |
| 21 | + return |
| 22 | + |
| 23 | + new_version = f"{cargo_toml['package']['version'].split('-', 1)[0]}-{label}" |
| 24 | + print(f"{cargo_toml_path} new version: {new_version}") |
| 25 | + |
| 26 | + if not dry_run: |
| 27 | + cargo_toml['package']['version'] = new_version |
| 28 | + |
| 29 | + with open(cargo_toml_path, "w") as f: |
| 30 | + toml.dump(cargo_toml, f) |
| 31 | + |
| 32 | + |
| 33 | +def main(args): |
| 34 | + workdir = os.path.relpath(args.working_dir) |
| 35 | + print(f"Searching for Cargo.toml(s) in '{workdir}' to edit their version label ...") |
| 36 | + |
| 37 | + cargo_tomls = glob.glob(f"{workdir}/**/Cargo.toml", recursive=True) |
| 38 | + print(f"Cargo.toml(s) found: {cargo_tomls}") |
| 39 | + |
| 40 | + for cargo_toml in cargo_tomls: |
| 41 | + append_label_to_cargo_toml_version(cargo_toml, args.semver_label, args.dry_run) |
| 42 | + |
| 43 | + |
| 44 | +if __name__ == '__main__': |
| 45 | + parser = argparse.ArgumentParser( |
| 46 | + prog="Cargo.toml semver label editor", |
| 47 | + description="Edit all Cargo.toml in the given path and subdirectories by replacing their label with the given" |
| 48 | + " '--semver-label'.") |
| 49 | + parser.add_argument("-l", "--semver-label", required=True, |
| 50 | + help="Label to suffix to the Cargo.toml(s) semver version") |
| 51 | + parser.add_argument("-d", "--working-dir", type=dir_path, default="./", |
| 52 | + help="Directory in which Cargo.toml will be searched") |
| 53 | + parser.add_argument("--dry-run", action="store_true") |
| 54 | + |
| 55 | + main(parser.parse_args()) |
0 commit comments