]> git.proxmox.com Git - cargo.git/blame - src/doc/src/reference/manifest.md
Auto merge of #6925 - ehuss:package-include-manifest, r=alexcrichton
[cargo.git] / src / doc / src / reference / manifest.md
CommitLineData
4d590f95
BE
1## The Manifest Format
2
79d10021
BE
3The `Cargo.toml` file for each package is called its *manifest*. Every manifest
4file consists of one or more sections.
5
4d590f95
BE
6### The `[package]` section
7
8The first section in a `Cargo.toml` is `[package]`.
9
10```toml
11[package]
12name = "hello_world" # the name of the package
13version = "0.1.0" # the current version, obeying semver
59f35af8 14authors = ["Alice <a@example.com>", "Bob <b@example.com>"]
4d590f95
BE
15```
16
e2074dfb
EH
17#### The `name` field
18
19The package name is an identifier used to refer to the package. It is used
20when listed as a dependency in another package, and as the default name of
21inferred lib and bin targets.
22
23The name must not be empty, use only [alphanumeric] characters or `-` or `_`.
24Note that `cargo new` and `cargo init` impose some additional restrictions on
25the package name, such as enforcing that it is a valid Rust identifier and not
26a keyword. [crates.io][cratesio] imposes even more restrictions, such as
27enforcing only ASCII characters, not a reserved name, not a special Windows
28name such as "nul", is not too long, etc.
29
b54748ef 30[alphanumeric]: ../std/primitive.char.html#method.is_alphanumeric
4d590f95
BE
31
32#### The `version` field
33
34Cargo bakes in the concept of [Semantic
0c3851c0 35Versioning](https://semver.org/), so make sure you follow some basic rules:
4d590f95
BE
36
37* Before you reach 1.0.0, anything goes, but if you make breaking changes,
38 increment the minor version. In Rust, breaking changes include adding fields to
39 structs or variants to enums.
40* After 1.0.0, only make breaking changes when you increment the major version.
41 Don’t break the build.
57b3e131 42* After 1.0.0, don’t add any new public API (no new `pub` anything) in patch-level
4d590f95
BE
43 versions. Always increment the minor version if you add any new `pub` structs,
44 traits, fields, types, functions, methods or anything else.
45* Use version numbers with three numeric parts such as 1.0.0 rather than 1.0.
46
e2074dfb
EH
47#### The `authors` field (optional)
48
49The `authors` field lists people or organizations that are considered the
50"authors" of the package. The exact meaning is open to interpretation — it may
51list the original or primary authors, current maintainers, or owners of the
52package. These names will be listed on the crate's page on
53[crates.io][cratesio]. An optional email address may be included within angled
54brackets at the end of each author.
55
3d029039
AC
56#### The `edition` field (optional)
57
58You can opt in to a specific Rust Edition for your package with the
f7c91ba6 59`edition` key in `Cargo.toml`. If you don't specify the edition, it will
3d029039
AC
60default to 2015.
61
62```toml
63[package]
64# ...
65edition = '2018'
66```
67
68The `edition` key affects which edition your package is compiled with. Cargo
4a8bd29f 69will always generate packages via `cargo new` with the `edition` key set to the
3d029039
AC
70latest edition. Setting the `edition` key in `[package]` will affect all
71targets/crates in the package, including test suites, benchmarks, binaries,
72examples, etc.
73
4d590f95
BE
74#### The `build` field (optional)
75
4a8bd29f 76This field specifies a file in the package root which is a [build script][1] for
4d590f95
BE
77building native code. More information can be found in the build script
78[guide][1].
79
3f2d93e3 80[1]: reference/build-scripts.html
4d590f95
BE
81
82```toml
83[package]
84# ...
85build = "build.rs"
86```
87
3fb15acf
DW
88#### The `links` field (optional)
89
88d5313c 90This field specifies the name of a native library that is being linked to.
3fb15acf
DW
91More information can be found in the [`links`][links] section of the build
92script guide.
93
94[links]: reference/build-scripts.html#the-links-manifest-key
95
96```toml
97[package]
98# ...
99links = "foo"
100build = "build.rs"
101```
102
4d590f95
BE
103#### The `documentation` field (optional)
104
105This field specifies a URL to a website hosting the crate's documentation.
106If no URL is specified in the manifest file, [crates.io][cratesio] will
107automatically link your crate to the corresponding [docs.rs][docsrs] page.
108
109Documentation links from specific hosts are blacklisted. Hosts are added
110to the blacklist if they are known to not be hosting documentation and are
f7c91ba6 111possibly of malicious intent e.g., ad tracking networks. URLs from the
4d590f95 112following hosts are blacklisted:
917c3634
BE
113
114* rust-ci.org
4d590f95
BE
115
116Documentation URLs from blacklisted hosts will not appear on crates.io, and
117may be replaced by docs.rs links.
118
119[docsrs]: https://docs.rs/
120[cratesio]: https://crates.io/
121
122#### The `exclude` and `include` fields (optional)
123
124You can explicitly specify to Cargo that a set of [globs][globs] should be
125ignored or included for the purposes of packaging and rebuilding a package. The
126globs specified in the `exclude` field identify a set of files that are not
127included when a package is published as well as ignored for the purposes of
128detecting when to rebuild a package, and the globs in `include` specify files
129that are explicitly included.
130
131If a VCS is being used for a package, the `exclude` field will be seeded with
132the VCS’ ignore settings (`.gitignore` for git for example).
133
134```toml
135[package]
136# ...
137exclude = ["build/**/*.o", "doc/**/*.html"]
138```
139
140```toml
141[package]
142# ...
143include = ["src/**/*", "Cargo.toml"]
144```
145
146The options are mutually exclusive: setting `include` will override an
147`exclude`. Note that `include` must be an exhaustive list of files as otherwise
49e37f80
EH
148necessary source files may not be included. The package's `Cargo.toml` is
149automatically included.
4d590f95 150
d4b5038d 151[globs]: https://docs.rs/glob/0.2.11/glob/struct.Pattern.html
4d590f95
BE
152
153#### Migrating to `gitignore`-like pattern matching
154
155The current interpretation of these configs is based on UNIX Globs, as
156implemented in the [`glob` crate](https://crates.io/crates/glob). We want
157Cargo's `include` and `exclude` configs to work as similar to `gitignore` as
158possible. [The `gitignore` specification](https://git-scm.com/docs/gitignore) is
159also based on Globs, but has a bunch of additional features that enable easier
160pattern writing and more control. Therefore, we are migrating the interpretation
161for the rules of these configs to use the [`ignore`
162crate](https://crates.io/crates/ignore), and treat them each rule as a single
163line in a `gitignore` file. See [the tracking
164issue](https://github.com/rust-lang/cargo/issues/4268) for more details on the
165migration.
166
167#### The `publish` field (optional)
168
169The `publish` field can be used to prevent a package from being published to a
467f878f
DW
170package registry (like *crates.io*) by mistake, for instance to keep a package
171private in a company.
4d590f95
BE
172
173```toml
174[package]
175# ...
176publish = false
177```
178
737382d7
EH
179The value many also be an array of strings which are registry names that are
180allowed to be published to.
181
182```toml
183[package]
184# ...
185publish = ["some-registry-name"]
186```
187
4d590f95
BE
188#### The `workspace` field (optional)
189
190The `workspace` field can be used to configure the workspace that this package
191will be a member of. If not specified this will be inferred as the first
192Cargo.toml with `[workspace]` upwards in the filesystem.
193
194```toml
195[package]
196# ...
917c3634 197workspace = "path/to/workspace/root"
4d590f95
BE
198```
199
200For more information, see the documentation for the workspace table below.
201
202#### Package metadata
203
204There are a number of optional metadata fields also accepted under the
205`[package]` section:
206
207```toml
208[package]
209# ...
210
211# A short blurb about the package. This is not rendered in any format when
212# uploaded to crates.io (aka this is not markdown).
213description = "..."
214
917c3634 215# These URLs point to more information about the package. These are
4d590f95
BE
216# intended to be webviews of the relevant data, not necessarily compatible
217# with VCS tools and the like.
218documentation = "..."
219homepage = "..."
220repository = "..."
221
917c3634
BE
222# This points to a file under the package root (relative to this `Cargo.toml`).
223# The contents of this file are stored and indexed in the registry.
5ccf654c 224# crates.io will render this file and place the result on the crate's page.
4d590f95
BE
225readme = "..."
226
227# This is a list of up to five keywords that describe this crate. Keywords
228# are searchable on crates.io, and you may choose any words that would
229# help someone find this crate.
230keywords = ["...", "..."]
231
232# This is a list of up to five categories where this crate would fit.
233# Categories are a fixed list available at crates.io/category_slugs, and
234# they must match exactly.
235categories = ["...", "..."]
236
f7c91ba6 237# This is an SPDX 2.1 license expression for this package. Currently
7dee65fe
TK
238# crates.io will validate the license provided against a whitelist of
239# known license and exception identifiers from the SPDX license list
f7c91ba6 240# 2.4. Parentheses are not currently supported.
7dee65fe
TK
241#
242# Multiple licenses can be separated with a `/`, although that usage
f7c91ba6 243# is deprecated. Instead, use a license expression with AND and OR
7dee65fe 244# operators to get more explicit semantics.
4d590f95
BE
245license = "..."
246
4a8bd29f 247# If a package is using a nonstandard license, then this key may be specified in
4d590f95
BE
248# lieu of the above key and must point to a file relative to this manifest
249# (similar to the readme key).
250license-file = "..."
251
ec9fbd0d
DB
252# Optional specification of badges to be displayed on crates.io.
253#
254# - The badges pertaining to build status that are currently available are
2269e51d 255# Appveyor, CircleCI, GitLab, Azure DevOps and TravisCI.
ec9fbd0d
DB
256# - Available badges pertaining to code test coverage are Codecov and
257# Coveralls.
50d210c0 258# - There are also maintenance-related badges based on isitmaintained.com
ec9fbd0d
DB
259# which state the issue resolution time, percent of open issues, and future
260# maintenance intentions.
6d269548 261#
94114d5d 262# If a `repository` key is required, this refers to a repository in
6d269548 263# `user/repo` format.
4d590f95 264[badges]
917c3634 265
4d590f95
BE
266# Appveyor: `repository` is required. `branch` is optional; default is `master`
267# `service` is optional; valid values are `github` (default), `bitbucket`, and
bfb72c57 268# `gitlab`; `id` is optional; you can specify the appveyor project id if you
ea42706d
PM
269# want to use that instead. `project_name` is optional; use when the repository
270# name differs from the appveyor project name.
4d590f95 271appveyor = { repository = "...", branch = "master", service = "github" }
917c3634 272
1da7d17b 273# Circle CI: `repository` is required. `branch` is optional; default is `master`
917c3634
BE
274circle-ci = { repository = "...", branch = "master" }
275
4d590f95
BE
276# GitLab: `repository` is required. `branch` is optional; default is `master`
277gitlab = { repository = "...", branch = "master" }
917c3634 278
2269e51d
RH
279# Azure DevOps: `project` is required. `pipeline` is required. `build` is optional; default is `1`
280# Note: project = `organization/project`, pipeline = `name_of_pipeline`, build = `definitionId`
281azure-devops = { project = "...", pipeline = "...", build="2" }
282
917c3634
BE
283# Travis CI: `repository` in format "<user>/<project>" is required.
284# `branch` is optional; default is `master`
285travis-ci = { repository = "...", branch = "master" }
286
4d590f95
BE
287# Codecov: `repository` is required. `branch` is optional; default is `master`
288# `service` is optional; valid values are `github` (default), `bitbucket`, and
289# `gitlab`.
290codecov = { repository = "...", branch = "master", service = "github" }
917c3634 291
4d590f95
BE
292# Coveralls: `repository` is required. `branch` is optional; default is `master`
293# `service` is optional; valid values are `github` (default) and `bitbucket`.
294coveralls = { repository = "...", branch = "master", service = "github" }
917c3634
BE
295
296# Is it maintained resolution time: `repository` is required.
297is-it-maintained-issue-resolution = { repository = "..." }
298
299# Is it maintained percentage of open issues: `repository` is required.
300is-it-maintained-open-issues = { repository = "..." }
301
dee137b6 302# Maintenance: `status` is required. Available options are:
303# - `actively-developed`: New features are being added and bugs are being fixed.
304# - `passively-maintained`: There are no plans for new features, but the maintainer intends to
305# respond to issues that get filed.
306# - `as-is`: The crate is feature complete, the maintainer does not intend to continue working on
307# it or providing support, but it works for the purposes it was designed for.
308# - `experimental`: The author wants to share it with the community but is not intending to meet
309# anyone's particular use case.
310# - `looking-for-maintainer`: The current maintainer would like to transfer the crate to someone
311# else.
312# - `deprecated`: The maintainer does not recommend using this crate (the description of the crate
313# can describe why, there could be a better solution available or there could be problems with
314# the crate that the author does not want to fix).
315# - `none`: Displays no badge on crates.io, since the maintainer has not chosen to specify
316# their intentions, potential crate users will need to investigate on their own.
917c3634 317maintenance = { status = "..." }
4d590f95
BE
318```
319
320The [crates.io](https://crates.io) registry will render the description, display
321the license, link to the three URLs and categorize by the keywords. These keys
322provide useful information to users of the registry and also influence the
323search ranking of a crate. It is highly discouraged to omit everything in a
324published crate.
325
7dee65fe 326SPDX 2.1 license expressions are documented
f7c91ba6 327[here][spdx-2.1-license-expressions]. The current version of the
7dee65fe
TK
328license list is available [here][spdx-license-list], and version 2.4
329is available [here][spdx-license-list-2.4].
330
4d590f95
BE
331#### The `metadata` table (optional)
332
333Cargo by default will warn about unused keys in `Cargo.toml` to assist in
334detecting typos and such. The `package.metadata` table, however, is completely
335ignored by Cargo and will not be warned about. This section can be used for
4a8bd29f 336tools which would like to store package configuration in `Cargo.toml`. For
4d590f95
BE
337example:
338
339```toml
340[package]
341name = "..."
342# ...
343
344# Metadata used when generating an Android APK, for example.
345[package.metadata.android]
346package-name = "my-awesome-android-app"
347assets = "path/to/static"
348```
349
350### Dependency sections
351
3f2d93e3 352See the [specifying dependencies page](reference/specifying-dependencies.html) for
4d590f95
BE
353information on the `[dependencies]`, `[dev-dependencies]`,
354`[build-dependencies]`, and target-specific `[target.*.dependencies]` sections.
355
356### The `[profile.*]` sections
357
358Cargo supports custom configuration of how rustc is invoked through profiles at
359the top level. Any manifest may declare a profile, but only the top level
4a8bd29f
ZL
360package’s profiles are actually read. All dependencies’ profiles will be
361overridden. This is done so the top-level package has control over how its
4d590f95
BE
362dependencies are compiled.
363
e881999f 364There are four currently supported profile names, all of which have the same
4d590f95
BE
365configuration available to them. Listed below is the configuration available,
366along with the defaults for each profile.
367
368```toml
369# The development profile, used for `cargo build`.
370[profile.dev]
371opt-level = 0 # controls the `--opt-level` the compiler builds with.
372 # 0-1 is good for debugging. 2 is well-optimized. Max is 3.
ad5d79c9 373 # 's' attempts to reduce size, 'z' reduces size even more.
a547302e
RG
374debug = true # (u32 or bool) Include debug information (debug symbols).
375 # Equivalent to `-C debuginfo=2` compiler flag.
4d590f95
BE
376rpath = false # controls whether compiler should set loader paths.
377 # If true, passes `-C rpath` flag to the compiler.
378lto = false # Link Time Optimization usually reduces size of binaries
379 # and static libraries. Increases compilation time.
077feed5
AC
380 # If true, passes `-C lto` flag to the compiler, and if a
381 # string is specified like 'thin' then `-C lto=thin` will
e74ff4db 382 # be passed.
4d590f95 383debug-assertions = true # controls whether debug assertions are enabled
f7c91ba6 384 # (e.g., debug_assert!() and arithmetic overflow checks)
0c46ede7 385codegen-units = 16 # if > 1 enables parallel code generation which improves
4d590f95 386 # compile times, but prevents some optimizations.
50d210c0 387 # Passes `-C codegen-units`.
4d590f95 388panic = 'unwind' # panic strategy (`-C panic=...`), can also be 'abort'
e0b4c582 389incremental = true # whether or not incremental compilation is enabled
2b6fd6f0
EH
390 # This can be overridden globally with the CARGO_INCREMENTAL
391 # environment variable or `build.incremental` config
392 # variable. Incremental is only used for path sources.
c4d4012d
EH
393overflow-checks = true # use overflow checks for integer arithmetic.
394 # Passes the `-C overflow-checks=...` flag to the compiler.
4d590f95 395
a472e7c4 396# The release profile, used for `cargo build --release` (and the dependencies
f7c91ba6 397# for `cargo test --release`, including the local library or binary).
4d590f95
BE
398[profile.release]
399opt-level = 3
400debug = false
401rpath = false
e5539627 402lto = false
4d590f95 403debug-assertions = false
0c46ede7 404codegen-units = 16
4d590f95 405panic = 'unwind'
e0b4c582 406incremental = false
c4d4012d 407overflow-checks = false
4d590f95 408
a472e7c4
DL
409# The testing profile, used for `cargo test` (for `cargo test --release` see
410# the `release` and `bench` profiles).
4d590f95
BE
411[profile.test]
412opt-level = 0
413debug = 2
414rpath = false
415lto = false
416debug-assertions = true
0c46ede7 417codegen-units = 16
4d590f95 418panic = 'unwind'
e0b4c582 419incremental = true
c4d4012d 420overflow-checks = true
4d590f95 421
a472e7c4
DL
422# The benchmarking profile, used for `cargo bench` (and the test targets and
423# unit tests for `cargo test --release`).
4d590f95
BE
424[profile.bench]
425opt-level = 3
426debug = false
427rpath = false
e5539627 428lto = false
4d590f95 429debug-assertions = false
0c46ede7 430codegen-units = 16
4d590f95 431panic = 'unwind'
e0b4c582 432incremental = false
c4d4012d 433overflow-checks = false
4d590f95
BE
434```
435
436### The `[features]` section
437
438Cargo supports features to allow expression of:
439
440* conditional compilation options (usable through `cfg` attributes);
441* optional dependencies, which enhance a package, but are not required; and
442* clusters of optional dependencies, such as `postgres`, that would include the
443 `postgres` package, the `postgres-macros` package, and possibly other packages
444 (such as development-time mocking libraries, debugging tools, etc.).
445
446A feature of a package is either an optional dependency, or a set of other
447features. The format for specifying features is:
448
449```toml
450[package]
451name = "awesome"
452
453[features]
454# The default set of optional packages. Most people will want to use these
455# packages, but they are strictly optional. Note that `session` is not a package
456# but rather another feature listed in this manifest.
457default = ["jquery", "uglifier", "session"]
458
459# A feature with no dependencies is used mainly for conditional compilation,
460# like `#[cfg(feature = "go-faster")]`.
461go-faster = []
462
463# The `secure-password` feature depends on the bcrypt package. This aliasing
464# will allow people to talk about the feature in a higher-level way and allow
465# this package to add more requirements to the feature in the future.
466secure-password = ["bcrypt"]
467
468# Features can be used to reexport features of other packages. The `session`
469# feature of package `awesome` will ensure that the `session` feature of the
470# package `cookie` is also enabled.
471session = ["cookie/session"]
472
473[dependencies]
474# These packages are mandatory and form the core of this package’s distribution.
475cookie = "1.2.0"
476oauth = "1.1.0"
477route-recognizer = "=2.1.0"
478
479# A list of all of the optional dependencies, some of which are included in the
480# above `features`. They can be opted into by apps.
481jquery = { version = "1.0.2", optional = true }
482uglifier = { version = "1.5.3", optional = true }
483bcrypt = { version = "*", optional = true }
484civet = { version = "*", optional = true }
485```
486
487To use the package `awesome`:
488
489```toml
490[dependencies.awesome]
491version = "1.3.5"
492default-features = false # do not include the default features, and optionally
493 # cherry-pick individual features
494features = ["secure-password", "civet"]
495```
496
497#### Rules
498
499The usage of features is subject to a few rules:
500
501* Feature names must not conflict with other package names in the manifest. This
502 is because they are opted into via `features = [...]`, which only has a single
503 namespace.
504* With the exception of the `default` feature, all features are opt-in. To opt
505 out of the default feature, use `default-features = false` and cherry-pick
506 individual features.
507* Feature groups are not allowed to cyclically depend on one another.
508* Dev-dependencies cannot be optional.
509* Features groups can only reference optional dependencies.
510* When a feature is selected, Cargo will call `rustc` with `--cfg
511 feature="${feature_name}"`. If a feature group is included, it and all of its
512 individual features will be included. This can be tested in code via
513 `#[cfg(feature = "foo")]`.
514
515Note that it is explicitly allowed for features to not actually activate any
516optional dependencies. This allows packages to internally enable/disable
517features without requiring a new dependency.
518
519#### Usage in end products
520
521One major use-case for this feature is specifying optional features in
4a8bd29f 522end-products. For example, the Servo package may want to include optional
4d590f95
BE
523features that people can enable or disable when they build it.
524
525In that case, Servo will describe features in its `Cargo.toml` and they can be
526enabled using command-line flags:
527
bc489e25 528```console
4d590f95
BE
529$ cargo build --release --features "shumway pdf"
530```
531
532Default features could be excluded using `--no-default-features`.
533
534#### Usage in packages
535
536In most cases, the concept of *optional dependency* in a library is best
537expressed as a separate package that the top-level application depends on.
538
539However, high-level packages, like Iron or Piston, may want the ability to
540curate a number of packages for easy installation. The current Cargo system
541allows them to curate a number of mandatory dependencies into a single package
542for easy installation.
543
544In some cases, packages may want to provide additional curation for optional
545dependencies:
546
547* grouping a number of low-level optional dependencies together into a single
548 high-level feature;
549* specifying packages that are recommended (or suggested) to be included by
550 users of the package; and
551* including a feature (like `secure-password` in the motivating example) that
552 will only work if an optional dependency is available, and would be difficult
553 to implement as a separate package (for example, it may be overly difficult to
554 design an IO package to be completely decoupled from OpenSSL, with opt-in via
555 the inclusion of a separate package).
556
557In almost all cases, it is an antipattern to use these features outside of
558high-level packages that are designed for curation. If a feature is optional, it
559can almost certainly be expressed as a separate package.
560
561### The `[workspace]` section
562
4a8bd29f 563Packages can define a workspace which is a set of crates that will all share the
4d590f95
BE
564same `Cargo.lock` and output directory. The `[workspace]` table can be defined
565as:
566
567```toml
568[workspace]
569
74b4d0ff
PM
570# Optional key, inferred from path dependencies if not present.
571# Additional non-path dependencies that should be included must be given here.
572# In particular, for a virtual manifest, all members have to be listed.
4d590f95
BE
573members = ["path/to/member1", "path/to/member2", "path/to/member3/*"]
574
74b4d0ff 575# Optional key, empty if not present.
4d590f95
BE
576exclude = ["path1", "path/to/dir2"]
577```
578
917c3634 579Workspaces were added to Cargo as part of [RFC 1525] and have a number of
4d590f95
BE
580properties:
581
917c3634
BE
582* A workspace can contain multiple crates where one of them is the *root crate*.
583* The *root crate*'s `Cargo.toml` contains the `[workspace]` table, but is not
4d590f95 584 required to have other configuration.
917c3634 585* Whenever any crate in the workspace is compiled, output is placed in the
f7c91ba6 586 *workspace root* (i.e., next to the *root crate*'s `Cargo.toml`).
917c3634 587* The lock file for all crates in the workspace resides in the *workspace root*.
2896e3f1 588* The `[patch]`, `[replace]` and `[profile.*]` sections in `Cargo.toml`
589 are only recognized
917c3634 590 in the *root crate*'s manifest, and ignored in member crates' manifests.
4d590f95
BE
591
592[RFC 1525]: https://github.com/rust-lang/rfcs/blob/master/text/1525-cargo-workspace.md
593
917c3634
BE
594The *root crate* of a workspace, indicated by the presence of `[workspace]` in
595its manifest, is responsible for defining the entire workspace. All `path`
4d590f95
BE
596dependencies residing in the workspace directory become members. You can add
597additional packages to the workspace by listing them in the `members` key. Note
598that members of the workspaces listed explicitly will also have their path
4a8bd29f 599dependencies included in the workspace. Sometimes a package may have a lot of
4d590f95
BE
600workspace members and it can be onerous to keep up to date. The path dependency
601can also use [globs][globs] to match multiple paths. Finally, the `exclude`
602key can be used to blacklist paths from being included in a workspace. This can
603be useful if some path dependencies aren't desired to be in the workspace at
604all.
605
606The `package.workspace` manifest key (described above) is used in member crates
607to point at a workspace's root crate. If this key is omitted then it is inferred
608to be the first crate whose manifest contains `[workspace]` upwards in the
609filesystem.
610
611A crate may either specify `package.workspace` or specify `[workspace]`. That
612is, a crate cannot both be a root crate in a workspace (contain `[workspace]`)
613and also be a member crate of another workspace (contain `package.workspace`).
614
615Most of the time workspaces will not need to be dealt with as `cargo new` and
616`cargo init` will handle workspace configuration automatically.
617
917c3634
BE
618#### Virtual Manifest
619
620In workspace manifests, if the `package` table is present, the workspace root
06a6a40a 621crate will be treated as a normal package, as well as a workspace. If the
622`package` table is not present in a workspace manifest, it is called a *virtual
917c3634
BE
623manifest*.
624
27d4195d
PM
625#### Package selection
626
627In a workspace, package-related cargo commands like `cargo build` apply to
628packages selected by `-p` / `--package` or `--all` command-line parameters.
629When neither is specified, the optional `default-members` configuration is used:
48b87407
PM
630
631```toml
632[workspace]
633members = ["path/to/member1", "path/to/member2", "path/to/member3/*"]
27d4195d 634default-members = ["path/to/member2", "path/to/member3/foo"]
48b87407 635```
917c3634 636
27d4195d
PM
637When specified, `default-members` must expand to a subset of `members`.
638
639When `default-members` is not specified, the default is the root manifest
640if it is a package, or every member manifest (as if `--all` were specified
641on the command-line) for virtual workspaces.
917c3634 642
9c8da172 643### The project layout
4d590f95 644
4a8bd29f 645If your package is an executable, name the main source file `src/main.rs`. If it
4d590f95
BE
646is a library, name the main source file `src/lib.rs`.
647
648Cargo will also treat any files located in `src/bin/*.rs` as executables. If your
649executable consists of more than just one source file, you might also use a directory
650inside `src/bin` containing a `main.rs` file which will be treated as an executable
651with a name of the parent directory.
4d590f95 652
4a8bd29f 653Your package can optionally contain folders named `examples`, `tests`, and
4d590f95 654`benches`, which Cargo will treat as containing examples,
999cba15
PM
655integration tests, and benchmarks respectively. Analogous to `bin` targets, they
656may be composed of single files or directories with a `main.rs` file.
4d590f95 657
bc489e25 658```
4d590f95
BE
659▾ src/ # directory containing source files
660 lib.rs # the main entry point for libraries and packages
4a8bd29f 661 main.rs # the main entry point for packages producing executables
4d590f95
BE
662 ▾ bin/ # (optional) directory containing additional executables
663 *.rs
664 ▾ */ # (optional) directories containing multi-file executables
665 main.rs
666▾ examples/ # (optional) examples
667 *.rs
f0be7a39
SS
668 ▾ */ # (optional) directories containing multi-file examples
669 main.rs
4d590f95
BE
670▾ tests/ # (optional) integration tests
671 *.rs
f0be7a39
SS
672 ▾ */ # (optional) directories containing multi-file tests
673 main.rs
4d590f95
BE
674▾ benches/ # (optional) benchmarks
675 *.rs
f0be7a39
SS
676 ▾ */ # (optional) directories containing multi-file benchmarks
677 main.rs
4d590f95
BE
678```
679
680To structure your code after you've created the files and folders for your
4a8bd29f 681package, you should remember to use Rust's module system, which you can read
b54748ef
EH
682about in [the
683book](../book/ch07-00-managing-growing-projects-with-packages-crates-and-modules.html).
4d590f95 684
eed6bdc8
EH
685See [Configuring a target](#configuring-a-target) below for more details on
686manually configuring target settings. See [Target
687auto-discovery](#target-auto-discovery) below for more information on
688controlling how Cargo automatically infers targets.
689
4d590f95
BE
690### Examples
691
692Files located under `examples` are example uses of the functionality provided by
693the library. When compiled, they are placed in the `target/examples` directory.
694
695They can compile either as executables (with a `main()` function) or libraries
696and pull in the library by using `extern crate <library-name>`. They are
697compiled when you run your tests to protect them from bitrotting.
698
699You can run individual executable examples with the command `cargo run --example
700<example-name>`.
701
c4d4012d
EH
702Specify `crate-type` to make an example be compiled as a library (additional
703information about crate types is available in
b54748ef 704[The Rust Reference](../reference/linkage.html)):
4d590f95
BE
705
706```toml
707[[example]]
708name = "foo"
709crate-type = ["staticlib"]
710```
711
712You can build individual library examples with the command `cargo build
713--example <example-name>`.
714
715### Tests
716
717When you run `cargo test`, Cargo will:
718
719* compile and run your library’s unit tests, which are in the files reachable
720 from `lib.rs` (naturally, any sections marked with `#[cfg(test)]` will be
721 considered at this stage);
722* compile and run your library’s documentation tests, which are embedded inside
723 of documentation blocks;
724* compile and run your library’s [integration tests](#integration-tests); and
725* compile your library’s examples.
726
727#### Integration tests
728
729Each file in `tests/*.rs` is an integration test. When you run `cargo test`,
730Cargo will compile each of these files as a separate crate. The crate can link
731to your library by using `extern crate <library-name>`, like any other code that
732depends on it.
733
734Cargo will not automatically compile files inside subdirectories of `tests`, but
735an integration test can import modules from these directories as usual. For
736example, if you want several integration tests to share some code, you can put
737the shared code in `tests/common/mod.rs` and then put `mod common;` in each of
738the test files.
739
740### Configuring a target
741
742All of the `[[bin]]`, `[lib]`, `[[bench]]`, `[[test]]`, and `[[example]]`
743sections support similar configuration for specifying how a target should be
744built. The double-bracket sections like `[[bin]]` are array-of-table of
745[TOML](https://github.com/toml-lang/toml#array-of-tables), which means you can
746write more than one `[[bin]]` section to make several executables in your crate.
747
748The example below uses `[lib]`, but it also applies to all other sections
749as well. All values listed are the defaults for that option unless otherwise
750specified.
751
752```toml
753[package]
754# ...
755
756[lib]
757# The name of a target is the name of the library that will be generated. This
4a8bd29f 758# is defaulted to the name of the package, with any dashes replaced
4d590f95
BE
759# with underscores. (Rust `extern crate` declarations reference this name;
760# therefore the value must be a valid Rust identifier to be usable.)
761name = "foo"
762
763# This field points at where the crate is located, relative to the `Cargo.toml`.
764path = "src/lib.rs"
765
766# A flag for enabling unit tests for this target. This is used by `cargo test`.
767test = true
768
769# A flag for enabling documentation tests for this target. This is only relevant
770# for libraries, it has no effect on other sections. This is used by
771# `cargo test`.
772doctest = true
773
774# A flag for enabling benchmarks for this target. This is used by `cargo bench`.
775bench = true
776
777# A flag for enabling documentation of this target. This is used by `cargo doc`.
778doc = true
779
780# If the target is meant to be a compiler plugin, this field must be set to true
781# for Cargo to correctly compile it and make it available for all dependencies.
782plugin = false
783
784# If the target is meant to be a "macros 1.1" procedural macro, this field must
785# be set to true.
786proc-macro = false
787
788# If set to false, `cargo test` will omit the `--test` flag to rustc, which
789# stops it from generating a test harness. This is useful when the binary being
790# built manages the test runner itself.
791harness = true
3d029039
AC
792
793# If set then a target can be configured to use a different edition than the
794# `[package]` is configured to use, perhaps only compiling a library with the
795# 2018 edition or only compiling one unit test with the 2015 edition. By default
796# all targets are compiled with the edition specified in `[package]`.
797edition = '2015'
83fc0760
DW
798
799# Here's an example of a TOML "array of tables" section, in this case specifying
800# a binary target name and path.
801[[bin]]
802name = "my-cool-binary"
803path = "src/my-cool-binary.rs"
4d590f95
BE
804```
805
eed6bdc8
EH
806#### Target auto-discovery
807
808By default, Cargo automatically determines the targets to build based on the
809[layout of the files](#the-project-layout) on the filesystem. The target
810configuration tables, such as `[lib]`, `[[bin]]`, `[[test]]`, `[[bench]]`, or
811`[[example]]`, can be used to add additional targets that don't follow the
812standard directory layout.
813
814The automatic target discovery can be disabled so that only manually
815configured targets will be built. Setting the keys `autobins`, `autoexamples`,
816`autotests`, or `autobenches` to `false` in the `[package]` section will
817disable auto-discovery of the corresponding target type.
818
819Disabling automatic discovery should only be needed for specialized
820situations. For example, if you have a library where you want a *module* named
821`bin`, this would present a problem because Cargo would usually attempt to
822compile anything in the `bin` directory as an executable. Here is a sample
823layout of this scenario:
824
825```
826├── Cargo.toml
827└── src
828    ├── lib.rs
829    └── bin
830       └── mod.rs
831```
832
833To prevent Cargo from inferring `src/bin/mod.rs` as an executable, set
834`autobins = false` in `Cargo.toml` to disable auto-discovery:
835
836```toml
837[package]
838# …
839autobins = false
840```
841
842> **Note**: For packages with the 2015 edition, the default for auto-discovery
843> is `false` if at least one target is manually defined in `Cargo.toml`.
844> Beginning with the 2018 edition, the default is always `true`.
e471745e 845
4d590f95
BE
846#### The `required-features` field (optional)
847
848The `required-features` field specifies which features the target needs in order
849to be built. If any of the required features are not selected, the target will
850be skipped. This is only relevant for the `[[bin]]`, `[[bench]]`, `[[test]]`,
851and `[[example]]` sections, it has no effect on `[lib]`.
852
853```toml
854[features]
855# ...
856postgres = []
857sqlite = []
858tools = []
859
860[[bin]]
861# ...
862required-features = ["postgres", "tools"]
863```
864
865#### Building dynamic or static libraries
866
4a8bd29f 867If your package produces a library, you can specify which kind of library to
4d590f95
BE
868build by explicitly listing the library in your `Cargo.toml`:
869
870```toml
871# ...
872
873[lib]
874name = "..."
875crate-type = ["dylib"] # could be `staticlib` as well
876```
877
878The available options are `dylib`, `rlib`, `staticlib`, `cdylib`, and
62c6de38 879`proc-macro`.
4d590f95
BE
880
881You can read more about the different crate types in the
b54748ef 882[Rust Reference Manual](../reference/linkage.html)
4d590f95
BE
883
884### The `[patch]` Section
885
886This section of Cargo.toml can be used to [override dependencies][replace] with
887other copies. The syntax is similar to the `[dependencies]` section:
888
889```toml
890[patch.crates-io]
891foo = { git = 'https://github.com/example/foo' }
892bar = { path = 'my/local/bar' }
97555df8
PM
893
894[dependencies.baz]
895git = 'https://github.com/example/baz'
896
897[patch.'https://github.com/example/baz']
97584002 898baz = { git = 'https://github.com/example/patched-baz', branch = 'my-branch' }
4d590f95
BE
899```
900
901The `[patch]` table is made of dependency-like sub-tables. Each key after
737382d7
EH
902`[patch]` is a URL of the source that is being patched, or the name of a
903registry. The name `crates-io` may be used to override the default registry
904[crates.io]. The first `[patch]` in the example above demonstrates overriding
905[crates.io], and the second `[patch]` demonstrates overriding a git source.
4d590f95
BE
906
907Each entry in these tables is a normal dependency specification, the same as
908found in the `[dependencies]` section of the manifest. The dependencies listed
909in the `[patch]` section are resolved and used to patch the source at the
910URL specified. The above manifest snippet patches the `crates-io` source (e.g.
97555df8
PM
911crates.io itself) with the `foo` crate and `bar` crate. It also
912patches the `https://github.com/example/baz` source with a `my-branch` that
913comes from elsewhere.
4d590f95
BE
914
915Sources can be patched with versions of crates that do not exist, and they can
916also be patched with versions of crates that already exist. If a source is
917patched with a crate version that already exists in the source, then the
918source's original crate is replaced.
919
920More information about overriding dependencies can be found in the [overriding
921dependencies][replace] section of the documentation and [RFC 1969] for the
2c00108d 922technical specification of this feature.
4d590f95
BE
923
924[RFC 1969]: https://github.com/rust-lang/rfcs/pull/1969
737382d7 925[crates.io]: https://crates.io/
3f2d93e3 926[replace]: reference/specifying-dependencies.html#overriding-dependencies
4d590f95
BE
927
928### The `[replace]` Section
929
930This section of Cargo.toml can be used to [override dependencies][replace] with
931other copies. The syntax is similar to the `[dependencies]` section:
932
933```toml
934[replace]
935"foo:0.1.0" = { git = 'https://github.com/example/foo' }
936"bar:1.0.2" = { path = 'my/local/bar' }
937```
938
f7c91ba6
AR
939Each key in the `[replace]` table is a [package ID
940specification](reference/pkgid-spec.html), which allows arbitrarily choosing a node in the
4d590f95
BE
941dependency graph to override. The value of each key is the same as the
942`[dependencies]` syntax for specifying dependencies, except that you can't
943specify features. Note that when a crate is overridden the copy it's overridden
944with must have both the same name and version, but it can come from a different
f7c91ba6 945source (e.g., git or a local path).
4d590f95
BE
946
947More information about overriding dependencies can be found in the [overriding
948dependencies][replace] section of the documentation.
7dee65fe
TK
949
950[spdx-2.1-license-expressions]: https://spdx.org/spdx-specification-21-web-version#h.jxpfx0ykyb60
951[spdx-license-list]: https://spdx.org/licenses/
952[spdx-license-list-2.4]: https://github.com/spdx/license-list-data/tree/v2.4