如何覆盖 Cargo 配置目录的位置?

How can the location of Cargo's configuration directory be overridden?

Cargo 在搜索其配置目录时的默认行为似乎是在当前用户的主目录中查找(~/.cargo 在我的系统上)。如何修改此行为以使 Cargo 在用户提供的目录中查找?

可以通过环境变量 $CARGO_HOME 更改默认位置,它会覆盖默认位置 $HOME/.cargo

Environment variables Cargo reads

You can override these environment variables to change Cargo's behavior on your system:

  • CARGO_HOME — Cargo maintains a local cache of the registry index and of git checkouts of crates. By default these are stored under $HOME/.cargo, but this variable overrides the location of this directory. Once a crate is cached it is not removed by the clean command.
  • CARGO_TARGET_DIR — Location of where to place all generated artifacts, relative to the current working directory.
  • RUSTC — Instead of running rustc, Cargo will execute this specified compiler instead.
  • RUSTC_WRAPPER — Instead of simply running rustc, Cargo will execute this specified wrapper instead, passing as its commandline arguments the rustc invocation, with the first argument being rustc.
  • RUSTDOC — Instead of running rustdoc, Cargo will execute this specified rustdoc instance instead.
  • RUSTDOCFLAGS — A space-separated list of custom flags to pass to all rustdoc invocations that Cargo performs. In contrast with cargo rustdoc, this is useful for passing a flag to all rustdoc instances.
  • RUSTFLAGS — A space-separated list of custom flags to pass to all compiler invocations that Cargo performs. In contrast with cargo rustc, this is useful for passing a flag to all compiler instances.
  • CARGO_INCREMENTAL — If this is set to 1 then Cargo will force incremental compilation to be enabled for the current compilation, and when set to 0 it will force disabling it. If this env var isn't present then cargo's defaults will otherwise be used.
  • CARGO_CACHE_RUSTC_INFO — If this is set to 0 then Cargo will not try to cache compiler version information.

The Cargo documentation


Hierarchical structure

Cargo allows local configuration for a particular package as well as global configuration, like git. Cargo extends this to a hierarchical strategy. If, for example, Cargo were invoked in /projects/foo/bar/baz, then the following configuration files would be probed for and unified in this order:

  • /projects/foo/bar/baz/.cargo/config
  • /projects/foo/bar/.cargo/config
  • /projects/foo/.cargo/config
  • /projects/.cargo/config
  • /.cargo/config
  • $HOME/.cargo/config

With this structure, you can specify configuration per-package, and even possibly check it into version control. You can also specify personal defaults with a configuration file in your home directory.

The Cargo documentation