Search code examples
rustrust-cargo

What files in a Cargo project should be in my .gitignore?


I created a "hello world" Rust app using cargo new. When I executed git status it showed a bunch of files:

A  rust/welcomec/Cargo.lock
A  rust/welcomec/Cargo.toml
A  rust/welcomec/src/main.rs
A  rust/welcomec/target/debug/.cargo-lock
A  rust/welcomec/target/debug/.fingerprint/welcomec-2d68725c8fae6fd1/bin-welcome-2d68725c8fae6fd1
A  rust/welcomec/target/debug/.fingerprint/welcomec-2d68725c8fae6fd1/bin-welcome-2d68725c8fae6fd1.json
A  rust/welcomec/target/debug/.fingerprint/welcomec-2d68725c8fae6fd1/dep-bin-welcome-2d68725c8fae6fd1
A  rust/welcomec/target/debug/deps/welcome-2d68725c8fae6fd1
A  rust/welcomec/target/debug/welcome
A  rust/welcomec/target/debug/welcome.d

Can I safely ignore any of these files and/or directories?


Solution

  • Summary

    .gitignore for executable crates

    # Generated files
    /target/
    

    .gitignore for library crates

    # Generated files
    /target/
    
    # Well, this depends... See below!
    Cargo.lock
    

    Details

    You can always ignore the target/ folder completely. It only contains generated files (e.g. compile artifacts) and is also usually quite large.

    If you are developing an executable program, then that's it already! Just a single entry.

    For library projects, you may also want to ignore Cargo.lock. But this is a bit more nuanced. The official stance on that matter was changed recently. Cargo.lock enables reproducible builds as it records the exact version of all dependencies. This is very useful. For executables you absolutely want those reproducible builds, hence the recommendation above.

    It is important to understand that if a project uses your library, your Cargo.lock is ignored! Cargo only cares about Cargo.toml of dependencies. So whether Cargo.lock is in your repository is basically only relevant for your development of the library.

    • On the one hand, you should always test your library with the latest version of all your dependencies. That's an argument against Cargo.lock.

    • On the other hand, Cargo.lock gives you the same benefit as in other projects: reproducible builds mean stable CI, easier bisecting, yada yada.

    In the end, you decide. But be assured: you can't really screw it up. Either way is usually fine.


    And note: cargo new should already create an appropriate .gitignore file for you.