Description
Problem
(That is an ugly title. Improvements welcome.)
Background
cargo init
has an obscure but convenient feature for small programs. Consider the following:
$ mkdir small
$ cd small
$ touch small.rs
$ cargo init --lib
This will produce a Cargo.toml
that looks like
[package]
name = "small"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
[lib]
name = "small"
path = "small.rs"
It will not produce src/lib.rs
in this case: everything is self-contained in a single directory. I find this quite convenient.
(Note that for this to work, the directory name and the source file name have to be spelled the same.)
Hyphens
OK, let's try this with a different name.
$ mkdir dashed-name
$ cd dashed-name
$ touch dashed-name.rs
$ cargo init --lib
We get a warning message this time:
warning: compiling this new package may not work due to invalid workspace configuration
failed to parse manifest at `/tmp/dashed-name/./Cargo.toml`
Caused by:
library target names cannot contain hyphens: dashed-name
Created library package
Sure enough, the generated Cargo.toml
now looks like this.
[package]
name = "dashed-name"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
[lib]
name = "dashed-name"
path = "dashed-name.rs"
And sure enough, trying to build using this will fail.
error: failed to parse manifest at `/tmp/dashed-name/Cargo.toml`
Caused by:
library target names cannot contain hyphens: dashed-name
Steps
See above.
Possible Solution(s)
In order of preference:
-
Omit
lib.name
from the generated declaration. It is not needed for libs anyhow. This will cause the hyphens to be defaulted to underscores when derivinglib.name
frompackage.name
. -
Replace hyphens with underscores when generating
lib.name
. -
Just get rid of this whole defaulted-source feature of
cargo init
. I really like it, and would prefer that it stay, but it may be more trouble than it's worth.
Notes
Vaguely relevant issues: #2775, #6827, #9333 (fixed, closed).
This issue does not affect cargo init --bin
, since hyphens are allowed in bin.name
. One could also not generate bin.name
in the case that there is only one bin
in the generated Cargo.toml, but that's a separate issue.
Version
cargo 1.64.0 (387270bc7 2022-09-16)
release: 1.64.0
commit-hash: 387270bc7f446d17869c7f208207c73231d6a252
commit-date: 2022-09-16
host: x86_64-unknown-linux-gnu
libgit2: 1.4.2 (sys:0.14.2 vendored)
libcurl: 7.83.1-DEV (sys:0.4.55+curl-7.83.1 vendored ssl:OpenSSL/1.1.1q)
os: Debian n/a [64-bit]