strut_core/pivot.rs
1use std::env;
2use std::path::PathBuf;
3
4/// Owns the logic for [resolving](Pivot::resolve) the runtime pivot directory.
5///
6/// ## Pivot directory
7///
8/// Pivot directory is the current working directory of the runtime process,
9/// **unless** running using Cargo (e.g.: `cargo run`, `cargo test`, via IDE,
10/// etc.): then it’s the directory containing `Cargo.toml`.
11pub struct Pivot;
12
13impl Pivot {
14 /// Resolves the **pivot directory** at runtime, which is the directory
15 /// relative to which the file queries are normally performed.
16 ///
17 /// Example: the config directory, when given as a relative path, is
18 /// resolved relative to the pivot directory.
19 ///
20 /// When running a binary in a development environment (e.g.: using
21 /// `cargo run`, `cargo test`, or from an IDE), the pivot directory is the
22 /// directory containing the crate’s `Cargo.toml` file. This is detected by
23 /// reading the `CARGO_MANIFEST_DIR` environment variable at runtime.
24 ///
25 /// When running a binary without using `cargo` (e.g., by executing the
26 /// binary in production), the `CARGO_MANIFEST_DIR` environment variable is
27 /// normally not set, and the pivot directory is the process’s
28 /// [current](env::current_dir) working directory.
29 pub fn resolve() -> PathBuf {
30 env::var("CARGO_MANIFEST_DIR")
31 .map(PathBuf::from)
32 .unwrap_or_else(|_| Self::require_current_dir())
33 }
34
35 /// Returns the current working directory at runtime, or panics if it is not
36 /// accessible (e.g., it doesn’t exist or the user has insufficient
37 /// permissions).
38 fn require_current_dir() -> PathBuf {
39 env::current_dir().expect(concat!(
40 "it should be possible to access the current working directory",
41 " at runtime"
42 ))
43 }
44}