#! /usr/bin/env python3

### NOTE TO ANYONE USING THIS
# As of June 2019, `cargo +nightly build --offline` does a better job than this
# script. We don't need these hacks anymore :) Thanks Cargo Team!

from pathlib import Path

PACKAGE = """\
[[package]]
name = "{}"
version = "{}"
source = "registry+https://github.com/rust-lang/crates.io-index"

"""

crates = {}
srcdir = Path.home() / ".cargo/registry/src"
# For me there's only one subdir, "github.com-1ecc6299db9ec823".
for src_subdir in srcdir.iterdir():
    for entry in src_subdir.iterdir():
        name, version = entry.name.rsplit("-", 1)
        try:
            version_ints = [int(i) for i in version.split(".")]
        except ValueError:
            # If the version has "-alpha" or whatever, just skip it.
            continue
        # Find the latest version for each crate.
        if name not in crates or version_ints > crates[name][1]:
            crates[name] = (version, version_ints)

with open("Cargo.lock", "w") as f:
    # Sorted output order is nice in case we end up git-diff'ing these.
    for crate, (version, _) in sorted(crates.items()):
        f.write(PACKAGE.format(crate, version))
