Skip to main content

cargo_util_config/
definition.rs

1use std::cmp::Ordering;
2use std::fmt;
3use std::path::{Path, PathBuf};
4
5/// Location where a config value is defined.
6#[derive(Clone, Debug, Eq, Default)]
7pub struct Definition {
8    origin: Origin,
9    scope: Scope,
10}
11
12impl Definition {
13    pub const fn builtin() -> Self {
14        Self {
15            scope: Scope::BuiltIn,
16            origin: Origin::BuiltIn,
17        }
18    }
19
20    pub fn path(path: PathBuf) -> Self {
21        Self {
22            scope: Scope::Path,
23            origin: Origin::Path(path),
24        }
25    }
26
27    pub fn environment(key: String) -> Self {
28        Self {
29            scope: Scope::Environment,
30            origin: Origin::Environment(key),
31        }
32    }
33
34    pub fn cli(path: Option<PathBuf>) -> Self {
35        Self {
36            scope: Scope::Cli,
37            origin: path.map(Origin::Path).unwrap_or(Origin::Cli),
38        }
39    }
40
41    pub fn origin(&self) -> &Origin {
42        &self.origin
43    }
44
45    /// Returns the scope in which the config value is defined.
46    pub fn scope(&self) -> Scope {
47        self.scope
48    }
49
50    /// Root directory where this is defined.
51    ///
52    /// If from a file, it is the directory above `.cargo/config.toml`.
53    /// CLI and env use the provided current working directory.
54    pub fn root<'a>(&'a self, current_dir: &'a Path) -> &'a Path {
55        self.origin
56            .as_path()
57            .map(|p| p.parent().unwrap().parent().unwrap())
58            .unwrap_or(current_dir)
59    }
60
61    /// Parent directory where this is defined.
62    ///
63    /// If from a file, it is the directory `.cargo/`.
64    /// CLI and env use the provided current working directory.
65    pub fn parent<'a>(&'a self, current_dir: &'a Path) -> &'a Path {
66        self.origin
67            .as_path()
68            .map(|p| p.parent().unwrap())
69            .unwrap_or(current_dir)
70    }
71
72    /// Returns true if self is a higher priority to other.
73    ///
74    /// CLI is preferred over environment, which is preferred over files.
75    pub fn is_higher_priority(&self, other: &Definition) -> bool {
76        self.scope().is_higher_priority(other.scope())
77    }
78}
79
80impl PartialOrd for Definition {
81    fn partial_cmp(&self, other: &Definition) -> Option<Ordering> {
82        Some(self.cmp(other))
83    }
84}
85
86impl Ord for Definition {
87    fn cmp(&self, other: &Definition) -> Ordering {
88        self.scope().cmp(&other.scope())
89    }
90}
91
92impl PartialEq for Definition {
93    fn eq(&self, other: &Definition) -> bool {
94        // configuration values are equivalent no matter where they're defined,
95        // but they need to be defined in the same location. For example if
96        // they're defined in the environment that's different than being
97        // defined in a file due to path interpretations.
98        self.scope() == other.scope()
99    }
100}
101
102impl fmt::Display for Definition {
103    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
104        self.origin.fmt(f)
105    }
106}
107
108/// Immediate location where a config value came from
109#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
110pub enum Origin {
111    #[default]
112    BuiltIn,
113    /// Defined in the specified TOML file
114    Path(PathBuf),
115    /// Env variable where this came from
116    Environment(String),
117    /// Passed in on the command line.
118    Cli,
119}
120
121impl Origin {
122    pub fn as_path(&self) -> Option<&Path> {
123        match self {
124            Self::Path(p) => Some(p.as_path()),
125            Self::Environment(_) | Self::Cli | Self::BuiltIn => None,
126        }
127    }
128}
129
130impl fmt::Display for Origin {
131    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
132        match self {
133            Origin::Path(p) => p.display().fmt(f),
134            Origin::Environment(key) => write!(f, "environment variable `{}`", key),
135            Origin::Cli => write!(f, "--config cli option"),
136            Origin::BuiltIn => write!(f, "default"),
137        }
138    }
139}
140
141/// The kind of source where a config value is defined.
142///
143/// In priority order.
144#[derive(Clone, Copy, Default, Debug, PartialOrd, Ord, PartialEq, Eq)]
145pub enum Scope {
146    /// A built-in value.
147    #[default]
148    BuiltIn,
149    /// Loaded due to config file discovery.
150    Path,
151    /// A value defined in an environment variable.
152    Environment,
153    /// Loaded due to a request from the global cli arg `--config`
154    ///
155    /// Configs loaded via `include` are also seen as from cli args,
156    /// if the initial config is being loaded from cli.
157    Cli,
158}
159
160impl Scope {
161    /// Returns true if self is a higher priority to other.
162    ///
163    /// CLI is preferred over environment, which is preferred over files.
164    pub fn is_higher_priority(&self, other: Self) -> bool {
165        *self > other
166    }
167}