Check if the `Cargo.lock` is up to date without building anything

I'd like to put in git's pre-commit hook a quick check that makes sure that the Cargo.lock is up to date.

I do not however want to actually build anything as it can take a while. so cargo check --frozen is not ideal. Some kind of cargo check --frozen --dry-run would be great.

Any ideas what else could I use?

I haven't tried it myself, but the documentation suggests that cargo generate-lockfile --frozen is suitable for this purpose.

https://doc.rust-lang.org/cargo/commands/cargo-generate-lockfile.html

2 Likes

Thanks for pointing it out.

I played a bit with it now, and I'm very confused. It seems to be behaving somewhat like cargo update?

Let me explain in more details what I'm after:

Sometimes I'll make a change in Cargo.toml that is very trivial, and then just git commit -a && git push and since I never updated Cargo.lockby running cargo build to match by Cargo.tomls changes, now the CI might experience weird behavior (e.g. have to do the Cargo.lock change each time).

From what I can tell cargo generate-lockfile --frozen --offline and cargo generate-lockfile --frozen complain that "Cargo.lock needs to be updated", but when I actually run cargo build, Cargo.lock doesn't change. So somewhat like cargo update, it seems to want to do actual package updates (which github's dependabot takes care for us already).

So yeah - I'm only after ensuring Cargo.lock is matching current Cargo.toml, and not updating dependencies itself.

Coming at this particular part from the other direction, you could use cargo build --locked in CI to cause a rapid failure if Cargo.lock is out of date compared to Cargo.toml.

That doesn't fix the problem, but does mean that CI won't experience "weird behaviour", since CI will consistently fail due to out of date lockfiles.

cargo update -w --locked
  • The -w / --workspace is thety key element that shall make the Cargo.lock bump be as minimal as possible, much like cargo check/build/... do :slight_smile:

  • On older Cargo, I guess you could achieve the same by using -p your-own-package.

  • When dealing with multiple workspaces:

    find . -type f -name 'Cargo.lock' -print0 \
    | while IFS=$'\0' read -r -d '' file; do
        (set -x; cd "$(dirname "$file")" && cargo update -w --locked)
    done
    
  • When wanting to update (minimally), I recommend instead to replace --locked with -v: -w -v.

1 Like

Between my last post and now I did indeed add --locked in the CI.

Now I'm looking for something that would make this mistake surface faster, like in pre-commit hook.

This seems to work exactly like what I'm looking for. I would have never thought of it. Thanks a lot!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.