Skip to content

OUT_DIR is not cleaned #16332

@usamoi

Description

@usamoi

Problem

OUT_DIR is not cleaned before build scripts run, which is surprising.

Steps

build.rs:

use std::env::var_os;
use std::path::PathBuf;

fn main() {
    let out_dir = PathBuf::from(var_os("OUT_DIR").unwrap());
    {
        let r = std::fs::read_dir(&out_dir).unwrap();
        for x in r {
            dbg!(x.unwrap().file_name());
        }
    }
    std::fs::create_dir(out_dir.join("bits")).unwrap();
}

src/main.rs:

fn main() {}
  1. cargo run
  2. edit src/main.rs
  3. cargo run

Then cargo prints

error: failed to run custom build command for `hh v0.1.0 (/usamoi/playground/hh)`

Caused by:
  process didn't exit successfully: `/usamoi/playground/hh/target/debug/build/hh-6d5c061eda957f22/build-script-build` (exit status: 101)
  --- stderr
  [build.rs:9:13] x.unwrap().file_name() = "bits"

  thread 'main' (257176) panicked at build.rs:12:47:
  called `Result::unwrap()` on an `Err` value: Os { code: 17, kind: AlreadyExists, message: "File exists" }
  note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

This means that Cargo will not clean OUT_DIR before running build scripts, which is surprising! I cannot find any document about this behavior.

Possible Solution(s)

OUT_DIR should be cleaned before build scripts run.

Notes

No response

Version

cargo 1.91.1 (ea2d97820 2025-10-10)
release: 1.91.1
commit-hash: ea2d97820c16195b0ca3fadb4319fe512c199a43
commit-date: 2025-10-10
host: x86_64-unknown-linux-gnu
libgit2: 1.9.1 (sys:0.20.2 vendored)
libcurl: 8.15.0-DEV (sys:0.4.83+curl-8.15.0 vendored ssl:OpenSSL/3.5.2)
ssl: OpenSSL 3.5.2 5 Aug 2025
os: Arch Linux [64-bit]

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-build-scriptsArea: build.rs scriptsA-documenting-cargo-itselfArea: Cargo's documentationC-bugCategory: bugS-needs-mentorStatus: Issue or feature is accepted, but needs a team member to commit to helping and reviewing.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions