|
| 1 | +## 14.6.1 Install a Binary Crate from crates.io |
| 2 | +You can use the `cargo install` command to install a binary crate from [crates.io](https://crates.io/). This is not meant to replace system packages; it is intended as a convenient way for Rust developers to install tools shared by others. |
| 3 | + |
| 4 | +Its limitation is that it can only install crates that have a binary target. A binary target is an executable program, produced by a crate that has `src/main.rs` or is otherwise configured as a binary crate. |
| 5 | + |
| 6 | +Since there is the concept of a binary target, there is also the concept of a library target. A library target cannot be run by itself. |
| 7 | + |
| 8 | +Usually, the `README.md` file contains a description of the crate and tells you whether the crate has a library target, a binary target, or both. |
| 9 | + |
| 10 | +## 14.6.2 `cargo install` |
| 11 | +Binary files installed by `cargo install` are placed in the `bin` folder under the home directory. |
| 12 | + |
| 13 | +If you installed Rust with the default `rustup` configuration, the binary directory is `$HOME/.cargo/bin`. |
| 14 | + |
| 15 | +To make programs installed by `cargo install` directly executable, you need to make sure that directory is in the `$PATH` environment variable. |
| 16 | + |
| 17 | +For example, in Chapter 12 we mentioned the Rust implementation of the `grep` tool, called `ripgrep`, which is used to search files. To install `ripgrep`, we can run: |
| 18 | +```text |
| 19 | +$ cargo install ripgrep |
| 20 | + Updating crates.io index |
| 21 | + Downloaded ripgrep v13.0.0 |
| 22 | + Downloaded 1 crate (243.3 KB) in 0.88s |
| 23 | + Installing ripgrep v13.0.0 |
| 24 | +...... |
| 25 | + Compiling ripgrep v13.0.0 |
| 26 | + Finished release [optimized + debuginfo] target(s) in 3m 10s |
| 27 | + Installing ~/.cargo/bin/rg |
| 28 | + Installed package `ripgrep v13.0.0` (executable `rg`) |
| 29 | +``` |
| 30 | +Some output has been omitted, but this is roughly what it looks like. The penultimate line shows that the program was installed at `~/.cargo/bin/rg`. |
| 31 | + |
| 32 | +In the terminal, use `echo $PATH` to check whether this directory is in the environment variable. |
| 33 | + |
| 34 | +## 14.6.3 Extending Cargo with Custom Commands |
| 35 | +Cargo is designed so that it can be extended with subcommands. |
| 36 | + |
| 37 | +For example, if a binary in `$PATH` is named `cargo-something`, you can run it with `cargo something`, treating it as if it were a Cargo subcommand. |
| 38 | + |
| 39 | +When you run `cargo --list`, custom commands like this are also listed. Being able to install extensions with `cargo install` and then run them like built-in Cargo tools is a very convenient benefit of Cargo’s design. |
0 commit comments