Skip to content

Instantly share code, notes, and snippets.

@nl5887
Last active June 16, 2023 09:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nl5887/08e9820654152ce50be9df58c1ea3263 to your computer and use it in GitHub Desktop.
Save nl5887/08e9820654152ce50be9df58c1ea3263 to your computer and use it in GitHub Desktop.
Update cargo.toml dependencies recursively
import os
import toml
import argparse
parser = argparse.ArgumentParser(description='Update cargo toml module path')
parser.add_argument('--module', metavar='m', type=str, required=True)
parser.add_argument('--work-dir', type=str, default='.')
parser.add_argument('--version', type=str)
parser.add_argument('--path', type=str)
parser.add_argument('--ref', type=str)
parser.add_argument('--dry', action='store_true')
parser.add_argument('--no-dry', dest='dry', action='store_false')
parser.set_defaults(dry=True)
def main() -> int:
args = parser.parse_args()
for subdir, dirs, files in os.walk(args.work_dir):
for file in files:
if file != "Cargo.toml":
continue
p = (os.path.join(subdir, file))
d = toml.load(p)
module = args.module
if d.get('dependencies', {}).get(module) is None:
continue
if args.ref:
c = d.get('dependencies', {}).get(module)
rest = {k: v for k, v in c.items() if k not in ['path']}
d['dependencies'][module] = {
**(rest or {}),
'ref': args.ref,
}
if args.path:
c = d.get('dependencies', {}).get(module)
rest = {k: v for k, v in c.items() if k not in ['git', 'ref']}
d['dependencies'][module] = {
**(rest or {}),
'path': args.path,
}
if args.version:
c = d.get('dependencies', {}).get(module)
rest = {k: v for k, v in c.items()}
d['dependencies'][module] = {
**(rest or {}),
'version': args.version,
}
if args.dry:
toml.dumps(d, encoder=None)
else:
with open(p, 'w') as f:
toml.dump(d, f, encoder=None)
print(f"Updated {p}.")
if __name__ == '__main__':
import sys
sys.exit(main()) # next section explains the use of sys.exit
@nl5887
Copy link
Author

nl5887 commented Jun 10, 2022

If you need to test some dependencies locally, in large projects, you need to make sure you've updated all Cargo.tomls with correct version. This script will recursively update the dependency. You can also use the script to bump versions of dependencies easily.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment