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