LoginSignup
81
62

More than 5 years have passed since last update.

Cargo.toml の編集に cargo-edit を使う

Last updated at Posted at 2016-07-28

cargo-edit について cargo-edit の README.md をベースに簡単に日本語でまとめています。

※ 執筆時点の cargo-edit のバージョンは cargo-edit-0.1.3 です。

cargo は Rust の強力なツールの一つで、パッケージの取得、ビルドといった機能を持っています。
パッケージの追加や削除といった作業は Cargo.toml を編集して行えます。
管理するパッケージが増えるにつれ、依存解決やバージョンの変更などを行いたくなる場合、ファイルの編集というインターフェースはエディタで開くという手間もあり面倒に感じることが多くなるでしょう。
cargo-edit はそれを解決してくれるツールで、パッケージの追加・削除・確認を行うことができます。

cargo-edit:
https://github.com/killercup/cargo-edit

インストール

cargo install でインストールできます。 cargo はなるべく最新版を利用することが推奨されています。

cargo install cargo-edit

使い方

cargo に以下のサブコマンドをサポートする形でインストールされます。

  • cargo add
  • cargo list
  • cargo rm

各サブコマンドは cargo のサブコマンドと同様に cargo add --help のようにサブコマンドの後に --help を指定するとヘルプが出力されます。

cargo add

cargo add は名前の通り、パッケージを追加します。

# パッケージ名@バージョン でバージョンを指定する
$ cargo add regex@0.1.41
# バージョンが指定されない場合は最新のバージョン番号を crates.io から取得する
$ cargo add rand --build
# crates.io に存在しないパッケージを追加することもできる
$ mkdir -pv ./lib/trial-and-error
$ cd ./lib/trial-and-error
$ cargo init --name local_experiment
$ cd ../../
$ cargo add local_experiment --path=lib/trial-and-error/

Cargo.toml はこうなります。

[package]
authors = ["kizkoh"]
name = "study"
version = "0.1.0"

[build-dependencies]
rand = "0.3.14"

[dependencies]
regex = "0.1.41"

[dependencies.local_experiment]
optional = false
path = "lib/trial-and-error/"

cargo list

cargo list は依存パッケージの一覧を出力します。

# cargo build しないと `Your Cargo.toml is missing.` が出力される
$ cargo build
# --tree オプションで依存木を出力できる
$ cargo list --tree
├── rand (0.3.14)
│   └── libc (0.2.14)
└── regex (0.1.73)
    ├── aho-corasick (0.5.2)
    │   └── memchr (0.1.11)
    │       └── libc (0.2.14)
    ├── memchr (0.1.11)
    │   └── libc (0.2.14)
    ├── regex-syntax (0.3.4)
    ├── thread_local (0.2.6)
    │   └── thread-id (2.0.0)
    │       ├── kernel32-sys (0.2.2)
    │       │   ├── winapi (0.2.8)
    │       │   └── winapi-build (0.1.1)
    │       └── libc (0.2.14)
    └── utf8-ranges (0.1.3)

cargo rm

cargo rmcargo add の逆の操作です。

# regex の依存を削除する
$ cargo rm regex
# rand の依存を削除する
$ cargo rm rand --build

Cargo.toml はこうなります。

[package]
authors = ["kizkoh"]
name = "study"
version = "0.1.0"

[dependencies]

[dependencies.local_experiment]
optional = false
path = "lib/trial-and-error/"

まとめ

ターミナルは常にビルドやテストのため開いていると思います。
cargo-edit を使えばエディタで Cargo.toml を開くことなくコマンド一つでパッケージの追加・削除・確認を行うことができます。

また、記事中では例に取り上げませんでしたが cargo add で追加したパッケージはアルファベット順にソートされます。 rustfmt を使ってコードはフォーマッティングできても Cargo.toml はフォーマットできません。見栄えを気にする際も便利なツールです。使わない理由はないですね!

81
62
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
81
62