cargo_util_config/
definition.rs1use std::cmp::Ordering;
2use std::fmt;
3use std::path::{Path, PathBuf};
4
5#[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 pub fn scope(&self) -> Scope {
47 self.scope
48 }
49
50 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 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 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 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#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
110pub enum Origin {
111 #[default]
112 BuiltIn,
113 Path(PathBuf),
115 Environment(String),
117 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#[derive(Clone, Copy, Default, Debug, PartialOrd, Ord, PartialEq, Eq)]
145pub enum Scope {
146 #[default]
148 BuiltIn,
149 Path,
151 Environment,
153 Cli,
158}
159
160impl Scope {
161 pub fn is_higher_priority(&self, other: Self) -> bool {
165 *self > other
166 }
167}