rust-lang/cargo · error

a Cargo.lock must exist for this command

Error message

a Cargo.lock must exist for this command

What it means

Thrown by `cargo pkgid` when no `Cargo.lock` file exists in the workspace. The `pkgid` command resolves a PackageIdSpec by querying the dependency graph from the lockfile, so a lockfile is a hard prerequisite.

Solutions

  1. Run `cargo generate-lockfile` or `cargo fetch` to create Cargo.lock first.
  2. Run `cargo build` which generates the lockfile as a side effect.
  3. Ensure Cargo.lock is not deleted by CI or build scripts.

Example fix

# Generate the lockfile, then run pkgid
cargo generate-lockfile
cargo pkgid
Defensive patterns

Strategy: validation

Validate before calling

use std::path::Path;
fn ensure_lockfile_exists(ws_root: &Path) -> Result<(), String> {
    let lockfile = ws_root.join("Cargo.lock");
    if !lockfile.is_file() {
        return Err("Cargo.lock not found; run `cargo generate-lockfile` first".into());
    }
    Ok(())
}

Prevention

When it happens

Trigger: Running `cargo pkgid` (or `cargo pkgid <spec>`) in a workspace that has never been built or had its lockfile generated, or where `Cargo.lock` was deleted.

Common situations: Fresh checkout where `cargo build` has not been run; a library crate where `Cargo.lock` is gitignored and not present; running `cargo pkgid` before any dependency-resolving command.

Related errors


AI-assisted analysis of rust-lang/cargo@eb98b54bc9 (2026-08-11). Data as JSON: /api/errors/961e175dab24b3ae. Report an issue: GitHub.

Appendix: source

Thrown at src/ops/cargo_pkgid.rs:7

use crate::ops;
use crate::util::CargoResult;
use crate::workspace::{PackageIdSpec, PackageIdSpecQuery, Workspace};

pub fn pkgid(ws: &Workspace<'_>, spec: Option<&str>) -> CargoResult<PackageIdSpec> {
    let Some(resolve) = ops::load_pkg_lockfile(ws)? else {
        anyhow::bail!("a Cargo.lock must exist for this command")
    };

    let pkgid = match spec {
        Some(spec) => PackageIdSpec::query_str(spec, resolve.iter())?,
        None => ws.current()?.package_id(),
    };
    Ok(pkgid.to_spec())
}

View on GitHub (pinned to eb98b54bc9)