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