├── src └── doc │ ├── favicon.ico │ ├── images │ ├── forkme.png │ ├── noise.png │ ├── search.png │ ├── auth-level-acl.png │ ├── circle-with-i.png │ ├── org-level-acl.png │ └── Cargo-Logo-Small.png │ ├── html-headers.html │ ├── footer.html │ ├── javascripts │ ├── all.js │ └── prism.js │ ├── pkgid-spec.md │ ├── header.html │ ├── machine-readable-output.md │ ├── policies.md │ ├── index.md │ ├── environment-variables.md │ ├── stylesheets │ ├── prism.css │ ├── all.css │ └── normalize.css │ ├── config.md │ ├── source-replacement.md │ ├── faq.md │ ├── crates-io.md │ ├── specifying-dependencies.md │ ├── guide.md │ ├── build-script.md │ └── manifest.md ├── .gitmodules ├── README.md ├── .gitignore ├── LICENSE-MIT ├── Makefile ├── .travis.yml └── LICENSE-APACHE /src/doc/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rust-lang-ru/cargo-docs-ru/HEAD/src/doc/favicon.ico -------------------------------------------------------------------------------- /src/doc/images/forkme.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rust-lang-ru/cargo-docs-ru/HEAD/src/doc/images/forkme.png -------------------------------------------------------------------------------- /src/doc/images/noise.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rust-lang-ru/cargo-docs-ru/HEAD/src/doc/images/noise.png -------------------------------------------------------------------------------- /src/doc/images/search.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rust-lang-ru/cargo-docs-ru/HEAD/src/doc/images/search.png -------------------------------------------------------------------------------- /src/doc/images/auth-level-acl.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rust-lang-ru/cargo-docs-ru/HEAD/src/doc/images/auth-level-acl.png -------------------------------------------------------------------------------- /src/doc/images/circle-with-i.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rust-lang-ru/cargo-docs-ru/HEAD/src/doc/images/circle-with-i.png -------------------------------------------------------------------------------- /src/doc/images/org-level-acl.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rust-lang-ru/cargo-docs-ru/HEAD/src/doc/images/org-level-acl.png -------------------------------------------------------------------------------- /src/doc/images/Cargo-Logo-Small.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rust-lang-ru/cargo-docs-ru/HEAD/src/doc/images/Cargo-Logo-Small.png -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "src/rust-installer"] 2 | path = src/rust-installer 3 | url = https://github.com/rust-lang/rust-installer.git 4 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [Перевод документации по Cargo](https://rurust.github.io/cargo-docs-ru/). 2 | 3 | Cargo - это система сборки и пакетный менеджер для Rust. -------------------------------------------------------------------------------- /src/doc/html-headers.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | .cargo 3 | /config.stamp 4 | /config.mk 5 | src/doc/build 6 | src/etc/*.pyc 7 | src/registry/target 8 | src/registry/Cargo.lock 9 | rustc 10 | __pycache__ 11 | -------------------------------------------------------------------------------- /src/doc/footer.html: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2014 The Rust Project Developers 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | TARGET_ROOT = target 2 | 3 | clean: 4 | rm -rf $(TARGET_ROOT) 5 | 6 | # === Documentation 7 | 8 | DOCS := index faq config guide manifest build-script pkgid-spec crates-io \ 9 | environment-variables specifying-dependencies source-replacement \ 10 | policies machine-readable-output 11 | DOC_DIR := target/doc 12 | DOC_OPTS := --markdown-no-toc \ 13 | --markdown-css stylesheets/normalize.css \ 14 | --markdown-css stylesheets/all.css \ 15 | --markdown-css stylesheets/prism.css \ 16 | --html-in-header src/doc/html-headers.html \ 17 | --html-before-content src/doc/header.html \ 18 | --html-after-content src/doc/footer.html 19 | ASSETS := images/noise.png images/forkme.png images/Cargo-Logo-Small.png \ 20 | stylesheets/all.css stylesheets/normalize.css javascripts/prism.js \ 21 | javascripts/all.js stylesheets/prism.css images/circle-with-i.png \ 22 | images/search.png images/org-level-acl.png images/auth-level-acl.png \ 23 | favicon.ico 24 | 25 | doc: $(foreach doc,$(DOCS),target/doc/$(doc).html) \ 26 | $(foreach asset,$(ASSETS),target/doc/$(asset)) \ 27 | 28 | $(DOC_DIR)/%.html: src/doc/%.md src/doc/html-headers.html src/doc/header.html src/doc/footer.html 29 | @mkdir -p $(@D) 30 | rustdoc $< -o $(@D) $(DOC_OPTS) 31 | 32 | $(DOC_DIR)/%: src/doc/% 33 | @mkdir -p $(@D) 34 | cp $< $@ 35 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | rust: 3 | - stable 4 | sudo: false 5 | before_script: 6 | - git config --global user.email "Igor.Shaposhnik" 7 | - git config --global user.name "shaposhnikigor95@bk.ru" 8 | script: 9 | - make doc 10 | after_success: | 11 | [ $TRAVIS_BRANCH = master ] && 12 | [ $TRAVIS_PULL_REQUEST = false ] && 13 | [ $(uname -s) = Linux ] && 14 | pip install ghp-import --user $USER && 15 | $HOME/.local/bin/ghp-import -n target/doc && 16 | git push -qf https://${CDOC_TOKEN}@github.com/${TRAVIS_REPO_SLUG}.git gh-pages 17 | env: 18 | global: 19 | - secure: dGdvTkbweREdpaRQWzq9w837ibv3rLjI2fRq+BRh/pJt3imPQa8FMw8m3OoS9p/y4GlYDSu3p+aLCktH3ulRqtC0iAzy0BhnvVG6xJhnL2YRawJiA3bz//iaLdWZVd9gnu+UR1xFYA/ZzjpDrdq+9f37uYRClonDXz9wl01WCe0AiQ69LEe4MEedYNBwhYvDK6YPoWF4X0AF42uebuCwb4xLsFwzFGt4R/xZ7MU7SAFgZxsy+xEORbP5qqRUo2kG6BHxDfJlN9V966Iw5aViK6xLUarUKYSmDtIlGeLwuI+Zjvx/ompgfaq7YSSkGoD7QIWS6v5/6nB61drIT+43oWZ87r4YuRuRthTGNSadsmnzB0YIin9RNyHm6LabF9ykLaMARJI/dSy5nMyFpEA5qrda7nxrJJPFnWX2UVsRtEyGezXSYxVqM4OftCxAIy8rHQplzGVjzHzbby+M1sCoyCtkt5jz65ii6wgH7e/el8BC4nT0h0MV2X7HMqNO7nebYgctkWtHeH6ZLfMUuL6YbHdWqFk9mFNr/4S0vBO7qK5rZRD3oqzNw2nWwwojbl1oRhsVV8kA6tSNNXCgPbK4/qlKMK0rsTkRlO09aDyZOAcjKy1AY8daAomPYTigfWBy0CF/Jt7JLdfavaElA+FykhVQLrrCENzDGI2L0wsEE9A= 20 | os: 21 | - linux 22 | branches: 23 | only: 24 | - master 25 | -------------------------------------------------------------------------------- /src/doc/javascripts/all.js: -------------------------------------------------------------------------------- 1 | //= require_tree . 2 | 3 | Prism.languages.toml = { 4 | // https://github.com/LeaVerou/prism/issues/307 5 | 'comment': [{ 6 | pattern: /(^[^"]*?("[^"]*?"[^"]*?)*?[^"\\]*?)(\/\*[\w\W]*?\*\/|(^|[^:])#.*?(\r?\n|$))/g, 7 | lookbehind: true 8 | }], 9 | 'string': /("|')(\\?.)*?\1/g, 10 | 'number': /\d+/, 11 | 'boolean': /true|false/, 12 | 'toml-section': /\[.*\]/, 13 | 'toml-key': /[\w-]+/ 14 | }; 15 | 16 | $(function() { 17 | var pres = document.querySelectorAll('pre.rust'); 18 | for (var i = 0; i < pres.length; i++) { 19 | pres[i].className += ' language-rust'; 20 | } 21 | 22 | // Toggles docs menu 23 | $('button.dropdown, a.dropdown').click(function(el, e) { 24 | $(this).toggleClass('active').siblings('ul').toggleClass('open'); 25 | 26 | return false; 27 | }); 28 | 29 | // A click in the page anywhere but in the menu will turn the menu off 30 | $(document).on('click', function(e) { 31 | // Checks to make sure the click did not come from inside dropdown menu 32 | // if it doesn't we close the menu 33 | // else, we do nothing and just follow the link 34 | if (!$(e.target).closest('ul.dropdown').length) { 35 | var toggles = $('button.dropdown.active, a.dropdown.active'); 36 | toggles.toggleClass('active').siblings('ul').toggleClass('open'); 37 | 38 | } 39 | }); 40 | }); 41 | -------------------------------------------------------------------------------- /src/doc/pkgid-spec.md: -------------------------------------------------------------------------------- 1 | % Package ID Specifications 2 | 3 | # Package ID specifications 4 | 5 | Subcommands of Cargo frequently need to refer to a particular package within a 6 | dependency graph for various operations like updating, cleaning, building, etc. 7 | To solve this problem, Cargo supports Package ID Specifications. A specification 8 | is a string which is used to uniquely refer to one package within a graph of 9 | packages. 10 | 11 | ## Specification grammar 12 | 13 | The formal grammar for a Package Id Specification is: 14 | 15 | ```notrust 16 | pkgid := pkgname 17 | | [ proto "://" ] hostname-and-path [ "#" ( pkgname | semver ) ] 18 | pkgname := name [ ":" semver ] 19 | 20 | proto := "http" | "git" | ... 21 | ``` 22 | 23 | Here, brackets indicate that the contents are optional. 24 | 25 | ## Example specifications 26 | 27 | These could all be references to a package `foo` version `1.2.3` from the 28 | registry at `crates.io` 29 | 30 | | pkgid | name | version | url | 31 | |-------------------------------:|:------:|:---------:|:--------------------:| 32 | | `foo` | foo | * | * | 33 | | `foo:1.2.3` | foo | 1.2.3 | * | 34 | | `crates.io/foo` | foo | * | *://crates.io/foo | 35 | | `crates.io/foo#1.2.3` | foo | 1.2.3 | *://crates.io/foo | 36 | | `crates.io/bar#foo:1.2.3` | foo | 1.2.3 | *://crates.io/bar | 37 | | `http://crates.io/foo#1.2.3` | foo | 1.2.3 | http://crates.io/foo | 38 | 39 | ## Brevity of specifications 40 | 41 | The goal of this is to enable both succinct and exhaustive syntaxes for 42 | referring to packages in a dependency graph. Ambiguous references may refer to 43 | one or more packages. Most commands generate an error if more than one package 44 | could be referred to with the same specification. 45 | -------------------------------------------------------------------------------- /src/doc/header.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 48 | 49 |
50 | -------------------------------------------------------------------------------- /src/doc/machine-readable-output.md: -------------------------------------------------------------------------------- 1 | % Машиночитаемый вывод. 2 | 3 | Cargo может выдавать информацию о вашей сборке и вашем проекте в формате JSON. 4 | Cargo can output information about project and build in JSON format. 5 | 6 | # Информация о структуре проекта 7 | 8 | Вы можете использовать команду `cargo metadata` чтобы получить информацию о структуре проекта 9 | и зависимостях. Вывод данной команды будет примерно таким: 10 | 11 | ```text 12 | { 13 | // Версия формата сообщений . 14 | "version": integer, 15 | 16 | // Список пакетов для проекта, включая зависимости. 17 | "packages": [ 18 | { 19 | // Уникальный идентификатор пакета. 20 | "id": PackageId, 21 | 22 | "name": string, 23 | 24 | "version": string, 25 | 26 | "source": SourceId, 27 | 28 | // Список объявленных зависимостей. Используемые зависимости описаны в пол `resolve`. 29 | "dependencies": [ Dependency ], 30 | 31 | "targets: [ Target ], 32 | 33 | // Путь до Cargo.toml 34 | "manifest_path": string, 35 | } 36 | ], 37 | 38 | "workspace_members": [ PackageId ], 39 | 40 | // Граф зависимостей. 41 | "resolve": { 42 | "nodes": [ 43 | { 44 | "id": PackageId, 45 | "dependencies": [ PackageId ] 46 | } 47 | ] 48 | } 49 | } 50 | ``` 51 | 52 | 53 | # Ошибки компилятора 54 | 55 | Если вы добавите параметр `--message-format json` для команд типа `cargo build`, Cargo 56 | выдаст ошибки и предупреждения компилятора в формате JSON. Сообщения будут выведены в 57 | стандартный поток вывода. Каждое сообщение занимает ровно одну строчку и не содержит в себе 58 | символа перевода строки `\n`. Благодаря этому их можно обрабатывать не дожидаясь окончания сборки. 59 | 60 | Формат сообщений выглядит примерно так: 61 | 62 | ```text 63 | { 64 | // Тип сообщения. 65 | "reason": "compiler-message", 66 | 67 | // Уникальный идентификатор компилируемого пакета. 68 | "package_id": PackageId, 69 | 70 | // Уникальный идентификатор для типа сборки (например, bin) 71 | "target": Target, 72 | 73 | // Сообщение от компилятора в формате JSON. 74 | "message": {...} 75 | } 76 | ``` 77 | 78 | Спецификация пакетов и типов сборки такая же как и у `cargo metadata`. 79 | -------------------------------------------------------------------------------- /src/doc/policies.md: -------------------------------------------------------------------------------- 1 | % Crates.io package policies 2 | 3 | In general, these policies are guidelines. Problems are often contextual, and 4 | exceptional circumstances sometimes require exceptional measures. We plan to 5 | continue to clarify and expand these rules over time as new circumstances 6 | arise. 7 | 8 | # Package Ownership 9 | 10 | We have a first-come, first-served policy on crate names. Upon publishing a 11 | package, the publisher will be made owner of the package on Crates.io. 12 | 13 | If someone wants to take over a package, and the previous owner agrees, the 14 | existing maintainer can add them as an owner, and the new maintainer can remove 15 | them. If necessary, the team may reach out to inactive maintainers and help 16 | mediate the process of ownership transfer. 17 | 18 | # Removal 19 | 20 | Many questions are specialized instances of a more general form: “Under what 21 | circumstances can a package be removed from Crates.io?” 22 | 23 | The short version is that packages are first-come, first-served, and we won’t 24 | attempt to get into policing what exactly makes a legitimate package. We will 25 | do what the law requires us to do, and address flagrant violations of the Rust 26 | Code of Conduct. 27 | 28 | ## Squatting 29 | 30 | We do not have any policies to define 'squatting', and so will not hand over 31 | ownership of a package for that reason. 32 | 33 | 34 | ## The Law 35 | 36 | For issues such as DMCA violations, trademark and copyright infringement, 37 | Crates.io will respect Mozilla Legal’s decisions with regards to content that 38 | is hosted. 39 | 40 | ## Code of Conduct 41 | 42 | The Rust project has a [Code of Conduct] which governs appropriate conduct for 43 | the Rust community. In general, any content on Crates.io that violates the Code 44 | of Conduct may be removed. There are two important, related aspects: 45 | 46 | - We will not be pro-actively monitoring the site for these kinds of violations, 47 | but relying on the community to draw them to our attention. 48 | - “Does this violate the Code of Conduct” is a contextual question that 49 | cannot be directly answered in the hypothetical sense. All of the details 50 | must be taken into consideration in these kinds of situations. 51 | 52 | [Code of Conduct]: https://www.rust-lang.org/conduct.html 53 | -------------------------------------------------------------------------------- /src/doc/index.md: -------------------------------------------------------------------------------- 1 | % Cargo - менеджер пакетов для языка программирования Rust. 2 | 3 | # Установка 4 | 5 | Самый простой способ установить Cargo, это скачать последнюю стабильную версию Rust 6 | используя `rustup` скрипт: 7 | 8 | ```shell 9 | $ curl -sSf https://static.rust-lang.org/rustup.sh | sh 10 | ``` 11 | 12 | После выполнения данного скрипта вы получите последнюю стабильную версию Rust для вашей платформы, а так же последнюю версию Cargo. 13 | 14 | Если вы используете операционную систему Windows, вы можете скачать установщики последней стабильной версии Rust и ночную сборку Cargo. 32-х битная версия ([Rust](https://static.rust-lang.org/dist/rust-1.0.0-i686-pc-windows-gnu.msi) 15 | и [Cargo](https://static.rust-lang.org/cargo-dist/cargo-nightly-i686-pc-windows-gnu.tar.gz)) или 64-х битная версия ([Rust](https://static.rust-lang.org/dist/rust-1.0.0-x86_64-pc-windows-gnu.msi) и [Cargo](https://static.rust-lang.org/cargo-dist/cargo-nightly-x86_64-pc-windows-gnu.tar.gz)) 16 | 17 | Вы так же можете собрать Cargo из исходного кода. 18 | 19 | Чтобы убедиться, что установка прошла успешно, можно воспользоваться командой, которая выводит версию Cargo: 20 | ```shell 21 | $ cargo --version 22 | ``` 23 | 24 | # Давайте начнем 25 | 26 | Чтобы создать новый проект при помощи Cargo, необходимо воспользоваться командой `cargo new`: 27 | 28 | ```shell 29 | $ cargo new hello_world --bin 30 | ``` 31 | 32 | Мы передали аргумент `--bin`, потому что мы создаем исполняемую программу: если мы 33 | решим создать библиотеку, то этот аргумент необходимо убрать. 34 | 35 | Давайте посмотрим, что Cargo сгенерировал для нас: 36 | 37 | ```shell 38 | $ cd hello_world 39 | $ tree . 40 | . 41 | ├── Cargo.toml 42 | └── src 43 | └── main.rs 44 | 45 | 1 directory, 2 files 46 | ``` 47 | 48 | Это все, что нам необходимо для начала. Первым делом давайте посмотрим, что за файл `Cargo.toml`: 49 | 50 | ```toml 51 | [package] 52 | name = "hello_world" 53 | version = "0.1.0" 54 | authors = ["Your Name "] 55 | ``` 56 | 57 | Этот файл называется **манифестом** и содержит в себе все метаданные, которые необходимы Cargo, 58 | чтобы скомпилировать ваш проект. 59 | 60 | Вот, что мы найдем в файле `src/main.rs`: 61 | 62 | ``` 63 | fn main() { 64 | println!("Hello, world!"); 65 | } 66 | ``` 67 | 68 | Cargo сгенерировал “hello world” для нас. Давайте скомпилируем его: 69 | 70 |
$ cargo build
71 |    Compiling hello_world v0.1.0 (file:///path/to/project/hello_world)
73 | 74 | А потом запустим: 75 | 76 | ```shell 77 | $ ./target/debug/hello_world 78 | Hello, world! 79 | ``` 80 | 81 | Вы так же можете использовать `cargo run`, чтобы скомпилировать и запустить проект. Все за одну команду: 82 | 83 |
$ cargo run
84 |      Fresh hello_world v0.1.0 (file:///path/to/project/hello_world)
86 |    Running `target/hello_world`
88 | Hello, world!
89 | 90 | # Двигаемся дальше 91 | 92 | Чтобы получить более подробную информацию о использование Cargo, ознакомьтесь с [Руководством по Cargo](guide.html) 93 | -------------------------------------------------------------------------------- /src/doc/environment-variables.md: -------------------------------------------------------------------------------- 1 | % Environment Variables 2 | 3 | Cargo sets and reads a number of environment variables which your code can detect 4 | or override. Here is a list of the variables Cargo sets, organized by when it interacts 5 | with them: 6 | 7 | # Environment variables Cargo reads 8 | 9 | You can override these environment variables to change Cargo's behavior on your 10 | system: 11 | 12 | * `CARGO_HOME` - Cargo maintains a local cache of the registry index and of git 13 | checkouts of crates. By default these are stored under `$HOME/.cargo`, but 14 | this variable overrides the location of this directory. Once a crate is cached 15 | it is not removed by the clean command. 16 | * `CARGO_TARGET_DIR` - Location of where to place all generated artifacts, 17 | relative to the current working directory. 18 | * `RUSTC` - Instead of running `rustc`, Cargo will execute this specified 19 | compiler instead. 20 | * `RUSTDOC` - Instead of running `rustdoc`, Cargo will execute this specified 21 | `rustdoc` instance instead. 22 | * `RUSTFLAGS` - A space-separated list of custom flags to pass to all compiler 23 | invocations that Cargo performs. In contrast with `cargo rustc`, this is 24 | useful for passing a flag to *all* compiler instances. 25 | 26 | Note that Cargo will also read environment variables for `.cargo/config` 27 | configuration values, as described in [that documentation][config-env] 28 | 29 | [config-env]: config.html#environment-variables 30 | 31 | # Environment variables Cargo sets for crates 32 | 33 | Cargo exposes these environment variables to your crate when it is compiled. To get the 34 | value of any of these variables in a Rust program, do this: 35 | 36 | ``` 37 | let version = env!("CARGO_PKG_VERSION"); 38 | ``` 39 | 40 | `version` will now contain the value of `CARGO_PKG_VERSION`. 41 | 42 | * `CARGO_MANIFEST_DIR` - The directory containing the manifest of your package. 43 | * `CARGO_PKG_VERSION` - The full version of your package. 44 | * `CARGO_PKG_VERSION_MAJOR` - The major version of your package. 45 | * `CARGO_PKG_VERSION_MINOR` - The minor version of your package. 46 | * `CARGO_PKG_VERSION_PATCH` - The patch version of your package. 47 | * `CARGO_PKG_VERSION_PRE` - The pre-release version of your package. 48 | * `CARGO_PKG_AUTHORS` - Colon seperated list of authors from the manifest of your package. 49 | * `CARGO_PKG_NAME` - The name of your package. 50 | * `CARGO_PKG_DESCRIPTION` - The description of your package. 51 | * `CARGO_PKG_HOMEPAGE` - The home page of your package. 52 | 53 | # Environment variables Cargo sets for build scripts 54 | 55 | Cargo sets several environment variables when build scripts are run. Because these variables 56 | are not yet set when the build script is compiled, the above example using `env!` won't work 57 | and instead you'll need to retrieve the values when the build script is run: 58 | 59 | ``` 60 | use std::env; 61 | let out_dir = env::var("OUT_DIR").unwrap(); 62 | ``` 63 | 64 | `out_dir` will now contain the value of `OUT_DIR`. 65 | 66 | * `CARGO_MANIFEST_DIR` - The directory containing the manifest for the package 67 | being built (the package containing the build 68 | script). Also note that this is the value of the 69 | current working directory of the build script when it 70 | starts. 71 | * `CARGO_MANIFEST_LINKS` - the manifest `links` value. 72 | * `CARGO_FEATURE_` - For each activated feature of the package being 73 | built, this environment variable will be present 74 | where `` is the name of the feature uppercased 75 | and having `-` translated to `_`. 76 | * `OUT_DIR` - the folder in which all output should be placed. This folder is 77 | inside the build directory for the package being built, and it is 78 | unique for the package in question. 79 | * `TARGET` - the target triple that is being compiled for. Native code should be 80 | compiled for this triple. Some more information about target 81 | triples can be found in [clang’s own documentation][clang]. 82 | * `HOST` - the host triple of the rust compiler. 83 | * `NUM_JOBS` - the parallelism specified as the top-level parallelism. This can 84 | be useful to pass a `-j` parameter to a system like `make`. 85 | * `OPT_LEVEL`, `DEBUG` - values of the corresponding variables for the 86 | profile currently being built. 87 | * `PROFILE` - name of the profile currently being built (see 88 | [profiles][profile]). 89 | * `DEP__` - For more information about this set of environment 90 | variables, see build script documentation about [`links`][links]. 91 | * `RUSTC`, `RUSTDOC` - the compiler and documentation generator that Cargo has 92 | resolved to use, passed to the build script so it might 93 | use it as well. 94 | 95 | [links]: build-script.html#the-links-manifest-key 96 | [profile]: manifest.html#the-profile-sections 97 | [clang]:http://clang.llvm.org/docs/CrossCompilation.html#target-triple 98 | -------------------------------------------------------------------------------- /src/doc/stylesheets/prism.css: -------------------------------------------------------------------------------- 1 | /* http://prismjs.com/download.html?themes=prism-twilight&languages=markup+css+clike+javascript */ 2 | /** 3 | * prism.js Twilight theme 4 | * Based (more or less) on the Twilight theme originally of Textmate fame. 5 | * @author Remy Bach 6 | */ 7 | code[class*="language-"], 8 | pre[class*="language-"] { 9 | color: white; 10 | direction: ltr; 11 | font-family: Consolas, Monaco, 'Andale Mono', monospace; 12 | text-align: left; 13 | text-shadow: 0 -.1em .2em black; 14 | white-space: pre; 15 | word-spacing: normal; 16 | word-break: normal; 17 | line-height: 1.5; 18 | 19 | -moz-tab-size: 4; 20 | -o-tab-size: 4; 21 | tab-size: 4; 22 | 23 | -webkit-hyphens: none; 24 | -moz-hyphens: none; 25 | -ms-hyphens: none; 26 | hyphens: none; 27 | } 28 | 29 | pre[class*="language-"], 30 | :not(pre) > code[class*="language-"] { 31 | background: hsl(0, 0%, 8%); /* #141414 */ 32 | } 33 | 34 | /* Code blocks */ 35 | pre[class*="language-"] { 36 | border-radius: .5em; 37 | border: .3em solid hsl(0, 0%, 33%); /* #282A2B */ 38 | box-shadow: 1px 1px .5em black inset; 39 | margin: .5em 0; 40 | overflow: auto; 41 | padding: 1em; 42 | } 43 | 44 | pre[class*="language-"]::selection { 45 | /* Safari */ 46 | background: hsl(200, 4%, 16%); /* #282A2B */ 47 | } 48 | 49 | pre[class*="language-"]::selection { 50 | /* Firefox */ 51 | background: hsl(200, 4%, 16%); /* #282A2B */ 52 | } 53 | 54 | /* Text Selection colour */ 55 | pre[class*="language-"]::-moz-selection, pre[class*="language-"] ::-moz-selection, 56 | code[class*="language-"]::-moz-selection, code[class*="language-"] ::-moz-selection { 57 | text-shadow: none; 58 | background: hsla(0, 0%, 93%, 0.15); /* #EDEDED */ 59 | } 60 | 61 | pre[class*="language-"]::selection, pre[class*="language-"] ::selection, 62 | code[class*="language-"]::selection, code[class*="language-"] ::selection { 63 | text-shadow: none; 64 | background: hsla(0, 0%, 93%, 0.15); /* #EDEDED */ 65 | } 66 | 67 | /* Inline code */ 68 | :not(pre) > code[class*="language-"] { 69 | border-radius: .3em; 70 | border: .13em solid hsl(0, 0%, 33%); /* #545454 */ 71 | box-shadow: 1px 1px .3em -.1em black inset; 72 | padding: .15em .2em .05em; 73 | } 74 | 75 | .token.comment, 76 | .token.prolog, 77 | .token.doctype, 78 | .token.cdata { 79 | color: hsl(0, 0%, 47%); /* #777777 */ 80 | } 81 | 82 | .token.punctuation { 83 | opacity: .7; 84 | } 85 | 86 | .namespace { 87 | opacity: .7; 88 | } 89 | 90 | .token.tag, 91 | .token.boolean, 92 | .token.number, 93 | .token.deleted { 94 | color: hsl(14, 58%, 55%); /* #CF6A4C */ 95 | } 96 | 97 | .token.keyword, 98 | .token.property, 99 | .token.selector, 100 | .token.constant, 101 | .token.symbol, 102 | .token.builtin { 103 | color: hsl(53, 89%, 79%); /* #F9EE98 */ 104 | } 105 | 106 | .token.attr-name, 107 | .token.attr-value, 108 | .token.string, 109 | .token.char, 110 | .token.operator, 111 | .token.entity, 112 | .token.url, 113 | .language-css .token.string, 114 | .style .token.string, 115 | .token.variable, 116 | .token.inserted { 117 | color: hsl(76, 21%, 52%); /* #8F9D6A */ 118 | } 119 | 120 | .token.atrule { 121 | color: hsl(218, 22%, 55%); /* #7587A6 */ 122 | } 123 | 124 | .token.regex, 125 | .token.important { 126 | color: hsl(42, 75%, 65%); /* #E9C062 */ 127 | } 128 | 129 | .token.important { 130 | font-weight: bold; 131 | } 132 | 133 | .token.entity { 134 | cursor: help; 135 | } 136 | 137 | pre[data-line] { 138 | padding: 1em 0 1em 3em; 139 | position: relative; 140 | } 141 | 142 | /* Markup */ 143 | .language-markup .token.tag, 144 | .language-markup .token.attr-name, 145 | .language-markup .token.punctuation { 146 | color: hsl(33, 33%, 52%); /* #AC885B */ 147 | } 148 | 149 | /* Make the tokens sit above the line highlight so the colours don't look faded. */ 150 | .token { 151 | position: relative; 152 | z-index: 1; 153 | } 154 | 155 | .line-highlight { 156 | background: -moz-linear-gradient(left, hsla(0, 0%, 33%, .1) 70%, hsla(0, 0%, 33%, 0)); /* #545454 */ 157 | background: -o-linear-gradient(left, hsla(0, 0%, 33%, .1) 70%, hsla(0, 0%, 33%, 0)); /* #545454 */ 158 | background: -webkit-linear-gradient(left, hsla(0, 0%, 33%, .1) 70%, hsla(0, 0%, 33%, 0)); /* #545454 */ 159 | background: hsla(0, 0%, 33%, 0.25); /* #545454 */ 160 | background: linear-gradient(left, hsla(0, 0%, 33%, .1) 70%, hsla(0, 0%, 33%, 0)); /* #545454 */ 161 | border-bottom: 1px dashed hsl(0, 0%, 33%); /* #545454 */ 162 | border-top: 1px dashed hsl(0, 0%, 33%); /* #545454 */ 163 | left: 0; 164 | line-height: inherit; 165 | margin-top: 0.75em; /* Same as .prism’s padding-top */ 166 | padding: inherit 0; 167 | pointer-events: none; 168 | position: absolute; 169 | right: 0; 170 | white-space: pre; 171 | z-index: 0; 172 | } 173 | 174 | .line-highlight:before, 175 | .line-highlight[data-end]:after { 176 | background-color: hsl(215, 15%, 59%); /* #8794A6 */ 177 | border-radius: 999px; 178 | box-shadow: 0 1px white; 179 | color: hsl(24, 20%, 95%); /* #F5F2F0 */ 180 | content: attr(data-start); 181 | font: bold 65%/1.5 sans-serif; 182 | left: .6em; 183 | min-width: 1em; 184 | padding: 0 .5em; 185 | position: absolute; 186 | text-align: center; 187 | text-shadow: none; 188 | top: .4em; 189 | vertical-align: .3em; 190 | } 191 | 192 | .line-highlight[data-end]:after { 193 | bottom: .4em; 194 | content: attr(data-end); 195 | top: auto; 196 | } 197 | 198 | -------------------------------------------------------------------------------- /src/doc/config.md: -------------------------------------------------------------------------------- 1 | % Настройка Cargo 2 | 3 | В данном документе мы расскажем вам, как работает настройка Cargo, используя доступные для 4 | конфигурации ключи и настройки. Для настройке проекта с помощью манифест файла, загляните на 5 | страницу [формат манифеста](manifest.html). 6 | 7 | # Иерархическая структура 8 | 9 | Cargo позволяет делать настройки как для локальных проектов, так и для 10 | всех (как git, например). Cargo также расширяет эту возможность используя иерархическую 11 | структуру. Если, например, Cargo будет вызван в директории `/home/foo/bar/baz`, то поиск 12 | конфигурационных файлов будет осуществлен по следующим директориям: 13 | 14 | * `/home/foo/bar/baz/.cargo/config` 15 | * `/home/foo/bar/.cargo/config` 16 | * `/home/foo/.cargo/config` 17 | * `/home/.cargo/config` 18 | * `/.cargo/config` 19 | 20 | Благодаря такой структуре вы можете указывать конфигурацию для каждого проекта отдельно, и даже, 21 | возможно, добавлять его в вашу систему контроля версий. Вы также можете указать 22 | нужную вам конфигурацию в файле в домашней директории. 23 | 24 | # Формат конфигурационного файла 25 | 26 | Все конфигурационные файлы хранятся в [TOML формате][toml] (как манифесты), 27 | в простом формате ключ-значение, которые хранятся внутри секций (таблиц), а потом будут объединены. 28 | 29 | [toml]: https://github.com/toml-lang/toml 30 | 31 | # Ключи для конфигурации 32 | 33 | Все последующие ключи являются опциональными. Также стоит ответить, что мы указывали 34 | значения по умолчанию для каждого значения. 35 | 36 | Ключи для значений, которые указывают на определенную программу, могут быть в формате абсолютного 37 | пути, относительного, а также можно просто указать название программы. Абсолютные пути и 38 | название программ используются как есть. Относительные пути используются исходя из родительской 39 | директории, в которой расположена директория `.cargo`, в которой находится конфигурационный файл. 40 | 41 | ```toml 42 | # Массив путей к локальным репозиториям, которые будут переопределены в качестве 43 | # зависимостей. Для более подробной информации смотрите документ Specifying Dependencies. 44 | paths = ["/path/to/override"] 45 | 46 | [cargo-new] 47 | # Настройки для имени/email, которые будут помещены в блок `authors` в новых Cargo.toml 48 | # Если эти параметры не указаны, будут взяты параметры из конфигурации `git`. А, если и их нет 49 | # запишутся `$USER` и `$EMAIL`. 50 | name = "..." 51 | email = "..." 52 | 53 | # По умолчанию команда `cargo new` создан новый Git репозиторий. Это значение может быть 54 | # изменено на `hg`, тогда будет создан Mercurial репозиторий, или `none`, чтобы отключить 55 | # данный функционал. 56 | vcs = "none" 57 | 58 | # Для следующего раздела, $triple относится к любой возможной целевой платформой, 59 | # не к строкову литералу "$triple", и будет применяться каждый раз, когда будет сборка 60 | # для целевой платформы. 61 | [target] 62 | # Для сборок Cargo, для которых не указан параметр --target, будет использован компоновщик 63 | # переданный в rustc (с помощью `-C linker=`). По умолчанию этот флаг не передан 64 | # как параметр компилятора. 65 | linker = ".." 66 | 67 | [target.$triple] 68 | # Этот раздел похож на раздел, который был описан выше, но тут указывается конкретная 69 | # целевая платформа, которая будет скомпилирована. 70 | linker = ".." 71 | # пользовательские настройки будут переданы в компилятор, каждый раз когда будет $triple 72 | # вызвана компиляция для целевой платформы. 73 | # этот параметр переопределит build.rustflags, если он указан 74 | rustflags = ["..", ".."] 75 | 76 | # Настройки для реестра 77 | [registry] 78 | index = "..." # Ссылка для индекса реестра (по умолчанию - центральный репозиторий) 79 | token = "..." # Ключ доступа (можно найти на сайте центрального репозитория) 80 | 81 | [http] 82 | proxy = "..." # HTTP прокси. Используется для HTTP запросов (по умолчанию не указан) 83 | timeout = 60000 # Таймаут для каждого HTTP запроса, в миллисекундах 84 | cainfo = "cert.pem" # Путь до ключа Центра Сертификации (опционально) 85 | 86 | [build] 87 | jobs = 1 # количество параллельно выполняемых заданий, по умолчанию - 88 | # количество ЦП 89 | rustc = "rustc" # компилятор rust 90 | rustdoc = "rustdoc" # инструмент генерации документации 91 | target = "triple" # build for the target triple 92 | target-dir = "target" # путь к директории, в которой будет скомпилированный проект 93 | rustflags = ["..", ".."] # настройки, которые будут переданы компилятору 94 | 95 | [term] 96 | verbose = false # предоставлять ли cargo развернутый вывод 97 | color = 'auto' # предоставлять ли cargo цветной вывод 98 | 99 | # Конфигурация сети 100 | [net] 101 | retry = 2 # сколько раз будет вызвана попытка повторной отправки сигнала 102 | 103 | # Псевдонимы для команд Cargo. Первые 3 псевдонима встроены. 104 | # Если вы хотите передать параметры в псевдоним, в которых есть пробелы, то используйте список. 105 | [alias] 106 | b = "build" 107 | t = "test" 108 | r = "run" 109 | rr = "run --release" 110 | space_example = ["run", "--release", "--", "\"command list\""] 111 | ``` 112 | 113 | # Переменные среды 114 | 115 | Cargo также можно настроить с помощью переменных среды, в дополнение к 116 | TOML конфигурационным файлам. Для каждой настройки `foo.bar` 117 | есть переменная среды `CARGO_FOO_BAR` для которой также можно указать значение. 118 | Например, настройка `build.jobs` может быть указана с помощью переменной среды `CARGO_BUILD_JOBS`. 119 | 120 | Приоритет переменных среды выше, чем приоритет значений в TOML конфигурациях. В данный момент 121 | в качестве значений для переменных среды можно указывать только целочисленные, логические и 122 | строковые. 123 | 124 | В дополнение к вышеперечисленному, Cargo работает и с другими [переменными среды][env]. 125 | 126 | [env]: environment-variables.html 127 | -------------------------------------------------------------------------------- /src/doc/source-replacement.md: -------------------------------------------------------------------------------- 1 | % Replacing sources 2 | 3 | Cargo supports the ability to **replace one source with another** to express 4 | strategies along the lines of mirrors or vendoring dependencies. Configuration 5 | is currently done through the [`.cargo/config` configuration][config] mechanism, 6 | like so: 7 | 8 | [config]: config.html 9 | 10 | ```toml 11 | # The `source` table is where all keys related to source-replacement 12 | # are stored. 13 | [source] 14 | 15 | # Under the `source` table are a number of other tables whose keys are a 16 | # name for the relevant source. For example this section defines a new 17 | # source, called `my-awesome-source`, which comes from a directory 18 | # located at `vendor` relative to the directory containing this `.cargo/config` 19 | # file 20 | [source.my-awesome-source] 21 | directory = "vendor" 22 | 23 | # The crates.io default source for crates is available under the name 24 | # "crates-io", and here we use the `replace-with` key to indicate that it's 25 | # replaced with our source above. 26 | [source.crates-io] 27 | replace-with = "my-awesome-source" 28 | ``` 29 | 30 | With this configuration Cargo attempts to look up all crates in the directory 31 | "vendor" rather than querying the online registry at crates.io. Using source 32 | replacement Cargo can express: 33 | 34 | * Vendoring - custom sources can be defined which represent crates on the local 35 | filesystem. These sources are subsets of the source that they're replacing and 36 | can be checked into projects if necessary. 37 | 38 | * Mirroring - sources can be replaced with an equivalent version which acts as a 39 | cache for crates.io itself. 40 | 41 | Cargo has a core assumption about source replacement that the source code is 42 | exactly the same from both sources. In our above example Cargo assumes that all 43 | of the crates coming from `my-awesome-source` are the exact same as the copies 44 | from `crates-io`. Note that this also means that `my-awesome-source` is not 45 | allowed to have crates which are not present in the `crates-io` source. 46 | 47 | As a consequence, source replacement is not appropriate for situations such as 48 | patching a dependency or a private registry. Cargo supports patching 49 | dependencies through the usage of [the `[replace]` key][replace-section], and 50 | private registry support is planned for a future version of Cargo. 51 | 52 | [replace-section]: manifest.html#the-replace-section 53 | 54 | ## Configuration 55 | 56 | Configuration of replacement sources is done through [`.cargo/config`][config] 57 | and the full set of available keys are: 58 | 59 | ```toml 60 | # Each source has its own table where the key is the name of the source 61 | [source.the-source-name] 62 | 63 | # Indicate that `the-source-name` will be replaced with `another-source`, 64 | # defined elsewhere 65 | replace-with = "another-source" 66 | 67 | # Available kinds of sources that can be specified (described below) 68 | registry = "https://example.com/path/to/index" 69 | local-registry = "path/to/registry" 70 | directory = "path/to/vendor" 71 | ``` 72 | 73 | The `crates-io` represents the crates.io online registry (default source of 74 | crates) and can be replaced with: 75 | 76 | ```toml 77 | [source.crates-io] 78 | replace-with = 'another-source' 79 | ``` 80 | 81 | ## Registry Sources 82 | 83 | A "registry source" is one that is the same as crates.io itself. That is, it has 84 | an index served in a git repository which matches the format of the 85 | [crates.io index](https://github.com/rust-lang/crates.io-index). That repository 86 | then has configuration indicating where to download crates from. 87 | 88 | Currently there is not an already-available project for setting up a mirror of 89 | crates.io. Stay tuned though! 90 | 91 | ## Local Registry Sources 92 | 93 | A "local registry source" is intended to be a subset of another registry 94 | source, but available on the local filesystem (aka vendoring). Local registries 95 | are downloaded ahead of time, typically sync'd with a `Cargo.lock`, and are 96 | made up of a set of `*.crate` files and an index like the normal registry is. 97 | 98 | The primary way to manage and crate local registry sources is through the 99 | [`cargo-local-registry`][cargo-local-registry] subcommand, available on 100 | crates.io and can be installed with `cargo install cargo-local-registry`. 101 | 102 | [cargo-local-registry]: https://crates.io/crates/cargo-local-registry 103 | 104 | Local registries are contained within one directory and contain a number of 105 | `*.crate` files downloaded from crates.io as well as an `index` directory with 106 | the same format as the crates.io-index project (populated with just entries for 107 | the crates that are present). 108 | 109 | ## Directory Sources 110 | 111 | A "directory source" is similar to a local registry source where it contains a 112 | number of crates available on the local filesystem, suitable for vendoring 113 | dependencies. Also like local registries, directory sources can primarily be 114 | managed by an external subcommand, [`cargo-vendor`][cargo-vendor], which can be 115 | installed with `cargo install cargo-vendor`. 116 | 117 | [cargo-vendor]: https://crates.io/crates/cargo-vendor 118 | 119 | Directory sources are distinct from local registries though in that they contain 120 | the unpacked version of `*.crate` files, making it more suitable in some 121 | situations to check everything into source control. A directory source is just a 122 | directory containing a number of other directories which contain the source code 123 | for crates (the unpacked version of `*.crate` files). Currently no restriction 124 | is placed on the name of each directory. 125 | 126 | Each crate in a directory source also has an associated metadata file indicating 127 | the checksum of each file in the crate to protect against accidental 128 | modifications. 129 | -------------------------------------------------------------------------------- /src/doc/javascripts/prism.js: -------------------------------------------------------------------------------- 1 | /* http://prismjs.com/download.html?themes=prism&languages=markup+css+clike+javascript */ 2 | self="undefined"!=typeof window?window:"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope?self:{};var Prism=function(){var e=/\blang(?:uage)?-(?!\*)(\w+)\b/i,t=self.Prism={util:{encode:function(e){return e instanceof n?new n(e.type,t.util.encode(e.content),e.alias):"Array"===t.util.type(e)?e.map(t.util.encode):e.replace(/&/g,"&").replace(/e.length)break e;if(!(d instanceof a)){c.lastIndex=0;var m=c.exec(d);if(m){u&&(f=m[1].length);var y=m.index-1+f,m=m[0].slice(f),v=m.length,k=y+v,b=d.slice(0,y+1),w=d.slice(k+1),N=[p,1];b&&N.push(b);var O=new a(l,g?t.tokenize(m,g):m,h);N.push(O),w&&N.push(w),Array.prototype.splice.apply(r,N)}}}}}return r},hooks:{all:{},add:function(e,n){var a=t.hooks.all;a[e]=a[e]||[],a[e].push(n)},run:function(e,n){var a=t.hooks.all[e];if(a&&a.length)for(var r,i=0;r=a[i++];)r(n)}}},n=t.Token=function(e,t,n){this.type=e,this.content=t,this.alias=n};if(n.stringify=function(e,a,r){if("string"==typeof e)return e;if("[object Array]"==Object.prototype.toString.call(e))return e.map(function(t){return n.stringify(t,a,e)}).join("");var i={type:e.type,content:n.stringify(e.content,a,r),tag:"span",classes:["token",e.type],attributes:{},language:a,parent:r};if("comment"==i.type&&(i.attributes.spellcheck="true"),e.alias){var l="Array"===t.util.type(e.alias)?e.alias:[e.alias];Array.prototype.push.apply(i.classes,l)}t.hooks.run("wrap",i);var o="";for(var s in i.attributes)o+=s+'="'+(i.attributes[s]||"")+'"';return"<"+i.tag+' class="'+i.classes.join(" ")+'" '+o+">"+i.content+""},!self.document)return self.addEventListener?(self.addEventListener("message",function(e){var n=JSON.parse(e.data),a=n.language,r=n.code;self.postMessage(JSON.stringify(t.util.encode(t.tokenize(r,t.languages[a])))),self.close()},!1),self.Prism):self.Prism;var a=document.getElementsByTagName("script");return a=a[a.length-1],a&&(t.filename=a.src,document.addEventListener&&!a.hasAttribute("data-manual")&&document.addEventListener("DOMContentLoaded",t.highlightAll)),self.Prism}();"undefined"!=typeof module&&module.exports&&(module.exports=Prism);; 3 | Prism.languages.markup={comment://g,prolog:/<\?.+?\?>/,doctype://,cdata://i,tag:{pattern:/<\/?[\w:-]+\s*(?:\s+[\w:-]+(?:=(?:("|')(\\?[\w\W])*?\1|[^\s'">=]+))?\s*)*\/?>/gi,inside:{tag:{pattern:/^<\/?[\w:-]+/i,inside:{punctuation:/^<\/?/,namespace:/^[\w-]+?:/}},"attr-value":{pattern:/=(?:('|")[\w\W]*?(\1)|[^\s>]+)/gi,inside:{punctuation:/=|>|"/g}},punctuation:/\/?>/g,"attr-name":{pattern:/[\w:-]+/g,inside:{namespace:/^[\w-]+?:/}}}},entity:/\&#?[\da-z]{1,8};/gi},Prism.hooks.add("wrap",function(t){"entity"===t.type&&(t.attributes.title=t.content.replace(/&/,"&"))});; 4 | Prism.languages.css={comment:/\/\*[\w\W]*?\*\//g,atrule:{pattern:/@[\w-]+?.*?(;|(?=\s*{))/gi,inside:{punctuation:/[;:]/g}},url:/url\((["']?).*?\1\)/gi,selector:/[^\{\}\s][^\{\};]*(?=\s*\{)/g,property:/(\b|\B)[\w-]+(?=\s*:)/gi,string:/("|')(\\?.)*?\1/g,important:/\B!important\b/gi,punctuation:/[\{\};:]/g,"function":/[-a-z0-9]+(?=\()/gi},Prism.languages.markup&&Prism.languages.insertBefore("markup","tag",{style:{pattern:/[\w\W]*?<\/style>/gi,inside:{tag:{pattern:/|<\/style>/gi,inside:Prism.languages.markup.tag.inside},rest:Prism.languages.css}}});; 5 | Prism.languages.clike={comment:[{pattern:/(^|[^\\])\/\*[\w\W]*?\*\//g,lookbehind:!0},{pattern:/(^|[^\\:])\/\/.*?(\r?\n|$)/g,lookbehind:!0}],string:/("|')(\\?.)*?\1/g,"class-name":{pattern:/((?:(?:class|interface|extends|implements|trait|instanceof|new)\s+)|(?:catch\s+\())[a-z0-9_\.\\]+/gi,lookbehind:!0,inside:{punctuation:/(\.|\\)/}},keyword:/\b(if|else|while|do|for|return|in|instanceof|function|new|try|throw|catch|finally|null|break|continue)\b/g,"boolean":/\b(true|false)\b/g,"function":{pattern:/[a-z0-9_]+\(/gi,inside:{punctuation:/\(/}},number:/\b-?(0x[\dA-Fa-f]+|\d*\.?\d+([Ee]-?\d+)?)\b/g,operator:/[-+]{1,2}|!|<=?|>=?|={1,3}|&{1,2}|\|?\||\?|\*|\/|\~|\^|\%/g,ignore:/&(lt|gt|amp);/gi,punctuation:/[{}[\];(),.:]/g};; 6 | Prism.languages.javascript=Prism.languages.extend("clike",{keyword:/\b(break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|false|finally|for|function|get|if|implements|import|in|instanceof|interface|let|new|null|package|private|protected|public|return|set|static|super|switch|this|throw|true|try|typeof|var|void|while|with|yield)\b/g,number:/\b-?(0x[\dA-Fa-f]+|\d*\.?\d+([Ee]-?\d+)?|NaN|-?Infinity)\b/g}),Prism.languages.insertBefore("javascript","keyword",{regex:{pattern:/(^|[^/])\/(?!\/)(\[.+?]|\\.|[^/\r\n])+\/[gim]{0,3}(?=\s*($|[\r\n,.;})]))/g,lookbehind:!0}}),Prism.languages.markup&&Prism.languages.insertBefore("markup","tag",{script:{pattern:/[\w\W]*?<\/script>/gi,inside:{tag:{pattern:/|<\/script>/gi,inside:Prism.languages.markup.tag.inside},rest:Prism.languages.javascript}}});; 7 | -------------------------------------------------------------------------------- /src/doc/stylesheets/all.css: -------------------------------------------------------------------------------- 1 | html { 2 | background: url("../images/noise.png"); 3 | background-color: #3b6837; 4 | } 5 | 6 | main, #header { width: 900px; } 7 | 8 | * { 9 | box-sizing: border-box; 10 | } 11 | 12 | body { 13 | display: -webkit-flex; 14 | display: flex; 15 | -webkit-flex-direction: column; 16 | flex-direction: column; 17 | -webkit-align-items: center; 18 | align-items: center; 19 | font-family: sans-serif; 20 | } 21 | 22 | a { color: #00ac5b; text-decoration: none; } 23 | a:hover { color: #00793f; } 24 | 25 | h1 { 26 | font-size: 24px; 27 | margin: 20px 0 10px 0; 28 | font-weight: bold; 29 | color: #b64790; 30 | } 31 | 32 | h1 code:not(.highlight) { 33 | color: #d9a700; 34 | vertical-align: bottom; 35 | } 36 | h1 a, h2 a { color: #b64790; text-decoration: none; } 37 | h1:hover a, h2:hover a { color: #A03D7E; } 38 | h1:hover a:after, 39 | h2:hover a:after { content: '\2002\00a7\2002'; } 40 | :target { background: rgba(239, 242, 178, 1); padding: 5px; } 41 | 42 | h1.title { /* style rustdoc-generated title */ 43 | width: 100%; 44 | padding: 40px 20px 40px 60px; 45 | background-color: #edebdd; 46 | margin-bottom: 20px; 47 | -webkit-border-radius: 5px; 48 | -moz-border-radius: 5px; 49 | -ms-border-radius: 5px; 50 | border-radius: 5px; 51 | margin: 0; 52 | color: #383838; 53 | font-size: 2em; 54 | background-image: url(../images/circle-with-i.png); 55 | background-repeat: no-repeat; 56 | background-position: 20px center; 57 | } 58 | 59 | h2 { 60 | font-size: 18px; 61 | margin: 15px 0 5px 0; 62 | color: #b64790; 63 | font-weight: bold; 64 | } 65 | 66 | h2 code:not(.highlight) { color: #d9a700; } 67 | 68 | code:not(.highlight) { 69 | font-family: monospace; 70 | color: #b64790; 71 | } 72 | 73 | main { 74 | display: -webkit-flex; 75 | display: flex; 76 | -webkit-flex-direction: column; 77 | flex-direction: column; 78 | 79 | width: 100%; 80 | max-width: 900px; 81 | margin-bottom: 10px; 82 | 83 | background-color: #f9f7ec; 84 | padding: 15px; 85 | 86 | -webkit-border-radius: 10px; 87 | -moz-border-radius: 10px; 88 | -ms-border-radius: 10px; 89 | border-radius: 10px; 90 | box-shadow: 0px 0px 5px 2px #3b6837; 91 | border: 5px solid #62865f; 92 | color: #383838; 93 | } 94 | 95 | main > p:first-child { 96 | font-weight: 500; 97 | margin-top: 3px; 98 | padding-bottom: 15px; 99 | border-bottom: 1px solid #62865f; 100 | text-align: center; 101 | } 102 | 103 | main p:first-child a { color: #3b6837; } 104 | main p:first-child a:hover { color: #62865f; } 105 | 106 | main p, main ul { 107 | /* color: #3b6837; */ 108 | margin: 10px 0; 109 | line-height: 150%; 110 | } 111 | 112 | main ul { margin-left: 20px; } 113 | main li { list-style-type: disc; } 114 | main strong { font-weight: bold; } 115 | 116 | img.logo { 117 | align-self: center; 118 | margin-bottom: 10px; 119 | } 120 | 121 | pre { 122 | padding: 10px; 123 | margin: 10px 0; 124 | /* border: 1px solid #cad0d0; */ 125 | border-radius: 4px; 126 | max-width: calc(100vw - 45px); 127 | overflow-x: auto; 128 | 129 | background: #383838 !important; 130 | color: white; 131 | padding: 20px; 132 | 133 | /* override prism.js styles */ 134 | font-size: 1em !important; 135 | border: none !important; 136 | box-shadow: none !important; 137 | text-shadow: none !important; 138 | } 139 | 140 | pre code { 141 | text-shadow: none !important; 142 | } 143 | 144 | footer { 145 | padding: 40px; 146 | width: 900px; 147 | } 148 | footer a { 149 | color: white; 150 | } 151 | footer a:hover { 152 | color: #e6e6e6; 153 | } 154 | footer .sep, #header .sep { color: #284725; } 155 | footer .sep { margin: 0 10px; } 156 | #header .sep { margin-left: 10px; } 157 | 158 | .headerlink { 159 | display: none; 160 | text-decoration: none; 161 | } 162 | .fork-me { 163 | position:absolute; 164 | top:0; 165 | right:0; 166 | } 167 | 168 | .token.toml-section { color: #CB4B16; } 169 | .token.toml-key { color: #268BD2; } 170 | 171 | /* Rust code highlighting */ 172 | pre.rust .kw { color: #8959A8; } 173 | pre.rust .kw-2, pre.rust .prelude-ty { color: #4271AE; } 174 | pre.rust .number, pre.rust .string { color: #718C00; } 175 | pre.rust .self, pre.rust .boolval, pre.rust .prelude-val, 176 | pre.rust .attribute, pre.rust .attribute .ident { color: #C82829; } 177 | pre.rust .comment { color: #8E908C; } 178 | pre.rust .doccomment { color: #4D4D4C; } 179 | pre.rust .macro, pre.rust .macro-nonterminal { color: #3E999F; } 180 | pre.rust .lifetime { color: #B76514; } 181 | code span.s1 { color: #2AA198; } 182 | 183 | table th { border-bottom: 1px solid black; } 184 | table td, table th { padding: 5px 10px; } 185 | 186 | #header { 187 | color: white; 188 | position: relative; 189 | height: 100px; 190 | display: -webkit-flex; 191 | display: flex; 192 | -webkit-align-items: center; 193 | align-items: center; 194 | } 195 | #header h1 { font-size: 2em; } 196 | #header a, #header h1 { color: white; text-decoration: none; } 197 | #header a:hover { color: #d9d9d9; } 198 | 199 | #header input.search { 200 | border: none; 201 | color: black; 202 | outline: 0; 203 | margin-left: 30px; 204 | padding: 5px 5px 5px 25px; 205 | background-image: url(../images/search.png); 206 | background-repeat: no-repeat; 207 | background-position: 6px 6px; 208 | -webkit-border-radius: 15px; 209 | -moz-border-radius: 15px; 210 | -ms-border-radius: 15px; 211 | border-radius: 15px; 212 | } 213 | 214 | #header .nav { 215 | -webkit-flex-grow: 2; 216 | flex-grow: 2; 217 | text-align: right; 218 | } 219 | 220 | button.dropdown, a.dropdown { cursor: pointer; } 221 | button.dropdown .arrow, a.dropdown .arrow { 222 | font-size: 50%; display: inline-block; vertical-align: middle; 223 | } 224 | button.dropdown .arrow::after, a.dropdown .arrow::after { content: "▼"; } 225 | button.active.dropdown .arrow::after, a.active.dropdown .arrow::after { 226 | content: "▲"; 227 | } 228 | 229 | button { 230 | background: none; 231 | outline: 0; 232 | border: 0; 233 | padding: 10px; 234 | color: white; 235 | } 236 | 237 | button.active { 238 | background:#2a4f27; 239 | box-shadow:inset -2px 2px 4px 0 #243d26 240 | } 241 | 242 | ul.dropdown { 243 | display: none; 244 | visibility: none; 245 | position: absolute; 246 | top: 100%; 247 | right: 0; 248 | width: 100%; 249 | min-width: 150px; 250 | opacity: 0; 251 | margin: 0; 252 | text-align: left; 253 | padding: 0; 254 | background: white; 255 | border: 1px solid #d5d3cb; 256 | list-style: none; 257 | z-index: 10; 258 | -webkit-border-radius: 5px; 259 | -moz-border-radius: 5px; 260 | -ms-border-radius: 5px; 261 | border-radius: 5px; 262 | } 263 | 264 | ul.dropdown li a { 265 | font-size: 90%; 266 | width: 100%; 267 | display: inline-block; 268 | padding: 8px 10px; 269 | text-decoration: none; 270 | color: #383838 !important; 271 | } 272 | 273 | ul.dropdown li a:hover { 274 | background: #5e5e5e; 275 | color: white !important; 276 | } 277 | ul.dropdown li.last { border-top: 1px solid #d5d3cb; } 278 | ul.dropdown.open { 279 | display: block; 280 | visibility: visible; 281 | opacity: 1; 282 | } 283 | .dropdown-container { 284 | display: inline-block; 285 | position: relative; 286 | } 287 | 288 | p > img { 289 | max-width: 100%; 290 | } 291 | -------------------------------------------------------------------------------- /src/doc/stylesheets/normalize.css: -------------------------------------------------------------------------------- 1 | /*! normalize.css v2.0.1 | MIT License | git.io/normalize */ 2 | 3 | /* ========================================================================== 4 | HTML5 display definitions 5 | ========================================================================== */ 6 | 7 | /* 8 | * Corrects `block` display not defined in IE 8/9. 9 | */ 10 | 11 | article, 12 | aside, 13 | details, 14 | figcaption, 15 | figure, 16 | footer, 17 | header, 18 | hgroup, 19 | nav, 20 | section, 21 | summary { 22 | display: block; 23 | } 24 | 25 | /* 26 | * Corrects `inline-block` display not defined in IE 8/9. 27 | */ 28 | 29 | audio, 30 | canvas, 31 | video { 32 | display: inline-block; 33 | } 34 | 35 | /* 36 | * Prevents modern browsers from displaying `audio` without controls. 37 | * Remove excess height in iOS 5 devices. 38 | */ 39 | 40 | audio:not([controls]) { 41 | display: none; 42 | height: 0; 43 | } 44 | 45 | /* 46 | * Addresses styling for `hidden` attribute not present in IE 8/9. 47 | */ 48 | 49 | [hidden] { 50 | display: none; 51 | } 52 | 53 | /* ========================================================================== 54 | Base 55 | ========================================================================== */ 56 | 57 | /* 58 | * 1. Sets default font family to sans-serif. 59 | * 2. Prevents iOS text size adjust after orientation change, without disabling 60 | * user zoom. 61 | */ 62 | 63 | html { 64 | font-family: sans-serif; /* 1 */ 65 | -webkit-text-size-adjust: 100%; /* 2 */ 66 | -ms-text-size-adjust: 100%; /* 2 */ 67 | } 68 | 69 | /* 70 | * Removes default margin. 71 | */ 72 | 73 | body { 74 | margin: 0; 75 | } 76 | 77 | /* ========================================================================== 78 | Links 79 | ========================================================================== */ 80 | 81 | /* 82 | * Addresses `outline` inconsistency between Chrome and other browsers. 83 | */ 84 | 85 | a:focus { 86 | outline: thin dotted; 87 | } 88 | 89 | /* 90 | * Improves readability when focused and also mouse hovered in all browsers. 91 | */ 92 | 93 | a:active, 94 | a:hover { 95 | outline: 0; 96 | } 97 | 98 | /* ========================================================================== 99 | Typography 100 | ========================================================================== */ 101 | 102 | /* 103 | * Addresses `h1` font sizes within `section` and `article` in Firefox 4+, 104 | * Safari 5, and Chrome. 105 | */ 106 | 107 | h1 { 108 | font-size: 2em; 109 | } 110 | 111 | /* 112 | * Addresses styling not present in IE 8/9, Safari 5, and Chrome. 113 | */ 114 | 115 | abbr[title] { 116 | border-bottom: 1px dotted; 117 | } 118 | 119 | /* 120 | * Addresses style set to `bolder` in Firefox 4+, Safari 5, and Chrome. 121 | */ 122 | 123 | b, 124 | strong { 125 | font-weight: bold; 126 | } 127 | 128 | /* 129 | * Addresses styling not present in Safari 5 and Chrome. 130 | */ 131 | 132 | dfn { 133 | font-style: italic; 134 | } 135 | 136 | /* 137 | * Addresses styling not present in IE 8/9. 138 | */ 139 | 140 | mark { 141 | background: #ff0; 142 | color: #000; 143 | } 144 | 145 | 146 | /* 147 | * Corrects font family set oddly in Safari 5 and Chrome. 148 | */ 149 | 150 | code, 151 | kbd, 152 | pre, 153 | samp { 154 | font-family: monospace, serif; 155 | font-size: 1em; 156 | } 157 | 158 | /* 159 | * Improves readability of pre-formatted text in all browsers. 160 | */ 161 | 162 | pre { 163 | white-space: pre; 164 | white-space: pre-wrap; 165 | word-wrap: break-word; 166 | } 167 | 168 | /* 169 | * Sets consistent quote types. 170 | */ 171 | 172 | q { 173 | quotes: "\201C" "\201D" "\2018" "\2019"; 174 | } 175 | 176 | /* 177 | * Addresses inconsistent and variable font size in all browsers. 178 | */ 179 | 180 | small { 181 | font-size: 80%; 182 | } 183 | 184 | /* 185 | * Prevents `sub` and `sup` affecting `line-height` in all browsers. 186 | */ 187 | 188 | sub, 189 | sup { 190 | font-size: 75%; 191 | line-height: 0; 192 | position: relative; 193 | vertical-align: baseline; 194 | } 195 | 196 | sup { 197 | top: -0.5em; 198 | } 199 | 200 | sub { 201 | bottom: -0.25em; 202 | } 203 | 204 | /* ========================================================================== 205 | Embedded content 206 | ========================================================================== */ 207 | 208 | /* 209 | * Removes border when inside `a` element in IE 8/9. 210 | */ 211 | 212 | img { 213 | border: 0; 214 | } 215 | 216 | /* 217 | * Corrects overflow displayed oddly in IE 9. 218 | */ 219 | 220 | svg:not(:root) { 221 | overflow: hidden; 222 | } 223 | 224 | /* ========================================================================== 225 | Figures 226 | ========================================================================== */ 227 | 228 | /* 229 | * Addresses margin not present in IE 8/9 and Safari 5. 230 | */ 231 | 232 | figure { 233 | margin: 0; 234 | } 235 | 236 | /* ========================================================================== 237 | Forms 238 | ========================================================================== */ 239 | 240 | /* 241 | * Define consistent border, margin, and padding. 242 | */ 243 | 244 | fieldset { 245 | border: 1px solid #c0c0c0; 246 | margin: 0 2px; 247 | padding: 0.35em 0.625em 0.75em; 248 | } 249 | 250 | /* 251 | * 1. Corrects color not being inherited in IE 8/9. 252 | * 2. Remove padding so people aren't caught out if they zero out fieldsets. 253 | */ 254 | 255 | legend { 256 | border: 0; /* 1 */ 257 | padding: 0; /* 2 */ 258 | } 259 | 260 | /* 261 | * 1. Corrects font family not being inherited in all browsers. 262 | * 2. Corrects font size not being inherited in all browsers. 263 | * 3. Addresses margins set differently in Firefox 4+, Safari 5, and Chrome 264 | */ 265 | 266 | button, 267 | input, 268 | select, 269 | textarea { 270 | font-family: inherit; /* 1 */ 271 | font-size: 100%; /* 2 */ 272 | margin: 0; /* 3 */ 273 | } 274 | 275 | /* 276 | * Addresses Firefox 4+ setting `line-height` on `input` using `!important` in 277 | * the UA stylesheet. 278 | */ 279 | 280 | button, 281 | input { 282 | line-height: normal; 283 | } 284 | 285 | /* 286 | * 1. Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio` 287 | * and `video` controls. 288 | * 2. Corrects inability to style clickable `input` types in iOS. 289 | * 3. Improves usability and consistency of cursor style between image-type 290 | * `input` and others. 291 | */ 292 | 293 | button, 294 | html input[type="button"], /* 1 */ 295 | input[type="reset"], 296 | input[type="submit"] { 297 | -webkit-appearance: button; /* 2 */ 298 | cursor: pointer; /* 3 */ 299 | } 300 | 301 | /* 302 | * Re-set default cursor for disabled elements. 303 | */ 304 | 305 | button[disabled], 306 | input[disabled] { 307 | cursor: default; 308 | } 309 | 310 | /* 311 | * 1. Addresses box sizing set to `content-box` in IE 8/9. 312 | * 2. Removes excess padding in IE 8/9. 313 | */ 314 | 315 | input[type="checkbox"], 316 | input[type="radio"] { 317 | box-sizing: border-box; /* 1 */ 318 | padding: 0; /* 2 */ 319 | } 320 | 321 | /* 322 | * 1. Addresses `appearance` set to `searchfield` in Safari 5 and Chrome. 323 | * 2. Addresses `box-sizing` set to `border-box` in Safari 5 and Chrome 324 | * (include `-moz` to future-proof). 325 | */ 326 | 327 | input[type="search"] { 328 | -webkit-appearance: textfield; /* 1 */ 329 | -moz-box-sizing: content-box; 330 | -webkit-box-sizing: content-box; /* 2 */ 331 | box-sizing: content-box; 332 | } 333 | 334 | /* 335 | * Removes inner padding and search cancel button in Safari 5 and Chrome 336 | * on OS X. 337 | */ 338 | 339 | input[type="search"]::-webkit-search-cancel-button, 340 | input[type="search"]::-webkit-search-decoration { 341 | -webkit-appearance: none; 342 | } 343 | 344 | /* 345 | * Removes inner padding and border in Firefox 4+. 346 | */ 347 | 348 | button::-moz-focus-inner, 349 | input::-moz-focus-inner { 350 | border: 0; 351 | padding: 0; 352 | } 353 | 354 | /* 355 | * 1. Removes default vertical scrollbar in IE 8/9. 356 | * 2. Improves readability and alignment in all browsers. 357 | */ 358 | 359 | textarea { 360 | overflow: auto; /* 1 */ 361 | vertical-align: top; /* 2 */ 362 | } 363 | 364 | /* ========================================================================== 365 | Tables 366 | ========================================================================== */ 367 | 368 | /* 369 | * Remove most spacing between table cells. 370 | */ 371 | 372 | table { 373 | border-collapse: collapse; 374 | border-spacing: 0; 375 | } -------------------------------------------------------------------------------- /src/doc/faq.md: -------------------------------------------------------------------------------- 1 | % Frequently Asked Questions 2 | 3 | # Is the plan to use GitHub as a package repository? 4 | 5 | No. The plan for Cargo is to use [crates.io], like npm or Rubygems do with 6 | npmjs.org and rubygems.org. 7 | 8 | We plan to support git repositories as a source of packages forever, 9 | because they can be used for early development and temporary patches, 10 | even when people use the registry as the primary source of packages. 11 | 12 | # Why build crates.io rather than use GitHub as a registry? 13 | 14 | We think that it’s very important to support multiple ways to download 15 | packages, including downloading from GitHub and copying packages into 16 | your project itself. 17 | 18 | That said, we think that [crates.io] offers a number of important benefits, and 19 | will likely become the primary way that people download packages in Cargo. 20 | 21 | For precedent, both Node.js’s [npm][1] and Ruby’s [bundler][2] support both a 22 | central registry model as well as a Git-based model, and most packages 23 | are downloaded through the registry in those ecosystems, with an 24 | important minority of packages making use of git-based packages. 25 | 26 | [1]: https://www.npmjs.org 27 | [2]: https://bundler.io 28 | 29 | Some of the advantages that make a central registry popular in other 30 | languages include: 31 | 32 | * **Discoverability**. A central registry provides an easy place to look 33 | for existing packages. Combined with tagging, this also makes it 34 | possible for a registry to provide ecosystem-wide information, such as a 35 | list of the most popular or most-depended-on packages. 36 | * **Speed**. A central registry makes it possible to easily fetch just 37 | the metadata for packages quickly and efficiently, and then to 38 | efficiently download just the published package, and not other bloat 39 | that happens to exist in the repository. This adds up to a significant 40 | improvement in the speed of dependency resolution and fetching. As 41 | dependency graphs scale up, downloading all of the git repositories bogs 42 | down fast. Also remember that not everybody has a high-speed, 43 | low-latency Internet connection. 44 | 45 | # Will Cargo work with C code (or other languages)? 46 | 47 | Yes! 48 | 49 | Cargo handles compiling Rust code, but we know that many Rust projects 50 | link against C code. We also know that there are decades of tooling 51 | built up around compiling languages other than Rust. 52 | 53 | Our solution: Cargo allows a package to [specify a script](build-script.html) 54 | (written in Rust) to run before invoking `rustc`. Rust is leveraged to 55 | implement platform-specific configuration and refactor out common build 56 | functionality among packages. 57 | 58 | # Can Cargo be used inside of `make` (or `ninja`, or ...) 59 | 60 | Indeed. While we intend Cargo to be useful as a standalone way to 61 | compile Rust projects at the top-level, we know that some people will 62 | want to invoke Cargo from other build tools. 63 | 64 | We have designed Cargo to work well in those contexts, paying attention 65 | to things like error codes and machine-readable output modes. We still 66 | have some work to do on those fronts, but using Cargo in the context of 67 | conventional scripts is something we designed for from the beginning and 68 | will continue to prioritize. 69 | 70 | # Does Cargo handle multi-platform projects or cross-compilation? 71 | 72 | Rust itself provides facilities for configuring sections of code based 73 | on the platform. Cargo also supports [platform-specific 74 | dependencies][target-deps], and we plan to support more per-platform 75 | configuration in `Cargo.toml` in the future. 76 | 77 | [target-deps]: manifest.html#the-dependencies-section 78 | 79 | In the longer-term, we’re looking at ways to conveniently cross-compile 80 | projects using Cargo. 81 | 82 | # Does Cargo support environments, like `production` or `test`? 83 | 84 | We support environments through the use of [profiles][profile] to support: 85 | 86 | [profile]: manifest.html#the-profile-sections 87 | 88 | * environment-specific flags (like `-g --opt-level=0` for development 89 | and `--opt-level=3` for production). 90 | * environment-specific dependencies (like `hamcrest` for test assertions). 91 | * environment-specific `#[cfg]` 92 | * a `cargo test` command 93 | 94 | # Does Cargo work on Windows? 95 | 96 | Yes! 97 | 98 | All commits to Cargo are required to pass the local test suite on Windows. 99 | If, however, you find a Windows issue, we consider it a bug, so [please file an 100 | issue][3]. 101 | 102 | [3]: https://github.com/rust-lang/cargo/issues 103 | 104 | # Why do binaries have `Cargo.lock` in version control, but not libraries? 105 | 106 | The purpose of a `Cargo.lock` is to describe the state of the world at the time 107 | of a successful build. It is then used to provide deterministic builds across 108 | whatever machine is building the project by ensuring that the exact same 109 | dependencies are being compiled. 110 | 111 | This property is most desirable from applications and projects which are at the 112 | very end of the dependency chain (binaries). As a result, it is recommended that 113 | all binaries check in their `Cargo.lock`. 114 | 115 | For libraries the situation is somewhat different. A library is not only used by 116 | the library developers, but also any downstream consumers of the library. Users 117 | dependent on the library will not inspect the library’s `Cargo.lock` (even if it 118 | exists). This is precisely because a library should **not** be deterministically 119 | recompiled for all users of the library. 120 | 121 | If a library ends up being used transitively by several dependencies, it’s 122 | likely that just a single copy of the library is desired (based on semver 123 | compatibility). If all libraries were to check in their `Cargo.lock`, then 124 | multiple copies of the library would be used, and perhaps even a version 125 | conflict. 126 | 127 | In other words, libraries specify semver requirements for their dependencies but 128 | cannot see the full picture. Only end products like binaries have a full 129 | picture to decide what versions of dependencies should be used. 130 | 131 | # Can libraries use `*` as a version for their dependencies? 132 | 133 | **As of January 22nd, 2016, [crates.io] rejects all packages (not just libraries) 134 | with wildcard dependency constraints.** 135 | 136 | While libraries _can_, strictly speaking, they should not. A version requirement 137 | of `*` says “This will work with every version ever,” which is never going 138 | to be true. Libraries should always specify the range that they do work with, 139 | even if it’s something as general as “every 1.x.y version.” 140 | 141 | # Why `Cargo.toml`? 142 | 143 | As one of the most frequent interactions with Cargo, the question of why the 144 | configuration file is named `Cargo.toml` arises from time to time. The leading 145 | capital-`C` was chosen to ensure that the manifest was grouped with other 146 | similar configuration files in directory listings. Sorting files often puts 147 | capital letters before lowercase letters, ensuring files like `Makefile` and 148 | `Cargo.toml` are placed together. The trailing `.toml` was chosen to emphasize 149 | the fact that the file is in the [TOML configuration 150 | format](https://github.com/toml-lang/toml). 151 | 152 | Cargo does not allow other names such as `cargo.toml` or `Cargofile` to 153 | emphasize the ease of how a Cargo repository can be identified. An option of 154 | many possible names has historically led to confusion where one case was handled 155 | but others were accidentally forgotten. 156 | 157 | [crates.io]: https://crates.io/ 158 | 159 | # How can Cargo work offline? 160 | 161 | Cargo is often used in situations with limited or no network access such as 162 | airplanes, CI environments, or embedded in large production deployments. Users 163 | are often surprised when Cargo attempts to fetch resources from the network, and 164 | hence the request for Cargo to work offline comes up frequently. 165 | 166 | Cargo, at its heart, will not attempt to access the network unless told to do 167 | so. That is, if no crates comes from crates.io, a git repository, or some other 168 | network location, Cargo will never attempt to make a network connection. As a 169 | result, if Cargo attempts to touch the network, then it's because it needs to 170 | fetch a required resource. 171 | 172 | Cargo is also quite aggressive about caching information to minimize the amount 173 | of network activity. It will guarantee, for example, that if `cargo build` (or 174 | an equivalent) is run to completion then the next `cargo build` is guaranteed to 175 | not touch the network so long as `Cargo.toml` has not been modified in the 176 | meantime. This avoidance of the network boils down to a `Cargo.lock` existing 177 | and a populated cache of the crates reflected in the lock file. If either of 178 | these components are missing, then they're required for the build to succeed and 179 | must be fetched remotely. 180 | 181 | As of Rust 1.11.0 Cargo understands a new flag, `--frozen`, which is an 182 | assertion that it shouldn't touch the network. When passed, Cargo will 183 | immediately return an error if it would otherwise attempt a network request. 184 | The error should include contextual information about why the network request is 185 | being made in the first place to help debug as well. Note that this flag *does 186 | not change the behavior of Cargo*, it simply asserts that Cargo shouldn't touch 187 | the network as a previous command has been run to ensure that network activity 188 | shouldn't be necessary. 189 | 190 | For more information about vendoring, see documentation on [source 191 | replacement][replace]. 192 | 193 | [replace]: source-replacement.html 194 | -------------------------------------------------------------------------------- /src/doc/crates-io.md: -------------------------------------------------------------------------------- 1 | % Publishing on crates.io 2 | 3 | Once you've got a library that you'd like to share with the world, it's time to 4 | publish it on [crates.io]! Publishing a crate is when a specific 5 | version is uploaded to be hosted on [crates.io]. 6 | 7 | Take care when publishing a crate, because a publish is **permanent**. The 8 | version can never be overwritten, and the code cannot be deleted. There is no 9 | limit to the number of versions which can be published, however. 10 | 11 | # Before your first publish 12 | 13 | First thing’s first, you’ll need an account on [crates.io] to acquire 14 | an API token. To do so, [visit the home page][crates.io] and log in via a GitHub 15 | account (required for now). After this, visit your [Account 16 | Settings](https://crates.io/me) page and run the `cargo login` command 17 | specified. 18 | 19 | ```notrust 20 | $ cargo login abcdefghijklmnopqrstuvwxyz012345 21 | ``` 22 | 23 | This command will inform Cargo of your API token and store it locally in your 24 | `~/.cargo/config`. Note that this token is a **secret** and should not be shared 25 | with anyone else. If it leaks for any reason, you should regenerate it 26 | immediately. 27 | 28 | # Before publishing a new crate 29 | 30 | Keep in mind that crate names on [crates.io] are allocated on a first-come-first- 31 | serve basis. Once a crate name is taken, it cannot be used for another crate. 32 | 33 | ## Packaging a crate 34 | 35 | The next step is to package up your crate into a format that can be uploaded to 36 | [crates.io]. For this we’ll use the `cargo package` subcommand. This will take 37 | our entire crate and package it all up into a `*.crate` file in the 38 | `target/package` directory. 39 | 40 | ```notrust 41 | $ cargo package 42 | ``` 43 | 44 | As an added bonus, the `*.crate` will be verified independently of the current 45 | source tree. After the `*.crate` is created, it’s unpacked into 46 | `target/package` and then built from scratch to ensure that all necessary files 47 | are there for the build to succeed. This behavior can be disabled with the 48 | `--no-verify` flag. 49 | 50 | Now’s a good time to take a look at the `*.crate` file to make sure you didn’t 51 | accidentally package up that 2GB video asset. There is currently a 10MB upload 52 | size limit on `*.crate` files. Cargo will automatically ignore files ignored by 53 | your version control system when packaging, but if you want to specify an extra 54 | set of files to ignore you can use the `exclude` key in the manifest: 55 | 56 | ```toml 57 | [package] 58 | # ... 59 | exclude = [ 60 | "public/assets/*", 61 | "videos/*", 62 | ] 63 | ``` 64 | 65 | The syntax of each element in this array is what 66 | [rust-lang/glob](https://github.com/rust-lang/glob) accepts. If you’d rather 67 | roll with a whitelist instead of a blacklist, Cargo also supports an `include` 68 | key: 69 | 70 | ```toml 71 | [package] 72 | # ... 73 | include = [ 74 | "**/*.rs", 75 | "Cargo.toml", 76 | ] 77 | ``` 78 | 79 | ## Uploading the crate 80 | 81 | Now that we’ve got a `*.crate` file ready to go, it can be uploaded to 82 | [crates.io] with the `cargo publish` command. And that’s it, you’ve now published 83 | your first crate! 84 | 85 | ```notrust 86 | $ cargo publish 87 | ``` 88 | 89 | If you’d like to skip the `cargo package` step, the `cargo publish` subcommand 90 | will automatically package up the local crate if a copy isn’t found already. 91 | 92 | Be sure to check out the [metadata you can 93 | specify](manifest.html#package-metadata) to ensure your crate can be discovered 94 | more easily! 95 | 96 | # Publishing a new version of an existing crate 97 | 98 | In order to release a new version, change the `version` value specified in your 99 | `Cargo.toml` manifest. Keep in mind [the semver 100 | rules](manifest.html#the-version-field). Then optionally run `cargo package` if 101 | you want to inspect the `*.crate` file for the new version before publishing, 102 | and run `cargo publish` to upload the new version. 103 | 104 | # Managing a crates.io-based crate 105 | 106 | Management of crates is primarily done through the command line `cargo` tool 107 | rather than the [crates.io] web interface. For this, there are a few subcommands 108 | to manage a crate. 109 | 110 | ## `cargo yank` 111 | 112 | Occasions may arise where you publish a version of a crate that actually ends up 113 | being broken for one reason or another (syntax error, forgot to include a file, 114 | etc.). For situations such as this, Cargo supports a “yank” of a version of a 115 | crate. 116 | 117 | ```notrust 118 | $ cargo yank --vers 1.0.1 119 | $ cargo yank --vers 1.0.1 --undo 120 | ``` 121 | 122 | A yank **does not** delete any code. This feature is not intended for deleting 123 | accidentally uploaded secrets, for example. If that happens, you must reset 124 | those secrets immediately. 125 | 126 | The semantics of a yanked version are that no new dependencies can be created 127 | against that version, but all existing dependencies continue to work. One of the 128 | major goals of [crates.io] is to act as a permanent archive of crates that does 129 | not change over time, and allowing deletion of a version would go against this 130 | goal. Essentially a yank means that all projects with a `Cargo.lock` will not 131 | break, while any future `Cargo.lock` files generated will not list the yanked 132 | version. 133 | 134 | ## `cargo owner` 135 | 136 | A crate is often developed by more than one person, or the primary maintainer 137 | may change over time! The owner of a crate is the only person allowed to publish 138 | new versions of the crate, but an owner may designate additional owners. 139 | 140 | ```notrust 141 | $ cargo owner --add my-buddy 142 | $ cargo owner --remove my-buddy 143 | $ cargo owner --add github:rust-lang:owners 144 | $ cargo owner --remove github:rust-lang:owners 145 | ``` 146 | 147 | The owner IDs given to these commands must be GitHub user names or GitHub teams. 148 | 149 | If a user name is given to `--add`, that user becomes a “named” owner, with 150 | full rights to the crate. In addition to being able to publish or yank versions 151 | of the crate, they have the ability to add or remove owners, *including* the 152 | owner that made *them* an owner. Needless to say, you shouldn’t make people you 153 | don’t fully trust into a named owner. In order to become a named owner, a user 154 | must have logged into [crates.io] previously. 155 | 156 | If a team name is given to `--add`, that team becomes a “team” owner, with 157 | restricted right to the crate. While they have permission to publish or yank 158 | versions of the crate, they *do not* have the ability to add or remove owners. 159 | In addition to being more convenient for managing groups of owners, teams are 160 | just a bit more secure against owners becoming malicious. 161 | 162 | The syntax for teams is currently `github:org:team` (see examples above). 163 | In order to add a team as an owner one must be a member of that team. No 164 | such restriction applies to removing a team as an owner. 165 | 166 | ## GitHub permissions 167 | 168 | Team membership is not something GitHub provides simple public access to, and it 169 | is likely for you to encounter the following message when working with them: 170 | 171 | > It looks like you don’t have permission to query a necessary property from 172 | GitHub to complete this request. You may need to re-authenticate on [crates.io] 173 | to grant permission to read GitHub org memberships. Just go to 174 | https://crates.io/login 175 | 176 | This is basically a catch-all for “you tried to query a team, and one of the 177 | five levels of membership access control denied this”. That is not an 178 | exaggeration. GitHub’s support for team access control is Enterprise Grade. 179 | 180 | The most likely cause of this is simply that you last logged in before this 181 | feature was added. We originally requested *no* permissions from GitHub when 182 | authenticating users, because we didn’t actually ever use the user’s token for 183 | anything other than logging them in. However to query team membership on your 184 | behalf, we now require 185 | [the `read:org` scope](https://developer.github.com/v3/oauth/#scopes). 186 | 187 | You are free to deny us this scope, and everything that worked before teams 188 | were introduced will keep working. However you will never be able to add a team 189 | as an owner, or publish a crate as a team owner. If you ever attempt to do this, 190 | you will get the error above. You may also see this error if you ever try to 191 | publish a crate that you don’t own at all, but otherwise happens to have a team. 192 | 193 | If you ever change your mind, or just aren’t sure if [crates.io] has sufficient 194 | permission, you can always go to https://crates.io/login, which will prompt you 195 | for permission if [crates.io] doesn’t have all the scopes it would like to. 196 | 197 | An additional barrier to querying GitHub is that the organization may be 198 | actively denying third party access. To check this, you can go to: 199 | 200 | https://github.com/organizations/:org/settings/oauth_application_policy 201 | 202 | where `:org` is the name of the organization (e.g. rust-lang). You may see 203 | something like: 204 | 205 | ![Organization Access Control](images/org-level-acl.png) 206 | 207 | Where you may choose to explicitly remove [crates.io] from your organization’s 208 | blacklist, or simply press the “Remove Restrictions” button to allow all third 209 | party applications to access this data. 210 | 211 | Alternatively, when [crates.io] requested the `read:org` scope, you could have 212 | explicitly whitelisted [crates.io] querying the org in question by pressing 213 | the “Grant Access” button next to its name: 214 | 215 | ![Authentication Access Control](images/auth-level-acl.png) 216 | 217 | [crates.io]: https://crates.io/ 218 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /src/doc/specifying-dependencies.md: -------------------------------------------------------------------------------- 1 | % Способы указания зависимостей 2 | 3 | Ваши контейнеры (crates) могут зависеть от других библиотек с [crates.io], `git` 4 | репозиториев, или поддиректорий в локальной файловой системе. Вы также можете 5 | временно перезаписать расположение зависимости, например, чтобы проверить 6 | исправление в пакете, с которым вы работаете локально. Вы можете указать 7 | зависимости для различных платформ, и зависимости, используемые только при 8 | разработке. Давайте посмотрим, как этим управлять. 9 | 10 | # Указание зависимостей с crates.io 11 | 12 | Cargo по-умолчанию настроен на поиск зависимостей по [crates.io]. В этом случае 13 | требуется только название и строка, содержащая номер версии. 14 | В [руководстве по Cargo](guide.html), мы указали зависимость от 15 | контейнера `time`: 16 | 17 | ```toml 18 | [dependencies] 19 | time = "0.1.12" 20 | ``` 21 | 22 | Строка `"0.1.12"` является строкой указания семантической версии, также 23 | известной как [SemVer]. Поскольку эта строка не содержит каких-либо операторов, 24 | то эта строка интерпретируется также, как если бы мы указали строку `"^0.1.12"`, 25 | которую называют мажорным ограничением. 26 | Подробнее о семантическом версионировании можно прочитать на сайте 27 | [semver.org](http://semver.org/lang/ru/). 28 | 29 | [SemVer]: https://github.com/steveklabnik/semver#requirements 30 | 31 | ## Мажорные ограничения 32 | 33 | **Мажорное ограничение** разрешает совместимые обновления указанной версии. 34 | Обновление допускается, если в номере новой версии не изменяется самая левая 35 | ненулевая цифра в группе *мажорная.минорная.патч*. 36 | В этом случае, если мы запустим `cargo update -p time`, cargo обновит пакет 37 | до `0.1.13`, если он доступен, но не обновит до `0.2.0`. Иначе, если указать 38 | строку версии как `^1.0`, cargo обновит до `1.1`, но не `2.0`. `0.0.x` 39 | считается несовместимым с любой другой версией. 40 | 41 | Вот несколько примеров мажорных ограничений и версий, которые оно разрешает: 42 | 43 | ```notrust 44 | ^1.2.3 := >=1.2.3 <2.0.0 45 | ^1.2 := >=1.2.0 <2.0.0 46 | ^1 := >=1.0.0 <2.0.0 47 | ^0.2.3 := >=0.2.3 <0.3.0 48 | ^0.0.3 := >=0.0.3 <0.0.4 49 | ^0.0 := >=0.0.0 <0.1.0 50 | ^0 := >=0.0.0 <1.0.0 51 | ``` 52 | 53 | Хотя семантическое версионирование подразумевает, что нет совместимости до 54 | 1.0.0, многие программисты относятся к релизам `0.x.y` также, как к `1.x.y` 55 | релизам: то есть `y` увеличивается для обратно совместимых баг-фиксов, а `x` 56 | увеличивается при добавлении новых возможностей. Таким образом, Cargo считает 57 | `0.x.y` и `0.x.z` версии совместимыми, если`z > y`. 58 | 59 | ## Минорные ограничения 60 | 61 | **Минорное ограничение** указывает минимальную версию с некоторой возможностью 62 | обновления. 63 | Если вы указываете мажорную версию, минорную и номер патча или только мажорную 64 | и минорную версию, то допускаются изменения только на уровне версии патча. 65 | Если вы указываете только мажорный номер версии, то разрешается изменение на 66 | уровне минорной версии и версии патча. 67 | 68 | `~1.2.3` является примером минорного ограничения. 69 | 70 | ```notrust 71 | ~1.2.3 := >=1.2.3 <1.3.0 72 | ~1.2 := >=1.2.0 <1.3.0 73 | ~1 := >=1.0.0 <2.0.0 74 | ``` 75 | 76 | ## Позиционные ограничения 77 | 78 | **Позиционное ограничение** разрешает любую версию в соответствии с шаблоном. 79 | 80 | `*`, `1.*` и `1.2.*` являются примерами позиционного ограничения. 81 | 82 | ```notrust 83 | * := >=0.0.0 84 | 1.* := >=1.0.0 <2.0.0 85 | 1.2.* := >=1.2.0 <1.3.0 86 | ``` 87 | 88 | ## Ограничения неравенством 89 | 90 | **Ограничение неравенством** позволяет вручную указывать допустимый диапазон 91 | версий или конкретную версию, которая требуется. 92 | 93 | Ниже несколько примеров ограничения неравенством: 94 | 95 | ```notrust 96 | >= 1.2.0 97 | > 1 98 | < 2 99 | = 1.2.3 100 | ``` 101 | 102 | ## Несколько ограничений 103 | 104 | Несколько ограничений версии могут быть разделены через запятую, 105 | например, `>= 1.2, < 1.5`. 106 | 107 | # Указание зависимостей из `git` репозиториев 108 | 109 | Для указания зависимости от библиотеки, расположенной в `git` репозитории, 110 | вы должны, как минимум, указать расположение репозитория с помощью ключа `git`: 111 | 112 | ```toml 113 | [dependencies] 114 | rand = { git = "https://github.com/rust-lang-nursery/rand" } 115 | ``` 116 | 117 | Cargo загрузит `git` репозиторий, а затем 118 | будет искать `Cargo.toml` для запрошенного контейнера 119 | в любом месте `git` репозитория (не обязательно в корне). 120 | 121 | Поскольку мы не указали никакой другой информации, Cargo предполагает, 122 | что мы намерены использовать последний коммит в ветке `master` 123 | для сборки нашего проекта. 124 | Вы можете комбинировать ключ `git` с ключами `rev`, `tag` или `branch`, 125 | чтобы указать что-то ещё. Вот пример указания того, что вы хотите 126 | использовать последний коммит из ветки `next`: 127 | 128 | ```toml 129 | [dependencies] 130 | rand = { git = "https://github.com/rust-lang-nursery/rand", branch = "next" } 131 | ``` 132 | 133 | # Указание локальных зависимостей 134 | 135 | Со временем наш проект `hello_world` из [руководства](guide.html) значительно 136 | вырос! Понятно, что мы, вероятно, хотим разделить контейнер на несколько других. 137 | Для этого Cargo поддерживает **пути до зависимостей**, которые обычно являются 138 | под-контейнерами, которые живут в одном репозитории. Давайте начнем с создания 139 | нового контейнера внутри нашего проекта `hello_world`: 140 | 141 | ```shell 142 | # в папке hello_world/ 143 | $ cargo new hello_utils 144 | ``` 145 | 146 | Это создаст новую папку `hello_utils`, внутри которой `Cargo.toml` и папка `src` 147 | будут готовы для настройки. Чтобы сообщить Cargo об этом, откройте 148 | `hello_world/Cargo.toml` и добавьте `hello_utils` в ваши зависимости: 149 | 150 | ```toml 151 | [dependencies] 152 | hello_utils = { path = "hello_utils" } 153 | ``` 154 | 155 | Это укажет Cargo, что наш проект зависит от контейнера с именем `hello_utils`, 156 | который находится в папке `hello_utils` (относительно `Cargo.toml`, 157 | в котором это указано). 158 | 159 | Вот и всё! Следующий `cargo build` автоматически соберёт `hello_utils` и все 160 | свои зависимости, и другие контейнеры могут использовать под-контейнеры тем же 161 | образом. Однако, контейнеры, которые используют зависимости, указанные по 162 | локальному пути, не допускаются на [crates.io]. 163 | Если мы хотим опубликовать наш контейнер `hello_world`, мы должны сперва 164 | опубликовать `hello_utils` на [crates.io](https://crates.io) 165 | (или указать адрес `git` репозитория) и указать версию в строке зависимости: 166 | 167 | ```toml 168 | [dependencies] 169 | hello_utils = { path = "hello_utils", version = "0.1.0" } 170 | ``` 171 | 172 | # Переопределение зависимостей 173 | 174 | Иногда вам может понадобиться переопределить одну из Cargo зависимостей. 175 | Допустим, вы работаете над проектом, используя контейнер 176 | [`uuid`](https://crates.io/crates/uuid), который зависит от 177 | [`rand`](https://crates.io/crates/rand). Вы обнаружили ошибку в `rand`, и она 178 | уже исправлена, по пока не опубликована. Вы хотите проверить это исправление, 179 | поэтому давайте сначала посмотрим, как будет выглядеть ваш `Cargo.toml`: 180 | 181 | ```toml 182 | [package] 183 | name = "my-awesome-crate" 184 | version = "0.2.0" 185 | authors = ["The Rust Project Developers"] 186 | 187 | [dependencies] 188 | uuid = "0.2" 189 | ``` 190 | 191 | Чтобы переопределить зависимость `rand` контейнера `uuid`, мы будем 192 | использовать [секцию `[replace]`] [replace-section] в `Cargo.toml`, 193 | добавив это в конце: 194 | 195 | [replace-section]: manifest.html#the-replace-section 196 | 197 | ```toml 198 | [replace] 199 | "rand:0.3.14" = { git = 'https://github.com/rust-lang-nursery/rand' } 200 | ``` 201 | 202 | Это означает, что `rand` версии 0.3.14, которую мы сейчас используем, будет 203 | заменена веткой master репозитория `rand` на GitHub. В следующий раз, когда вы 204 | выполните `cargo build`, Cargo возьмёт на себя проверку этого репозитория и 205 | сборку `uuid` с обновлённой версией. 206 | 207 | Обратите внимание, что в секции `[replace]` переопределяемый контейнер должен 208 | иметь не только такое же имя, но и ту же версию, что и оригинальный. Это 209 | означает, что если в `master` ветке версия `rand` была обновлена до, скажем, 210 | 0.4.3, то вам необходимо выполнить несколько дополнительных шагов для 211 | тестирования контейнера: 212 | 213 | 1. Создайте форк оригинального репозитория 214 | 2. Создайте ветку, начинающуюся с релиза версии 0.3.14 (вероятно, отмечена 215 | тегом 0.3.14) 216 | 3. Найдите исправление и отправьте его в вашу ветку 217 | 4. В секции `[replace]` укажите ваш git репозиторий и ветку 218 | 219 | Этот метод также может быть полезен при тестировании новых функций зависимости. 220 | Используя этот метод вы можете использовать ветку, в которой вы будете 221 | добавлять фичи, а затем, когда она будет готова, вы можете отправить 222 | pull-request в основной репозиторий. Пока вы будете ожидать одобрения 223 | pull-request, вы можете работать локально с использованием `[replace]`, а 224 | затем, когда pull-request будет принят и опубликован, вы можете удалить секцию 225 | `[remove]` и использовать недавно опубликованную версию. 226 | 227 | Примечание: в файле `Cargo.lock` будут перечислены две версии переопределённого 228 | контейнера: один для оригинального контейнера, а другой для версии, указанной в 229 | `[replace]`. С помощью `cargo build -v` можно проверить, что только одна версия 230 | используется при сборке. 231 | 232 | ### Переопределение локальными зависимостями 233 | 234 | Иногда вы только временно работаете над контейнером, и вы не хотите изменять 235 | `Cargo.toml` с помощью секции `[replace]`, описанной выше. Для этого случая 236 | Cargo предлагает ограниченную версию переопределений, называемую **путевыми 237 | переопределениями**. 238 | 239 | Как и раньше, предположим, вы работаете над проектом, использующем 240 | [`uuid`](https://crates.io/crates/uuid), который зависит от 241 | [`rand`](https://crates.io/crates/rand). На этот раз вы тот, кто нашёл ошибку в 242 | контейнере `rand` и вы хотите написать патч и проверить его, используя вашу 243 | версию `rand` в контейнере `uuid`. Вот, как выглядит `Cargo.toml` 244 | в контейнере `uuid`: 245 | 246 | ```toml 247 | [package] 248 | name = "uuid" 249 | version = "0.2.2" 250 | authors = ["The Rust Project Developers"] 251 | 252 | [dependencies] 253 | rand = { version = "0.3", optional = true } 254 | ``` 255 | 256 | Вы тестируете локальную копию `rand`, скажем, в каталоге `~/src`: 257 | 258 | ```shell 259 | $ cd ~/src 260 | $ git clone https://github.com/rust-lang-nursery/rand 261 | ``` 262 | 263 | Переопределение пути передаётся в Cargo через механизм конфигурации 264 | `.cargo/config`. Если Cargo обнаружит эту конфигурацию при сборке вашего пакета, 265 | он будет использовать переопределённый на вашей локальной машине путь вместо 266 | источника, указанного в `Cargo.toml`. 267 | 268 | Cargo ищет каталог с именем `.cargo` вверх по иерархии каталогов вашего проекта. 269 | Если ваш проект находится в `/path/to/project/uuid`, он будет искать `.cargo` в: 270 | 271 | * `/path/to/project/uuid` 272 | * `/path/to/project` 273 | * `/path/to` 274 | * `/path` 275 | * `/` 276 | 277 | Это позволяет вам указать свои переопределения в родительском каталоге, который 278 | включает в себя пакеты, которые вы обычно используете на локальном компьютере, 279 | и использовать их во всех проектах. 280 | 281 | Чтобы указать переопределения, создайте файл `.cargo/config` у некоторого предка 282 | каталога вашего проекта (обычно его размещают в корневой директории вашего кода 283 | или в вашем домашнем каталоге). 284 | 285 | Поместите это внутрь файла: 286 | 287 | ```toml 288 | paths = ["/path/to/project/rand"] 289 | ``` 290 | 291 | Этот массив должен заполняться каталогами, содержащими `Cargo.toml`. 292 | В этом случае мы добавляем переопределение `rand`, поэтому 293 | этот контейнер будет единственным, который будет переопределен. 294 | Указанный путь должен быть абсолютным. 295 | 296 | Однако переопределения пути более ограничены, чем секция `[replace]`, тем более, 297 | что они не могут изменить структуру графика зависимостей. 298 | В заменяемом контейнере набор зависимостей должен быть точно таким же, как и в 299 | оригинальном. Например, это означает, что переопределения пути не могут 300 | использоваться для проверки добавления зависимостей к контейнеру, 301 | в этой ситуации следует использовать секцию `[replace]`. 302 | 303 | Примечание: использование локальной конфигурации для переопределения 304 | путей работает только для контейнеров, которые были опубликованы на [crates.io]. 305 | Вы не можете использовать эту функцию для локальных неопубликованных контейнеров. 306 | 307 | Более подробную информацию о локальной конфигурации можно найти в 308 | [документации по конфигурации](config.html). 309 | 310 | # Платформо-специфичные зависимости 311 | 312 | 313 | Специфичные для платформы зависимости указываются в том же формате, как и 314 | обычные, но указаны под секцией `target`. Для определения этих секций 315 | используется обычный Rust-like синтаксис `#[cfg]`: 316 | 317 | ```toml 318 | [target.'cfg(windows)'.dependencies] 319 | winhttp = "0.4.0" 320 | 321 | [target.'cfg(unix)'.dependencies] 322 | openssl = "1.0.1" 323 | 324 | [target.'cfg(target_arch = "x86")'.dependencies] 325 | native = { path = "native/i686" } 326 | 327 | [target.'cfg(target_arch = "x86_64")'.dependencies] 328 | native = { path = "native/x86_64" } 329 | ``` 330 | 331 | Как и в случае с Rust, здесь поддерживаются операторы `not`,`any` и `all` для 332 | объединения различных пар имя/значение. Обратите внимание, что синтаксис `cfg` 333 | доступен только с Cargo 0.9.0 (Rust 1.8.0). 334 | 335 | В дополнение к синтаксису `#[cfg]` Cargo также поддерживает перечисление полной 336 | цели, к которой будут относиться зависимости: 337 | 338 | ```toml 339 | [target.x86_64-pc-windows-gnu.dependencies] 340 | winhttp = "0.4.0" 341 | 342 | [target.i686-unknown-linux-gnu.dependencies] 343 | openssl = "1.0.1" 344 | ``` 345 | 346 | Если вы используете кастомную спецификацию целевой платформы, укажите полный 347 | путь и имя файла: 348 | 349 | ```toml 350 | [target."x86_64/windows.json".dependencies] 351 | winhttp = "0.4.0" 352 | 353 | [target."i686/linux.json".dependencies] 354 | openssl = "1.0.1" 355 | native = { path = "native/i686" } 356 | 357 | [target."x86_64/linux.json".dependencies] 358 | openssl = "1.0.1" 359 | native = { path = "native/x86_64" } 360 | ``` 361 | 362 | # Зависимости для режима разработки 363 | 364 | Вы можете добавить секцию `[dev-dependencies]` в свой `Cargo.toml`, формат 365 | которого эквивалентен `[dependencies]`: 366 | 367 | ```toml 368 | [dev-dependencies] 369 | tempdir = "0.3" 370 | ``` 371 | 372 | Dev-зависимости используются не при компиляции сборки, а при компиляции тестов, 373 | примеров и бенчмарков. 374 | 375 | Эти зависимости *не* распространяются на другие пакеты, которые зависят от 376 | этого пакета. 377 | 378 | Вы также можете указать платформо-специфичные зависимости, используя 379 | `dev-dependencies` вместо `dependencies` в секции `target`. Например: 380 | 381 | ```toml 382 | [target.'cfg(unix)'.dev-dependencies] 383 | mio = "0.0.1" 384 | ``` 385 | 386 | [crates.io]: https://crates.io/ 387 | 388 | # Зависимости для сборки 389 | 390 | Вы можете объявить зависимость от других контейнеров на основе Cargo для их 391 | использования в сценариях сборки. Зависимости объявляются через раздел 392 | `build-dependencies` манифеста: 393 | 394 | ```toml 395 | [build-dependencies] 396 | gcc = "0.3" 397 | ``` 398 | 399 | Сценарий сборки **не** имеет доступа к зависимостям, указанным в секции 400 | `dependencies` или `dev-dependencies`. Зависимости сборки также не будут 401 | доступны для самого пакета, если они не указаны в разделе `dependencies`. 402 | Сам пакет и сценарий его сборки собираются отдельно, поэтому их зависимости 403 | могут не совпадать. Cargo.toml проще и чище, используя независимые зависимости 404 | для независимых целей. 405 | 406 | # Выбор возможностей (features) 407 | 408 | Если пакет зависит от некоторых возможностей, вы можете выбрать, 409 | какие из них использовать: 410 | 411 | ```toml 412 | [dependencies.awesome] 413 | version = "1.3.5" 414 | default-features = false # не включать стандартные возможности, и, опционально, 415 | # включить указанные возможности 416 | features = ["secure-password", "civet"] 417 | ``` 418 | 419 | Больше информации о возможностях можно найти в 420 | [документации по manifest](manifest.html#the-features-section). 421 | -------------------------------------------------------------------------------- /src/doc/guide.md: -------------------------------------------------------------------------------- 1 | % Руководство по Cargo 2 | 3 | Добро пожаловать в руководство по Cargo. Это руководство даст вам все необходимое, чтобы вы могли использовать Cargo для разработки проектов на языке программирования Rust. 4 | 5 | # Зачем нужен Cargo? 6 | 7 | Cargo - это инструмент, который позволяет указывать необходимые зависимости для проектов на языке Rust и убедиться, что вы получите воспроизводимые сборки. 8 | 9 | Для достижения этих целей, Cargo выполняет следующие действия: 10 | 11 | * Создает два файла с некоторой необходимой информацией о проекте. 12 | * Получает и собирает зависимости вашего проекта. 13 | * Запускает `rustc` или другие инструменты сборки со всеми необходимыми параметрами для правильной сборки вашего проекта. 14 | * Предоставляет все необходимые условия, чтобы работа с проектами на Rust стала проще. 15 | 16 | # Создание нового проекта 17 | 18 | Для создания нового проекта с помощью Cargo, воспользуйтесь командой `cargo new`: 19 | 20 | ```shell 21 | $ cargo new hello_world --bin 22 | ``` 23 | 24 | Мы передали аргумент `--bin`, потому что мы создаем исполняемую программу: если мы 25 | решим создать библиотеку, то этот аргумент необходимо убрать. Эта команда по умолчанию так же создает `git` репозиторий. Если вы этого не планировали, добавьте аргумент `--vcs none`. 26 | 27 | Давайте посмотрим, что Cargo сгенерировал для нас: 28 | 29 | ```shell 30 | $ cd hello_world 31 | $ tree . 32 | . 33 | ├── Cargo.toml 34 | └── src 35 | └── main.rs 36 | 37 | 1 directory, 2 files 38 | ``` 39 | 40 | Если бы мы выполнили команду `cargo new hello_world` без аргумента `--bin`, тогда 41 | мы бы получили файл `lib.rs`, вместо `main.rs`. В данный момент это все, что нам необходимо для начала. Первым делом, давайте посмотрим, что за файл `Cargo.toml`: 42 | 43 | ```toml 44 | [package] 45 | name = "hello_world" 46 | version = "0.1.0" 47 | authors = ["Your Name "] 48 | ``` 49 | 50 | Этот файл называется **манифестом** и содержит в себе все метаданные, которые необходимы Cargo, 51 | чтобы скомпилировать ваш проект. 52 | 53 | Вот, что мы найдем в файле `src/main.rs`: 54 | 55 | ``` 56 | fn main() { 57 | println!("Hello, world!"); 58 | } 59 | ``` 60 | 61 | Cargo сгенерировал “hello world” для нас. Давайте скомпилируем его: 62 | 63 |
$ cargo build
 64 |    Compiling hello_world v0.1.0 (file:///path/to/project/hello_world)
66 | 67 | А затем запустите его: 68 | 69 | ```shell 70 | $ ./target/debug/hello_world 71 | Hello, world! 72 | ``` 73 | 74 | Вы так же можете использовать `cargo run`, чтобы скомпилировать и запустить проект. Все за одну команду. (Вы не увидите фразу `Compiling`, если вы не вносили каких-либо изменений в исходный код, с момента последней компиляции): 75 | 76 |
$ cargo run
 77 |    Compiling hello_world v0.1.0 (file:///path/to/project/hello_world)
 79 |    Running `target/debug/hello_world`
 81 | Hello, world!
82 | 83 | Теперь вы увидите новый файл - `Cargo.lock`. Он содержит в себе информацию о зависимостях проекта. Т.к мы еще не добавили зависимости, для нас это, пока, не очень интересно. 84 | 85 | После того, как вы закончите работу над программой и будете готовы выпустить релизную версию, вы можете воспользоваться командой `cargo build --release`, чтобы скомпилировать ваш проект с включенной оптимизацией: 86 | 87 |
$ cargo build --release
 88 |    Compiling hello_world v0.1.0 (file:///path/to/project/hello_world)
90 | 91 | `cargo build --release` создаст исполняемый файл в директории 92 | `target/release`, вместо `target/debug`. 93 | 94 | Компиляция в режиме дебага является стандартной при разработке, т.к компилятору необходимо меньше времени на компиляцию проекта, из-за выключенной оптимизации кода, но исполняемый файл будет работать медленнее. Релизная версия требует больше времени для сборки проекта, но финальный результат будет работать быстрее. 95 | 96 | # Работа с существующим Cargo проектом 97 | 98 | Если вы скачиваете существующий проект, который использует Cargo, то начать работу с ним будет очень просто. 99 | 100 | Для начала, давайте загрузим какой-либо проект. В данном примере мы воспользуемся `rand`. Заберем копию его репозиторий с GitHub: 101 | 102 | ```sh 103 | $ git clone https://github.com/rust-lang-nursery/rand.git 104 | $ cd rand 105 | ``` 106 | 107 | Чтобы собрать `rand` воспользуемся командой `cargo build`: 108 | 109 |
$ cargo build
110 |    Compiling rand v0.1.0 (file:///path/to/project/rand)
111 | 112 | Cargo получит все зависимости для данного проекта, а затем соберет их вместе с проектом. 113 | 114 | # Добавление зависимостей из crates.io 115 | 116 | [crates.io] - это центральный репозиторий сообщества Rust, который служит в качестве хранилища, в котором можно найти и загрузить необходимые пакеты. `cargo` настроен так, что использует данный репозиторий по умолчанию. 117 | 118 | Чтобы добавить зависимую библиотеку, которая расположена на [crates.io], просто добавьте ее в ваш `Cargo.toml`. 119 | 120 | [crates.io]: https://crates.io/ 121 | 122 | ## Добавление зависимостей 123 | 124 | Если в вашем `Cargo.toml` еще нет раздела `[dependencies]`, добавьте его, 125 | затем перечислите контейнеры и их версии, которые вы хотите использовать. В этом примере мы добавим в зависимости контейнер `time`: 126 | 127 | ```toml 128 | [dependencies] 129 | time = "0.1.12" 130 | ``` 131 | 132 | Строка версии должна соответствовать [семантическому версионированию]. В документе [определение зависимостей](specifying-dependencies.html), вы найдете больше информации о всех возможностях, которые вам предоставлены. 133 | 134 | [семантическому версионированию]: https://github.com/steveklabnik/semver#requirements 135 | 136 | Если нам так же необходимо добавить новый контейнер, как зависимость, например, `regex`, нам не нужно добавлять блок `[dependencies]` каждый раз. Посмотрите, как выглядит наш 137 | `Cargo.toml` файл, в котором перечислены две зависимости - `time` и `regex` 138 | crates: 139 | 140 | ```toml 141 | [package] 142 | name = "hello_world" 143 | version = "0.1.0" 144 | authors = ["Your Name "] 145 | 146 | [dependencies] 147 | time = "0.1.12" 148 | regex = "0.1.41" 149 | ``` 150 | 151 | Запустите заново `cargo build`, и Cargo загрузит все новые зависимости, а так же их зависимости. Скомпилирует эти зависимости и обновит `Cargo.lock`: 152 | 153 |
$ cargo build
154 |     Updating registry `https://github.com/rust-lang/crates.io-index`
155 |  Downloading memchr v0.1.5
156 |  Downloading libc v0.1.10
157 |  Downloading regex-syntax v0.2.1
158 |  Downloading memchr v0.1.5
159 |  Downloading aho-corasick v0.3.0
160 |  Downloading regex v0.1.41
161 |    Compiling memchr v0.1.5
162 |    Compiling libc v0.1.10
163 |    Compiling regex-syntax v0.2.1
164 |    Compiling memchr v0.1.5
165 |    Compiling aho-corasick v0.3.0
166 |    Compiling regex v0.1.41
167 |    Compiling hello_world v0.1.0 (file:///path/to/project/hello_world)
168 | 169 | Наш `Cargo.lock` хранит в себе информацию о том, какую именно версию (с ревизией) мы используем. 170 | 171 | Теперь, если `regex` получит обновление, мы будем собирать проект с той же версией, которая указана в `Cargo.lock`, пока не воспользуемся командой `cargo update`. 172 | 173 | Теперь вы можете использовать библиотеку `regex`, используя `extern crate` в `main.rs`. 174 | 175 | ``` 176 | extern crate regex; 177 | 178 | use regex::Regex; 179 | 180 | fn main() { 181 | let re = Regex::new(r"^\d{4}-\d{2}-\d{2}$").unwrap(); 182 | println!("Did our date match? {}", re.is_match("2014-01-01")); 183 | } 184 | ``` 185 | 186 | Запустим этот код и увидим: 187 | 188 |
$ cargo run
189 |      Running `target/hello_world`
190 | Did our date match? true
191 | 192 | # Схема проекта 193 | 194 | Cargo размещает файлы определенным образом, чтобы можно было начать работать с новым Cargo проектом: 195 | 196 | ```shell 197 | . 198 | ├── Cargo.lock 199 | ├── Cargo.toml 200 | ├── benches 201 | │   └── large-input.rs 202 | ├── examples 203 | │   └── simple.rs 204 | ├── src 205 | │   ├── bin 206 | │   │   └── another_executable.rs 207 | │   ├── lib.rs 208 | │   └── main.rs 209 | └── tests 210 | └── some-integration-tests.rs 211 | ``` 212 | 213 | * `Cargo.toml` и `Cargo.lock` размещается в корневой директории вашего проекта. 214 | * Исходный код отправляется в директорию `src`. 215 | * Стандартный файл библиотеки расположен по адресу `src/lib.rs`. 216 | * Стандартный исполняемый файл находится по адресу `src/main.rs`. 217 | * Другие исполняемые файлы могут быть расположены в `src/bin/*.rs`. 218 | * Интеграционные тесты находятся в директории `tests` (юнит тесты в том файле, который они тестируют). 219 | * Исполняемые примеры распологаются в директории `examples`. 220 | * Бенчмарки хранятся в директории `benches`. 221 | 222 | Более детально это рассмотрено в [описание манифеста](manifest.html#the-project-layout). 223 | 224 | # Cargo.toml vs Cargo.lock 225 | 226 | `Cargo.toml` и `Cargo.lock` служат для двух разных целей. Перед тем, как мы начнем говорить об этом, рассмотрим небольшое изложение того, что мы изучили ранее: 227 | 228 | * `Cargo.toml` - необходим для описания зависимостей, которые добавляете вы. 229 | * `Cargo.lock` - хранит в себе точную информацию о зависимостях. Его создает Cargo и он не должен изменяться в ручную. 230 | 231 | Если вы создаете библиотеку, которую будут использовать другие проекты в качестве зависимости, добавьте `Cargo.lock` в ваш `.gitignore` файл. Если вы создаете исполняемые файлы, например, 232 | консольную программу, добавьте `Cargo.lock` в ваш `git` репозиторий. Если вам интересно, почему это так, прочитайте ["Почему приложения хранят в репозитории `Cargo.lock`, а библиотеки нет?" в 233 | FAQ](faq.html#why-do-binaries-have-cargolock-in-version-control-but-not-libraries). 234 | 235 | Давайте копнем немного глубже. 236 | 237 | `Cargo.toml` - это файл **манифеста**, в котором вы можете указать кучу разных метаданных о проекте. Например, мы можем указать, что мы зависим от другого проекта: 238 | 239 | ```toml 240 | [package] 241 | name = "hello_world" 242 | version = "0.1.0" 243 | authors = ["Your Name "] 244 | 245 | [dependencies] 246 | rand = { git = "https://github.com/rust-lang-nursery/rand.git" } 247 | ``` 248 | 249 | Этот проект имеет одну зависимость - библиотеку `rand`. В данном примере мы указатели в качестве зависимости конкретный git репозиторий, расположенный на GitHub. Т.к мы не указали какой-либо другой информации, Cargo предполагает, что мы будем использовать последний коммит с ветки `master`, чтобы собрать наш проект. 250 | 251 | Звучит круто? Ну, есть одна проблема: Если вы собрали ваш проект сегодня, а потом отправили копию мне, но, я соберу его только завтра, может случится что-то плохое. В репозитории `rand` могут появиться новые коммиты, и моя сборка будет содержать новые коммиты, а ваша - нет. 252 | Таким образом, мы получим разные сборки. Это не очень хорошо, так как мы хотим получать воспроизводимые сборки. 253 | 254 | Мы можем решить данную проблему, добавив `rev` в строку с зависимостью в файле `Cargo.toml`: 255 | 256 | ```toml 257 | [dependencies] 258 | rand = { git = "https://github.com/rust-lang-nursery/rand.git", rev = "9f35b8e" } 259 | ``` 260 | 261 | Теперь сборки будут одинаковые. Но есть небольшой недостаток: теперь нам нужно обновлять SHA-1 хеш коммита каждый раз, когда мы захотим обновить версию библиотеки. Это так утомительно и может привести к ошибкам! 262 | 263 | Вспомним про `Cargo.lock`. Благодаря нему нам не обязательно каждый раз в ручную указывать точную версию библиотеки, которую мы будем использовать. Cargo сделает это за нас. Все, что нам нужно - это манифест. Например, вот такой: 264 | 265 | ```toml 266 | [package] 267 | name = "hello_world" 268 | version = "0.1.0" 269 | authors = ["Your Name "] 270 | 271 | [dependencies] 272 | rand = { git = "https://github.com/rust-lang-nursery/rand.git" } 273 | ``` 274 | 275 | Cargo заберет последний коммит и запишет эту информацию в ваш `Cargo.lock` во время первой сборки. Этот файл будет выглядеть вот так: 276 | 277 | ```toml 278 | [root] 279 | name = "hello_world" 280 | version = "0.1.0" 281 | dependencies = [ 282 | "rand 0.1.0 (git+https://github.com/rust-lang-nursery/rand.git#9f35b8e439eeedd60b9414c58f389bdc6a3284f9)", 283 | ] 284 | 285 | [[package]] 286 | name = "rand" 287 | version = "0.1.0" 288 | source = "git+https://github.com/rust-lang-nursery/rand.git#9f35b8e439eeedd60b9414c58f389bdc6a3284f9" 289 | 290 | ``` 291 | 292 | Как вы можете видеть, в `Cargo.lock` довольно много информации. Включая точную версию библиотеки, которую мы будем использовать для сборки. Теперь, если мы передаем проект кому-то другому, то сборки проекта будут одинаковые и нам не нужно обновлять хеш коммита каждый раз. Нам даже не нужно его указывать в `Cargo.toml`, т.к Cargo сам заберет последний коммит. 293 | 294 | Когда мы будем готовы выпустить новую версию библиотеки, Cargo может заново просчитать зависимости и обновить их для нас: 295 | 296 | ```shell 297 | $ cargo update # updates all dependencies 298 | $ cargo update -p rand # updates just “rand” 299 | ``` 300 | 301 | Эта команда создаст новый `Cargo.lock` с новой информацией о версиях зависимостей. 302 | Обратите внимания, что аргумент для `cargo update` является 303 | [идентификатор пакета](pkgid-spec.html) и `rand` это сокращенная запись идентификатора. 304 | 305 | # Тесты 306 | 307 | Cargo запустит ваши тесты с помощью команды `cargo test`. Cargo запускает тесты из двух мест: из вашей `src` директории, а так же в директории `tests/`. 308 | Тесты в ваших `src` файла должны быть юнит тестами, а в папке `tests/` должны находиться интеграционные тесты. Таким образом, вам необходимо импортировать ваши контейнеры в интеграционные тесты. 309 | 310 | Давайте рассмотрим пример запуска `cargo test` в нашем проекте, в котором, на данный момент, нет тестов: 311 | 312 |
$ cargo test
313 |    Compiling rand v0.1.0 (https://github.com/rust-lang-nursery/rand.git#9f35b8e)
315 |    Compiling hello_world v0.1.0 (file:///path/to/project/hello_world)
317 |      Running target/test/hello_world-9c2b65bbb79eabce
319 | 
320 | running 0 tests
321 | 
322 | test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured
323 | 
324 | 325 | Если в вашем проекте есть тесты, вы должны увидеть вывод с правильным количеством тестов. 326 | 327 | Вы так же можете запустить определенные тесты, передавая фильтр: 328 | 329 |
$ cargo test foo
330 | 
331 | 332 | Эта команда запустит все тесты, у которых есть `foo` в название. 333 | 334 | `cargo test` может проводить дополнительные проверки. Например, скомпилирует все примеры, которые вы добавите и протестирует примеры в вашей документации. Более подробно можно прочитать в [разделе тестирования][testing] документации по языку программирования Rust. 335 | 336 | [testing]: https://doc.rust-lang.org/book/testing.html 337 | 338 | ## Travis CI 339 | 340 | Вы можете тестировать ваш проект с помощью Travis CI. Пример `.travis.yml` файла: 341 | 342 | ``` 343 | language: rust 344 | rust: 345 | - stable 346 | - beta 347 | - nightly 348 | matrix: 349 | allow_failures: 350 | - rust: nightly 351 | ``` 352 | 353 | В данном случае ваш код будет протестирован на всех трех доступных ветках Rust, но все ошибки сборки на nightly сборке не приведет к ошибке всего билда. Пожалуйста, ознакомьтесь с [документацией Travis CI для языка Rust](https://docs.travis-ci.com/user/languages/rust/) чтобы получить более подробную информацию. 354 | 355 | # Что дальше? 356 | 357 | Теперь, когда у вас есть представления, как использовать cargo, как создать свой первый контейнер, вам будет интересно почитать следующее: 358 | 359 | * [Как опубликовать ваш контейнер на crates.io](crates-io.html) 360 | * [Все возможные способы указания зависимостей](specifying-dependencies.html) 361 | * [Узнать подробнее о том, что можно включить в манифест `Cargo.toml`](manifest.html) 362 | -------------------------------------------------------------------------------- /src/doc/build-script.md: -------------------------------------------------------------------------------- 1 | % Поддержка сборочных скриптов 2 | 3 | Некоторые пакеты требуют компиляции стороннего кода написанного на других 4 | языках программирования, например СИ-библиотек. Другие пакеты предназначены 5 | для линковки с СИ-библиотеками. Они могут располагаться где-то в системе, или 6 | собираться из исходников. Третий вариант - это контейнеры, которые требуют 7 | дополнительной подготовки к сборке, например генерации кода перед сборкой. 8 | 9 | Cargo не ставит целью заменить инструменты которые хорошо оптимизированы 10 | для своих задач. Вместо этого, данные инструменты можно интегрировать в процесс 11 | сборки посредством опции `build` сборочного манифеста. 12 | 13 | ```toml 14 | [package] 15 | # ... 16 | build = "build.rs" 17 | ``` 18 | 19 | Rust файл, указанный в опции `build` (относительно корня пакета) будет 20 | скомпилирован и выполнен перед тем, как что-либо еще будет компилироваться 21 | в этом пакете. Это позволяет вашему rust-коду зависеть от других собранных 22 | или сгенерированных артефактов. Опция `build` не имеет значения по умолчанию, 23 | и должна быть указана явно, если это требуется. 24 | 25 | Причание. В rust 1.17 этот механизм был доработан следующим образом. Если 26 | в корневой директории контейнера есть файл build.rs, то считается, что опция 27 | build = "build.rs" указана. Отключить это вы можете задав build=false. 28 | 29 | Примеры случаев, для которых подходит опция `build`: 30 | 31 | * Сборка статической С-библиотеки 32 | * Поиск С-библиотеки на диске 33 | * Генерация rust-модуля из спецификации 34 | * Осуществление любой платформо-специфичной конфигурации, которая нужна для сборки 35 | 36 | Каждый из этих случаев детально описан ниже для пояснения того, как работает 37 | опция `build`. 38 | 39 | ## Входные данные для скрипта сборки 40 | 41 | Когда вы запускаете скрипт сборки, можно задать параметры, которые передаются 42 | путем задания переменных окружения [environment variables][env]. 43 | 44 | Вдобавок к переменным окружения, текущая директория скрипта сборки является 45 | директорией пакета скрипта сборки. 46 | 47 | [env]: environment-variables.html 48 | 49 | ## Выходной результат скрипта сборки 50 | 51 | Все строки, которые будут напечатаны в stdout, будут записаны в файл 52 | `target/debug/build//output` (точное расположение зависит от вашей конфигурации). 53 | Все строки, которые начинаются с `cargo:` интерпретируются напрямую cargo. 54 | Эти строки обязаны задаваться в форме `cargo:key=value`, как показано в примере: 55 | 56 | ```notrust 57 | cargo:rustc-link-lib=static=foo 58 | cargo:rustc-link-search=native=/path/to/foo 59 | cargo:rustc-cfg=foo 60 | cargo:root=/path/to/foo 61 | cargo:libdir=/path/to/foo/lib 62 | cargo:include=/path/to/foo/include 63 | ``` 64 | 65 | Ниже перечислены ключи, которые влияют на cargo: 66 | 67 | * `rustc-link-lib=[KIND=]NAME` передать указанное значение компилятору с опцией `-l`. 68 | Опциональный параметр KIND может принимать значения static, dylib(по умолчанию), 69 | framework. Для получения подробностей см. rustc --help 70 | * `rustc-link-search=[KIND=]PATH` передать указанное значение компилятору с опцией `-L`. 71 | Опциональный параметр KIND может быть одним из: dependency, crate, native, framework, 72 | all (по умолчанию). См. rustc --help для подробностей. 73 | * `rustc-flags=FLAGS` набор флагов, которые следует передать компилятору. 74 | Поддерживаются только `-l` и `-L` (Прим.переводчика -- тогда на кой оно нужно?). 75 | * `rustc-cfg=FEATURE` указывает передать компилятору c директивой `--cfg` 76 | указанную возможность. Это может быть полезным для определения на этапе компиляции 77 | различных возможностей. 78 | 79 | * `rerun-if-changed=PATH` путь к файлу или директории, которые при изменении 80 | должны вызвать перезапуск скрипта сборки(определяется по атрибуту last-modified). 81 | Обычно скрипт сборки перезапускается если любой файл внутри контейнера изменяется. 82 | Эта опция позволяет указать более узкий набор файлов. Если опция указывает 83 | на директорию, то cargo смотрит только на изменение времени модификации директории, 84 | и не смотрит на каждый файл. Для того, чтобы скрипт перезапускался при любом изменении 85 | во всей директории, напечатайте строку с директорией и другую строку для всего 86 | внутри нее, рекурсивно. 87 | 88 | * `warning=MESSAGE` это сообщение будет напечатано в основную консоль после того, как 89 | скрипт сборки закончит выполнение. Варнинги печатаются только на зависимостях, 90 | добавленных через path. Таким образом, варнинги на зависимостях, которые приползли с 91 | crates.io не эмитятся по умолчанию. 92 | 93 | Любой другой элемент является пользовательскими мета-данными, и передается зависимостям. 94 | Больше информации можно найти в секции [`links`][links]. 95 | 96 | [links]: #Опция-сборочного-манифеста-links 97 | 98 | ## Зависимости для процесса сборки 99 | 100 | Скрипт сборки может иметь зависимости на другие cargo-пакеты. 101 | Эти зависимости объявляются в секции `build-dependencies`. 102 | 103 | ```toml 104 | [build-dependencies] 105 | foo = { git = "https://github.com/your-packages/foo" } 106 | ``` 107 | 108 | Скрипту сборки НЕ ДОСТУПНЫ зависимости, перечисленные в секциях 109 | `dependencies` и `dev-dependencies`. Так же, все зависимости этапа сборки 110 | недоступны пакету, и если они нужны, то их следует указать явно. 111 | 112 | ## Опция сборочного манифеста `links` 113 | 114 | В добавление к опции `build`, Cargo поддерживает опцию `links` для указания 115 | нативных библиотек, которые следует прилинковать. 116 | 117 | ```toml 118 | [package] 119 | # ... 120 | links = "foo" 121 | build = "build.rs" 122 | ``` 123 | 124 | Это означает, что пакет линкуется с нативной библиотекой `libfoo`, и он 125 | имеет скрипт сборки, который находит/собирает эту библиотеку. Cargo 126 | требует, чтобы опция `build` была указана, если вы используете опцию `links`. 127 | 128 | Цель этого ключа - чтобы Cargo знал о наборе используемых нативных библиотек, 129 | и передавал эту метаинформацию между скриптами сборки пакетов. 130 | 131 | Вы не можете слинковать несколько пакетов с одной нативной либой. 132 | Однако есть [определенные случаи соглашений][star-sys] в которых это требование 133 | смягчено. 134 | 135 | [star-sys]: #-sys-пакеты 136 | 137 | Как мы выяснили выше, каждый билд-скрипт может генерировать набор метаданных 138 | из пар ключ-значение. Эти метаданные передаются билд-скриптам зависимых пакетов. 139 | 140 | Например, если `libbar` зависит от `libfoo`, тогда если `libfoo` генерирует 141 | `key=value` как часть своих метаданных, то билд-скрипт `libbar` будет иметь 142 | переменную окружения `DEP_FOO_KEY=value`. 143 | 144 | Также надо учитывать, что метаданные передаются непосредственно-зависящим пакетам, 145 | но не транзитивно на остальных. Мотивация такой передачи данных описана ниже 146 | в секции по линковке системных либ. 147 | 148 | ## Явное указание метаданных 149 | 150 | Ключ `links` включает поддержку явного указания метаданных для конкретной библиотеки. 151 | Цель этого действия может состоять в том, чтобы сократить время компиляции. 152 | Для явного указания расположите соответствующую секцию конфигурации в 153 | [любом доступном](config.html) для cargo месте . 154 | 155 | ```toml 156 | [target.x86_64-unknown-linux-gnu.foo] 157 | rustc-link-search = ["/path/to/foo"] 158 | rustc-link-lib = ["foo"] 159 | root = "/path/to/foo" 160 | key = "value" 161 | ``` 162 | 163 | Эта секция декларирует, что для цели `x86_64-unknown-linux-gnu` бибилотека с именем 164 | `foo` имеет явно указанные метаданные. Эти метаданные являются такими же, как 165 | можно было бы получить запустив сборочный скрипт, предоставляющий набор пар 166 | ключ-значение. 167 | 168 | В таком варианте, если пакет декларирует, что линкуется с foo, сборочный скрипт 169 | **не будет** скомпилирован и запущен, что сэкономит время. Вместо этого будут 170 | использованы указанные метаданные. 171 | 172 | 173 | # Конкретный пример: кодогенерация 174 | 175 | Некоторые пакеты cargo требуют, чтобы перед началом компиляции была произведена 176 | генерация кода. Изучим простой пример, который осуществляет генерацию кода 177 | в процессе сборки проекта. 178 | 179 | Структура директории пакета выглядит следующим образом: 180 | 181 | ```notrust 182 | . 183 | ├── Cargo.toml 184 | ├── build.rs 185 | └── src 186 | └── main.rs 187 | 188 | 1 directory, 3 files 189 | ``` 190 | 191 | Как мы можем видеть, имеется исходник скрипта `build.rs` и исходник бинарника 192 | `main.rs`. Содержимое Cargo.toml: 193 | 194 | ```toml 195 | # Cargo.toml 196 | 197 | [package] 198 | name = "hello-from-generated-code" 199 | version = "0.1.0" 200 | authors = ["you@example.com"] 201 | build = "build.rs" 202 | ``` 203 | 204 | Тут указано, что мы используем сборочный скрипт. 205 | Его содержимое следующее: 206 | 207 | ```rust,no_run 208 | // build.rs 209 | 210 | use std::env; 211 | use std::fs::File; 212 | use std::io::Write; 213 | use std::path::Path; 214 | 215 | fn main() { 216 | let out_dir = env::var("OUT_DIR").unwrap(); 217 | let dest_path = Path::new(&out_dir).join("hello.rs"); 218 | let mut f = File::create(&dest_path).unwrap(); 219 | 220 | f.write_all(b" 221 | pub fn message() -> &'static str { 222 | \"Hello, World!\" 223 | } 224 | ").unwrap(); 225 | } 226 | ``` 227 | 228 | Несколько комментариев к сборочному скрипту: 229 | 230 | * Скрипт использует переменную окружения `OUT_DIR`, которая содержит путь к 231 | директории для сгенерированного кода. В качестве директории для входных файлов 232 | используется текущая директория запущенного процесса. (в нашем случае 233 | чтения каких бы то ни было входных файлов не производится) 234 | 235 | * Этот скрипт тривиален. Он просто генерирует файл, содержащий маленький 236 | кусочек кода. В реальных задачах ваш скрипт сборки может делать что-то 237 | более полезное. Например, это может быть генерация rust-модуля из СИ-хэдэров, 238 | или каких-то других языков. 239 | 240 | 241 | Содержимое main.rs: 242 | 243 | ```rust,ignore 244 | // src/main.rs 245 | 246 | include!(concat!(env!("OUT_DIR"), "/hello.rs")); 247 | 248 | fn main() { 249 | println!("{}", message()); 250 | } 251 | ``` 252 | 253 | Как можно видеть, здесь не происходит никакой магии: мы подгружаем сгенерированный 254 | ранее код при помощи макроса `include!`. Макрос `concat!` осуществляет конкатенацию строк 255 | на этапе компиляции. Таким образом, получается путь к подгужаемому файлу. 256 | 257 | Используя показанную структуру, вы можете подгружать любое количество сгенерированных 258 | файлов. 259 | 260 | # Конкретный пример: сборка нативного кода 261 | 262 | Иногда нужно собрать нативный СИ или СИ++ код и использовать его как часть 263 | пакета. Это еще одна возможность, которую предоставляет сборочный скрипт. 264 | Для примера создадим rust-программу, которая вызывает СИ-код, который 265 | печатает “Hello, World!”. 266 | 267 | Содержимое директории проекта: 268 | 269 | ```notrust 270 | . 271 | ├── Cargo.toml 272 | ├── build.rs 273 | └── src 274 | ├── hello.c 275 | └── main.rs 276 | 277 | 1 directory, 4 files 278 | ``` 279 | 280 | Содержимое Cargo.toml: 281 | 282 | ```toml 283 | # Cargo.toml 284 | 285 | [package] 286 | name = "hello-world-from-c" 287 | version = "0.1.0" 288 | authors = ["you@example.com"] 289 | build = "build.rs" 290 | ``` 291 | 292 | Контент сборочного скрипта выглядит следующим образом: 293 | 294 | ```rust,no_run 295 | // build.rs 296 | 297 | use std::process::Command; 298 | use std::env; 299 | use std::path::Path; 300 | 301 | fn main() { 302 | let out_dir = env::var("OUT_DIR").unwrap(); 303 | 304 | // note that there are a number of downsides to this approach, the comments 305 | // below detail how to improve the portability of these commands. 306 | Command::new("gcc").args(&["src/hello.c", "-c", "-fPIC", "-o"]) 307 | .arg(&format!("{}/hello.o", out_dir)) 308 | .status().unwrap(); 309 | Command::new("ar").args(&["crus", "libhello.a", "hello.o"]) 310 | .current_dir(&Path::new(&out_dir)) 311 | .status().unwrap(); 312 | 313 | println!("cargo:rustc-link-search=native={}", out_dir); 314 | println!("cargo:rustc-link-lib=static=hello"); 315 | } 316 | ``` 317 | 318 | Этот сборочный скрипт при запуске компилирует наш СИ файл в объектный файл 319 | (при помощи `gcc`) и затем конвертирует этот объектник в статическую библиотеку 320 | (при помощи `ar`). На финальном шаге устанавливаются опции cargo, которые 321 | предписывают искать библиотеку для линковки в `out_dir` и линковаться статически 322 | с библиотекой `libhello.a` (при запуске rustc будет использован 323 | ключ `-l static=hello`). 324 | 325 | К данному скрипту имеется несколько замечаний: 326 | 327 | * Программа `gcc` присутствует не на всех платформах. Например, вряд ли на Windows 328 | будет gcc, и не все Unix-платформы могут иметь gcc. С командой `ar` аналогичная 329 | ситуация. 330 | * Эти команды не учитывают случай, если мы производим кросс-компиляцию. Если мы 331 | производим кросс-компиляцию для платформы типа Андроид, то вряд ли gcc соберет 332 | нам исполняемый файл с ARM-архитектурой. 333 | 334 | Однако, не стоит отчаиваться. Нам поможет секция `build-dependencies`. Экосистема 335 | Cargo имеет пакеты, которые полностью или частично абстрагируют нас от платформы 336 | и делают этот этап сборки более простым, портабельным и стандартизованным. 337 | Для примера, сборочный скрипт может быть написан следующим образом: 338 | 339 | ```rust,ignore 340 | // build.rs 341 | 342 | // Bring in a dependency on an externally maintained `gcc` package which manages 343 | // invoking the C compiler. 344 | extern crate gcc; 345 | 346 | fn main() { 347 | gcc::compile_library("libhello.a", &["src/hello.c"]); 348 | } 349 | ``` 350 | 351 | Это потребует зависимости на `gcc` контейнер. Добавить ее понадобиться в `Cargo.toml`: 352 | 353 | ```toml 354 | [build-dependencies] 355 | gcc = "0.3" 356 | ``` 357 | 358 | Контейнер [`gcc` crate](https://crates.io/crates/gcc) абстракция, позволяющая работать 359 | с различными вариантами, использующими С-код. 360 | 361 | * Выполняется правильный компилятор (MSVC на windows, `gcc` на MinGW, `cc` 362 | на Unix- платформах и т.д.). 363 | * Принимает переменную окружения TARGET для передачи правильных флажков компилятору. 364 | * Другие переменные окружения (`OPT_LEVEL`, `DEBUG`, и т.д.) обрабатываются автоматически. 365 | * Стандартный вывод и расположение директории `OUT_DIR` так же обрабатываются 366 | контейнером `gcc`. 367 | 368 | Here we can start to see some of the major benefits of farming as much 369 | functionality as possible out to common build dependencies rather than 370 | duplicating logic across all build scripts! 371 | 372 | Вернемся к исследованию содержимого директории `src`: 373 | 374 | ```c 375 | // src/hello.c 376 | 377 | #include 378 | 379 | void hello() { 380 | printf("Hello, World!\n"); 381 | } 382 | ``` 383 | 384 | ```rust,ignore 385 | // src/main.rs 386 | 387 | // аттрибут `#[link]` не является необходимым. Мы делегируем решение того, 388 | // с какой либой линковаться в скрипт сборки, вместо того чтобы захардкодить 389 | // его в исходном коде 390 | 391 | extern { fn hello(); } 392 | 393 | fn main() { 394 | unsafe { hello(); } 395 | } 396 | ``` 397 | 398 | And there we go! This should complete our example of building some C code from a 399 | Cargo package using the build script itself. This also shows why using a build 400 | dependency can be crucial in many situations and even much more concise! 401 | 402 | Еще мы тут увидели пример использования в скрипте сборки зависимостей, специально 403 | предназначенных для процесса сборки. 404 | 405 | # Конкретный пример: линковка с системными библиотеками 406 | 407 | В финальном примере будет показано как cargo линкуется с системными библиотеками, 408 | и как скрипт сборки может управлять этим процессом. 409 | 410 | 411 | Иногда для контейнеров rust требуются системные библиотеки. 412 | 413 | Quite frequently a Rust crate wants to link to a native library often provided 414 | on the system to bind its functionality or just use it as part of an 415 | implementation detail. This is quite a nuanced problem when it comes to 416 | performing this in a platform-agnostic fashion, and the purpose of a build 417 | script is again to farm out as much of this as possible to make this as easy as 418 | possible for consumers. 419 | 420 | В качестве примера рассмотрим одну из зависимостей самого cargo 421 | [Cargo’s own dependencies][git2-rs], [libgit2][libgit2]. Эта библиотека имеет 422 | некоторые ограничения: 423 | 424 | [git2-rs]: https://github.com/alexcrichton/git2-rs/tree/master/libgit2-sys 425 | [libgit2]: https://github.com/libgit2/libgit2 426 | 427 | * Имеет опциональную зависимость на OpenSSL на Unix-системах для реализации 428 | https-транспорта. 429 | * Имеет опциональную зависимость на libssh2 на всех платформах для реализации 430 | ssh-транспорта. 431 | * Зачастую не установлена по умолчанию на всех системах. 432 | * Собирается из исходников при помощи `cmake`. 433 | 434 | Чтобы понять, как это происходит, рассмотрим билд-манифест Cargo.toml. 435 | 436 | ```toml 437 | [package] 438 | name = "libgit2-sys" 439 | version = "0.1.0" 440 | authors = ["..."] 441 | links = "git2" 442 | build = "build.rs" 443 | 444 | [dependencies] 445 | libssh2-sys = { git = "https://github.com/alexcrichton/ssh2-rs" } 446 | 447 | [target.'cfg(unix)'.dependencies] 448 | openssl-sys = { git = "https://github.com/alexcrichton/openssl-sys" } 449 | 450 | # ... 451 | ``` 452 | 453 | Можно видеть, что в первой секции сборочного манифеста мы указываем сборочный скрипт 454 | опцией `build`. Также этот пример имеет опцию `links`, которая указывает нашему 455 | контейнеру (crate `libgit2-sys`) линковаться с нативной либой `git2`. 456 | 457 | Контейнер имеет безусловную зависимость на `libssh2` через указание 458 | `libssh2-sys` контейнера, и также платформо-специфичную зависимость на `openssl-sys` 459 | 460 | Тут имеется следующий интуитивно-непонятный момент: у нас указана Си-зависимость 461 | в сборочном манифесте cargo. Это является частью соглашений для cargo, которому 462 | посвящена следующая глава. 463 | 464 | ## `*-sys` пакеты 465 | 466 | Для облегчения линковки с системными библиотеками cargo имеет *соглашение* 467 | по именованию пакетов и функциональности. Любой пакет с именем `foo-sys` 468 | будет предоставлять две основные функциональные возможности: 469 | 470 | * контейнер будет линковаться с библиотекой `libfoo`. Обычно это вызывает 471 | проверку того, что либа `libfoo` установлена в системе. Если не установлена, 472 | то запускается процесс ее сборки. 473 | 474 | * контейнер будет предоставлять **декларации** для функций в `libfoo`, 475 | но **НЕ** предоставляет биндингов для абстракций более высокого уровня. 476 | 477 | Основное множество `*-sys` пакетов предоставляют основное множество зависимостей 478 | для линковки с нативными либами. Этим достигаются следующие выгоды для 479 | контейнеров, имеющих отношение к нативным либам: 480 | 481 | * Зависимости на `foo-sys` упрощают вышеописанное правило одного пакета 482 | на опцию `links`. 483 | * A common dependency allows centralizing logic on discovering `libfoo` itself 484 | (или сборку с исходников). 485 | * Эти зависимости легко переопределить. 486 | 487 | ## Сборка libgit2 488 | 489 | Теперь, когда мы получили зависимости libgit2, нам нужно написать логику 490 | сборочного скрипта. Мы не будем разбираться в узко-специфичных моментах кода 491 | и сконцентрируем свое внимание лишь на высокоуровневых деталях сборочного скрипта 492 | контейнера `libgit2-sys`. Это не является рекомендацией для всех пакетов, а лишь 493 | является одной из возможных специфичных стратегий. 494 | 495 | На первом шаге сборочный скрипт может попытаться найти место, в которое установлена 496 | libgit2. Это можно попытаться сделать при помощи предустановленного 497 | `pkg-config` (если он есть). We’ll also use a `build-dependencies` 498 | section to refactor out all the `pkg-config` related code (or someone’s already 499 | done that!). 500 | 501 | Если у `pkg-config` не получилось найти libgit2, или если `pkg-config` не 502 | установлен, следующим шагом будет сборка libgit2 из встроенных исходников 503 | (которые распространяются как часть самого `libgit2-sys`). 504 | Есть несколько нюансов, которые стоит упомянуть. 505 | 506 | * Система сборки libgit2, `cmake`, должна быть способна найти опциональную 507 | зависимость для libgit2’s -- libssh2. Нам не помешает убедиться, что она 508 | была собрана (это часть зависимостей Cargo), и мы должны обменяться с cargo 509 | этой информацией. 510 | Для осуществления этого используем формат метаданных для обмена между 511 | сборочными скриптами. В этом примере пакет libssh2 печатает `cargo:root=...` 512 | для того, чтобы сказать, куда libssh2 установлена. И мы передаем потом эту 513 | информацию в cmake через переменную окружения `CMAKE_PREFIX_PATH`. 514 | 515 | * Нам надо указать специфичные `CFLAGS` флаги для сборки СИ-кода (и сказать 516 | `cmake` об этом). Некоторые флаги могут потребовать указания ключа `-m64` для 517 | 64-битного кода, `-m32` для 32-битного кода, или `-fPIC` 518 | 519 | * На финальной стадии вызывается `cmake` и оказывается располагать весь выхлоп по 520 | `OUT_DIR`, и потом мы печатаем необходимые метаданные для указания rustc как линковаться 521 | с libgit2 522 | 523 | Большая часть функциональности этого сборочного скрипта легко модифицируется под 524 | основные зависимости. Поэтому сборочных скрипт запугивает даже в меньшей степени, чем это 525 | его описание. На самом деле, предполагается, что скрипты сборки достаточно кратки и 526 | и содержат логику, подобную той, что было описано выше для построения 527 | необходимых зависимостей. 528 | -------------------------------------------------------------------------------- /src/doc/manifest.md: -------------------------------------------------------------------------------- 1 | % The Manifest Format 2 | 3 | # The `[package]` section 4 | 5 | The first section in a `Cargo.toml` is `[package]`. 6 | 7 | ```toml 8 | [package] 9 | name = "hello_world" # the name of the package 10 | version = "0.1.0" # the current version, obeying semver 11 | authors = ["you@example.com"] 12 | ``` 13 | 14 | All three of these fields are mandatory. 15 | 16 | ## The `version` field 17 | 18 | Cargo bakes in the concept of [Semantic 19 | Versioning](http://semver.org/), so make sure you follow some basic rules: 20 | 21 | * Before you reach 1.0.0, anything goes. 22 | * After 1.0.0, only make breaking changes when you increment the major version. 23 | In Rust, breaking changes include adding fields to structs or variants to 24 | enums. Don’t break the build. 25 | * After 1.0.0, don’t add any new public API (no new `pub` anything) in tiny 26 | versions. Always increment the minor version if you add any new `pub` structs, 27 | traits, fields, types, functions, methods or anything else. 28 | * Use version numbers with three numeric parts such as 1.0.0 rather than 1.0. 29 | 30 | ## The `build` field (optional) 31 | 32 | This field specifies a file in the repository which is a [build script][1] for 33 | building native code. More information can be found in the build script 34 | [guide][1]. 35 | 36 | [1]: build-script.html 37 | 38 | ```toml 39 | [package] 40 | # ... 41 | build = "build.rs" 42 | ``` 43 | 44 | ## The `exclude` and `include` fields (optional) 45 | 46 | You can explicitly specify to Cargo that a set of [globs][globs] should be 47 | ignored or included for the purposes of packaging and rebuilding a package. The 48 | globs specified in the `exclude` field identify a set of files that are not 49 | included when a package is published as well as ignored for the purposes of 50 | detecting when to rebuild a package, and the globs in `include` specify files 51 | that are explicitly included. 52 | 53 | If a VCS is being used for a package, the `exclude` field will be seeded with 54 | the VCS’ ignore settings (`.gitignore` for git for example). 55 | 56 | ```toml 57 | [package] 58 | # ... 59 | exclude = ["build/**/*.o", "doc/**/*.html"] 60 | ``` 61 | 62 | ```toml 63 | [package] 64 | # ... 65 | include = ["src/**/*", "Cargo.toml"] 66 | ``` 67 | 68 | The options are mutually exclusive: setting `include` will override an 69 | `exclude`. Note that `include` must be an exhaustive list of files as otherwise 70 | necessary source files may not be included. 71 | 72 | [globs]: http://doc.rust-lang.org/glob/glob/struct.Pattern.html 73 | 74 | ## The `publish` field (optional) 75 | 76 | The `publish` field can be used to prevent a package from being published to a 77 | repository by mistake. 78 | 79 | ```toml 80 | [package] 81 | # ... 82 | publish = false 83 | ``` 84 | 85 | ## The `workspace` field (optional) 86 | 87 | The `workspace` field can be used to configure the workspace that this package 88 | will be a member of. If not specified this will be inferred as the first 89 | Cargo.toml with `[workspace]` upwards in the filesystem. 90 | 91 | ```toml 92 | [package] 93 | # ... 94 | workspace = "path/to/root" 95 | ``` 96 | 97 | For more information, see the documentation for the workspace table below. 98 | 99 | ## Package metadata 100 | 101 | There are a number of optional metadata fields also accepted under the 102 | `[package]` section: 103 | 104 | ```toml 105 | [package] 106 | # ... 107 | 108 | # A short blurb about the package. This is not rendered in any format when 109 | # uploaded to crates.io (aka this is not markdown). 110 | description = "..." 111 | 112 | # These URLs point to more information about the repository. 113 | documentation = "..." 114 | homepage = "..." 115 | repository = "..." 116 | 117 | # This points to a file in the repository (relative to this `Cargo.toml`). The 118 | # contents of this file are stored and indexed in the registry. 119 | readme = "..." 120 | 121 | # This is a small list of keywords used to categorize and search for this 122 | # package. 123 | keywords = ["...", "..."] 124 | 125 | # This is a string description of the license for this package. Currently 126 | # crates.io will validate the license provided against a whitelist of known 127 | # license identifiers from http://spdx.org/licenses/. Multiple licenses can be 128 | # separated with a `/`. 129 | license = "..." 130 | 131 | # If a project is using a nonstandard license, then this key may be specified in 132 | # lieu of the above key and must point to a file relative to this manifest 133 | # (similar to the readme key). 134 | license-file = "..." 135 | ``` 136 | 137 | The [crates.io](https://crates.io) registry will render the description, display 138 | the license, link to the three URLs and categorize by the keywords. These keys 139 | provide useful information to users of the registry and also influence the 140 | search ranking of a crate. It is highly discouraged to omit everything in a 141 | published crate. 142 | 143 | ## The `metadata` table (optional) 144 | 145 | Cargo by default will warn about unused keys in `Cargo.toml` to assist in 146 | detecting typos and such. The `package.metadata` table, however, is completely 147 | ignored by Cargo and will not be warned about. This section can be used for 148 | tools which would like to store project configuration in `Cargo.toml`. For 149 | example: 150 | 151 | ```toml 152 | [package] 153 | name = "..." 154 | # ... 155 | 156 | # Metadata used when generating an Android APK, for example. 157 | [package.metadata.android] 158 | package-name = "my-awesome-android-app" 159 | assets = "path/to/static" 160 | ``` 161 | 162 | # Dependency sections 163 | 164 | See the [specifying dependencies page](specifying-dependencies.html) for 165 | information on the `[dependencies]`, `[dev-dependencies]`, and target-specific 166 | `[target.*.dependencies]` sections. 167 | 168 | # The `[profile.*]` sections 169 | 170 | Cargo supports custom configuration of how rustc is invoked through profiles at 171 | the top level. Any manifest may declare a profile, but only the top level 172 | project’s profiles are actually read. All dependencies’ profiles will be 173 | overridden. This is done so the top-level project has control over how its 174 | dependencies are compiled. 175 | 176 | There are five currently supported profile names, all of which have the same 177 | configuration available to them. Listed below is the configuration available, 178 | along with the defaults for each profile. 179 | 180 | ```toml 181 | # The development profile, used for `cargo build`. 182 | [profile.dev] 183 | opt-level = 0 # controls the `--opt-level` the compiler builds with 184 | debug = true # controls whether the compiler passes `-g` 185 | rpath = false # controls whether the compiler passes `-C rpath` 186 | lto = false # controls `-C lto` for binaries and staticlibs 187 | debug-assertions = true # controls whether debug assertions are enabled 188 | codegen-units = 1 # controls whether the compiler passes `-C codegen-units` 189 | # `codegen-units` is ignored when `lto = true` 190 | panic = 'unwind' # panic strategy (`-C panic=...`), can also be 'abort' 191 | 192 | # The release profile, used for `cargo build --release`. 193 | [profile.release] 194 | opt-level = 3 195 | debug = false 196 | rpath = false 197 | lto = false 198 | debug-assertions = false 199 | codegen-units = 1 200 | panic = 'unwind' 201 | 202 | # The testing profile, used for `cargo test`. 203 | [profile.test] 204 | opt-level = 0 205 | debug = true 206 | rpath = false 207 | lto = false 208 | debug-assertions = true 209 | codegen-units = 1 210 | panic = 'unwind' 211 | 212 | # The benchmarking profile, used for `cargo bench`. 213 | [profile.bench] 214 | opt-level = 3 215 | debug = false 216 | rpath = false 217 | lto = false 218 | debug-assertions = false 219 | codegen-units = 1 220 | panic = 'unwind' 221 | 222 | # The documentation profile, used for `cargo doc`. 223 | [profile.doc] 224 | opt-level = 0 225 | debug = true 226 | rpath = false 227 | lto = false 228 | debug-assertions = true 229 | codegen-units = 1 230 | panic = 'unwind' 231 | ``` 232 | 233 | # The `[features]` section 234 | 235 | Cargo supports features to allow expression of: 236 | 237 | * conditional compilation options (usable through `cfg` attributes); 238 | * optional dependencies, which enhance a package, but are not required; and 239 | * clusters of optional dependencies, such as `postgres`, that would include the 240 | `postgres` package, the `postgres-macros` package, and possibly other packages 241 | (such as development-time mocking libraries, debugging tools, etc.). 242 | 243 | A feature of a package is either an optional dependency, or a set of other 244 | features. The format for specifying features is: 245 | 246 | ```toml 247 | [package] 248 | name = "awesome" 249 | 250 | [features] 251 | # The default set of optional packages. Most people will want to use these 252 | # packages, but they are strictly optional. Note that `session` is not a package 253 | # but rather another feature listed in this manifest. 254 | default = ["jquery", "uglifier", "session"] 255 | 256 | # A feature with no dependencies is used mainly for conditional compilation, 257 | # like `#[cfg(feature = "go-faster")]`. 258 | go-faster = [] 259 | 260 | # The `secure-password` feature depends on the bcrypt package. This aliasing 261 | # will allow people to talk about the feature in a higher-level way and allow 262 | # this package to add more requirements to the feature in the future. 263 | secure-password = ["bcrypt"] 264 | 265 | # Features can be used to reexport features of other packages. The `session` 266 | # feature of package `awesome` will ensure that the `session` feature of the 267 | # package `cookie` is also enabled. 268 | session = ["cookie/session"] 269 | 270 | [dependencies] 271 | # These packages are mandatory and form the core of this package’s distribution. 272 | cookie = "1.2.0" 273 | oauth = "1.1.0" 274 | route-recognizer = "=2.1.0" 275 | 276 | # A list of all of the optional dependencies, some of which are included in the 277 | # above `features`. They can be opted into by apps. 278 | jquery = { version = "1.0.2", optional = true } 279 | uglifier = { version = "1.5.3", optional = true } 280 | bcrypt = { version = "*", optional = true } 281 | civet = { version = "*", optional = true } 282 | ``` 283 | 284 | To use the package `awesome`: 285 | 286 | ```toml 287 | [dependencies.awesome] 288 | version = "1.3.5" 289 | default-features = false # do not include the default features, and optionally 290 | # cherry-pick individual features 291 | features = ["secure-password", "civet"] 292 | ``` 293 | 294 | ## Rules 295 | 296 | The usage of features is subject to a few rules: 297 | 298 | * Feature names must not conflict with other package names in the manifest. This 299 | is because they are opted into via `features = [...]`, which only has a single 300 | namespace. 301 | * With the exception of the `default` feature, all features are opt-in. To opt 302 | out of the default feature, use `default-features = false` and cherry-pick 303 | individual features. 304 | * Feature groups are not allowed to cyclically depend on one another. 305 | * Dev-dependencies cannot be optional. 306 | * Features groups can only reference optional dependencies. 307 | * When a feature is selected, Cargo will call `rustc` with `--cfg 308 | feature="${feature_name}"`. If a feature group is included, it and all of its 309 | individual features will be included. This can be tested in code via 310 | `#[cfg(feature = "foo")]`. 311 | 312 | Note that it is explicitly allowed for features to not actually activate any 313 | optional dependencies. This allows packages to internally enable/disable 314 | features without requiring a new dependency. 315 | 316 | ## Usage in end products 317 | 318 | One major use-case for this feature is specifying optional features in 319 | end-products. For example, the Servo project may want to include optional 320 | features that people can enable or disable when they build it. 321 | 322 | In that case, Servo will describe features in its `Cargo.toml` and they can be 323 | enabled using command-line flags: 324 | 325 | ``` 326 | $ cargo build --release --features "shumway pdf" 327 | ``` 328 | 329 | Default features could be excluded using `--no-default-features`. 330 | 331 | ## Usage in packages 332 | 333 | In most cases, the concept of *optional dependency* in a library is best 334 | expressed as a separate package that the top-level application depends on. 335 | 336 | However, high-level packages, like Iron or Piston, may want the ability to 337 | curate a number of packages for easy installation. The current Cargo system 338 | allows them to curate a number of mandatory dependencies into a single package 339 | for easy installation. 340 | 341 | In some cases, packages may want to provide additional curation for optional 342 | dependencies: 343 | 344 | * grouping a number of low-level optional dependencies together into a single 345 | high-level feature; 346 | * specifying packages that are recommended (or suggested) to be included by 347 | users of the package; and 348 | * including a feature (like `secure-password` in the motivating example) that 349 | will only work if an optional dependency is available, and would be difficult 350 | to implement as a separate package (for example, it may be overly difficult to 351 | design an IO package to be completely decoupled from OpenSSL, with opt-in via 352 | the inclusion of a separate package). 353 | 354 | In almost all cases, it is an antipattern to use these features outside of 355 | high-level packages that are designed for curation. If a feature is optional, it 356 | can almost certainly be expressed as a separate package. 357 | 358 | # The `[workspace]` section 359 | 360 | Projects can define a workspace which is a set of crates that will all share the 361 | same `Cargo.lock` and output directory. The `[workspace]` table can be defined 362 | as: 363 | 364 | ```toml 365 | [workspace] 366 | 367 | # Optional key, inferred if not present 368 | members = ["path/to/member1", "path/to/member2"] 369 | ``` 370 | 371 | Workspaces were added to Cargo as part [RFC 1525] and have a number of 372 | properties: 373 | 374 | * A workspace can contain multiple crates where one of them is the root crate. 375 | * The root crate's `Cargo.toml` contains the `[workspace]` table, but is not 376 | required to have other configuration. 377 | * Whenever any crate in the workspace is compiled, output is placed next to the 378 | root crate's `Cargo.toml`. 379 | * The lock file for all crates in the workspace resides next to the root crate's 380 | `Cargo.toml`. 381 | * The `[replace]` section in `Cargo.toml` is only recognized at the workspace 382 | root crate, it's ignored in member crates' manifests. 383 | 384 | [RFC 1525]: https://github.com/rust-lang/rfcs/blob/master/text/1525-cargo-workspace.md 385 | 386 | The root crate of a workspace, indicated by the presence of `[workspace]` in 387 | its manifest, is responsible for defining the entire workspace (listing all 388 | members). This can be done through the `members` key, and if it is omitted then 389 | members are implicitly included through all `path` dependencies. Note that 390 | members of the workspaces listed explicitly will also have their path 391 | dependencies included in the workspace. 392 | 393 | The `package.workspace` manifest key (described above) is used in member crates 394 | to point at a workspace's root crate. If this key is omitted then it is inferred 395 | to be the first crate whose manifest contains `[workspace]` upwards in the 396 | filesystem. 397 | 398 | A crate may either specify `package.workspace` or specify `[workspace]`. That 399 | is, a crate cannot both be a root crate in a workspace (contain `[workspace]`) 400 | and also be a member crate of another workspace (contain `package.workspace`). 401 | 402 | Most of the time workspaces will not need to be dealt with as `cargo new` and 403 | `cargo init` will handle workspace configuration automatically. 404 | 405 | # The project layout 406 | 407 | If your project is an executable, name the main source file `src/main.rs`. If it 408 | is a library, name the main source file `src/lib.rs`. 409 | 410 | Cargo will also treat any files located in `src/bin/*.rs` as executables. 411 | 412 | Your project can optionally contain folders named `examples`, `tests`, and 413 | `benches`, which Cargo will treat as containing example executable files, 414 | integration tests, and benchmarks respectively. 415 | 416 | ```notrust 417 | ▾ src/ # directory containing source files 418 | lib.rs # the main entry point for libraries and packages 419 | main.rs # the main entry point for projects producing executables 420 | ▾ bin/ # (optional) directory containing additional executables 421 | *.rs 422 | ▾ examples/ # (optional) examples 423 | *.rs 424 | ▾ tests/ # (optional) integration tests 425 | *.rs 426 | ▾ benches/ # (optional) benchmarks 427 | *.rs 428 | ``` 429 | 430 | To structure your code after you've created the files and folders for your project, you should remember to use Rust's module system, which you can read about in [the book](https://doc.rust-lang.org/book/crates-and-modules.html). 431 | 432 | # Examples 433 | 434 | Files located under `examples` are example uses of the functionality provided by 435 | the library. When compiled, they are placed in the `target/examples` directory. 436 | 437 | They must compile as executables (with a `main()` function) and load in the 438 | library by using `extern crate `. They are compiled when you run 439 | your tests to protect them from bitrotting. 440 | 441 | You can run individual examples with the command `cargo run --example 442 | `. 443 | 444 | # Tests 445 | 446 | When you run `cargo test`, Cargo will: 447 | 448 | * compile and run your library’s unit tests, which are in the files reachable 449 | from `lib.rs` (naturally, any sections marked with `#[cfg(test)]` will be 450 | considered at this stage); 451 | * compile and run your library’s documentation tests, which are embedded inside 452 | of documentation blocks; 453 | * compile and run your library’s [integration tests](#integration-tests); and 454 | * compile your library’s examples. 455 | 456 | ## Integration tests 457 | 458 | Each file in `tests/*.rs` is an integration test. When you run `cargo test`, 459 | Cargo will compile each of these files as a separate crate. The crate can link 460 | to your library by using `extern crate `, like any other code that 461 | depends on it. 462 | 463 | Cargo will not automatically compile files inside subdirectories of `tests`, but 464 | an integration test can import modules from these directories as usual. For 465 | example, if you want several integration tests to share some code, you can put 466 | the shared code in `tests/common/mod.rs` and then put `mod common;` in each of 467 | the test files. 468 | 469 | # Configuring a target 470 | 471 | All of the `[[bin]]`, `[lib]`, `[[bench]]`, `[[test]]`, and `[[example]]` 472 | sections support similar configuration for specifying how a target should be 473 | built. The double-bracket sections like `[[bin]]` are array-of-table of 474 | [TOML](https://github.com/toml-lang/toml#array-of-tables), which means you can 475 | write more than one `[[bin]]` section to make several executables in your crate. 476 | 477 | The example below uses `[lib]`, but it also applies to all other sections 478 | as well. All values listed are the defaults for that option unless otherwise 479 | specified. 480 | 481 | ```toml 482 | [package] 483 | # ... 484 | 485 | [lib] 486 | # The name of a target is the name of the library that will be generated. This 487 | # is defaulted to the name of the package or project, with any dashes replaced 488 | # with underscores. (Rust `extern crate` declarations reference this name; 489 | # therefore the value must be a valid Rust identifier to be usable.) 490 | name = "foo" 491 | 492 | # This field points at where the crate is located, relative to the `Cargo.toml`. 493 | path = "src/lib.rs" 494 | 495 | # A flag for enabling unit tests for this target. This is used by `cargo test`. 496 | test = true 497 | 498 | # A flag for enabling documentation tests for this target. This is only relevant 499 | # for libraries, it has no effect on other sections. This is used by 500 | # `cargo test`. 501 | doctest = true 502 | 503 | # A flag for enabling benchmarks for this target. This is used by `cargo bench`. 504 | bench = true 505 | 506 | # A flag for enabling documentation of this target. This is used by `cargo doc`. 507 | doc = true 508 | 509 | # If the target is meant to be a compiler plugin, this field must be set to true 510 | # for Cargo to correctly compile it and make it available for all dependencies. 511 | plugin = false 512 | 513 | # If the target is meant to be a "macros 1.1" procedural macro, this field must 514 | # be set to true. 515 | proc-macro = false 516 | 517 | # If set to false, `cargo test` will omit the `--test` flag to rustc, which 518 | # stops it from generating a test harness. This is useful when the binary being 519 | # built manages the test runner itself. 520 | harness = true 521 | ``` 522 | 523 | # Building dynamic or static libraries 524 | 525 | If your project produces a library, you can specify which kind of library to 526 | build by explicitly listing the library in your `Cargo.toml`: 527 | 528 | ```toml 529 | # ... 530 | 531 | [lib] 532 | name = "..." 533 | crate-type = ["dylib"] # could be `staticlib` as well 534 | ``` 535 | 536 | The available options are `dylib`, `rlib`, `staticlib`, `cdylib`, and 537 | `proc-macro`. You should only use this option in a project. Cargo will always 538 | compile packages (dependencies) based on the requirements of the project that 539 | includes them. 540 | 541 | You can read more about the different crate types in the 542 | [Rust Reference Manual](https://doc.rust-lang.org/reference.html#linkage) 543 | 544 | # The `[replace]` Section 545 | 546 | This section of Cargo.toml can be used to [override dependencies][replace] with 547 | other copies. The syntax is similar to the `[dependencies]` section: 548 | 549 | ```toml 550 | [replace] 551 | "foo:0.1.0" = { git = 'https://github.com/example/foo' } 552 | "bar:1.0.2" = { path = 'my/local/bar' } 553 | ``` 554 | 555 | Each key in the `[replace]` table is a [package id 556 | specification](pkgid-spec.html) which allows arbitrarily choosing a node in the 557 | dependency graph to override. The value of each key is the same as the 558 | `[dependencies]` syntax for specifying dependencies, except that you can't 559 | specify features. Note that when a crate is overridden the copy it's overridden 560 | with must have both the same name and version, but it can come from a different 561 | source (e.g. git or a local path). 562 | 563 | More information about overriding dependencies can be found in the [overriding 564 | dependencies][replace] section of the documentation. 565 | 566 | [replace]: specifying-dependencies.html#overriding-dependencies 567 | --------------------------------------------------------------------------------