Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
#!/usr/bin/env python
sync Pipfile dependency versions from Pipfile.lock
- Python >= 3.8
- tomlkit
import sys
import json
from typing import Dict, Union, Any
from argparse import ArgumentParser
from pathlib import Path
import tomlkit
from tomlkit.items import Table, InlineTable
def main() -> int:
parser = ArgumentParser(description=__doc__)
parser.add_argument("--dry-run", action="store_true")
parser.add_argument("--target", metavar='all|dev|nodev', default="all", help="target section")
parser.add_argument("--lockfile", default="Pipfile.lock", type=Path, help="Pipfile.lock")
parser.add_argument("--pipfile", default="Pipfile", type=Path, help="Pipfile (will be overwritten)")
args = parser.parse_args()
with as f:
pipfile = tomlkit.parse(
with as f:
pipfile_lock = json.load(f)
do_dev: bool
do_nodev: bool
if == "all":
do_dev = True
do_nodev = True
elif == "dev":
do_dev = True
do_nodev = False
elif == "nodev":
do_dev = False
do_nodev = True
print(f"error: --target must be one of ['all', 'dev', 'nodev']", file=sys.stderr)
return 1
if do_dev:
update_packages(pipfile["dev-packages"], {**pipfile_lock["default"], **pipfile_lock.get("develop", {})})
if do_nodev:
update_packages(pipfile["packages"], pipfile_lock["default"])
if not args.dry_run:
with"w") as f:
print(tomlkit.dumps(pipfile), file=sys.stdout)
return 0
def update_packages(packages: Table, locked_packages: Dict[str, Dict[str, Union[str, Dict[str, Any]]]]) -> None:
for pname in packages:
pbody = packages[pname]
if pname not in locked_packages:
print(f"""WARNING: "{pname}" entry not exists in Pipfile.lock""", file=sys.stderr)
locked_body = locked_packages[pname]
if "version" not in locked_body:
print(f"""WARNING: "{pname}" version not exists in Pipfile.lock""", file=sys.stderr)
locked_version = locked_body["version"]
if isinstance(pbody, str):
orig_version = pbody
packages[pname] = locked_version
elif isinstance(pbody, InlineTable) and "version" in pbody:
orig_version = pbody["version"]
pbody["version"] = locked_version
packages[pname] = pbody
print(f"""WARNING: {pname} cannot idetify orignial format Pipfile""", file=sys.stderr)
print(f"""{pname}{locked_version} """ + ("(not changd)" if orig_version == locked_version else f"(update from {orig_version})"), file=sys.stderr)
if __name__ == '__main__':
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment