cargo/config/
definition.rs1use std::cmp::Ordering;
2use std::fmt;
3use std::mem;
4use std::path::{Path, PathBuf};
5
6#[derive(Clone, Copy, Debug)]
8pub enum DefinitionKind {
9 BuiltIn,
11 Path,
13 Environment,
15 Cli,
20}
21
22#[derive(Clone, Debug, Eq, Default)]
24pub enum Definition {
25 #[default]
26 BuiltIn,
27 Path(PathBuf),
29 Environment(String),
31 Cli(Option<PathBuf>),
34}
35
36impl PartialOrd for Definition {
37 fn partial_cmp(&self, other: &Definition) -> Option<Ordering> {
38 Some(self.cmp(other))
39 }
40}
41
42impl Ord for Definition {
43 fn cmp(&self, other: &Definition) -> Ordering {
44 if mem::discriminant(self) == mem::discriminant(other) {
45 Ordering::Equal
46 } else if self.is_higher_priority(other) {
47 Ordering::Greater
48 } else {
49 Ordering::Less
50 }
51 }
52}
53
54impl Definition {
55 pub fn root<'a>(&'a self, cwd: &'a Path) -> &'a Path {
60 match self {
61 Definition::Path(p) | Definition::Cli(Some(p)) => p.parent().unwrap().parent().unwrap(),
62 Definition::Environment(_) | Definition::Cli(None) | Definition::BuiltIn => cwd,
63 }
64 }
65
66 pub fn is_higher_priority(&self, other: &Definition) -> bool {
70 matches!(
71 (self, other),
72 (Definition::Cli(_), Definition::Environment(_))
73 | (Definition::Cli(_), Definition::Path(_))
74 | (Definition::Cli(_), Definition::BuiltIn)
75 | (Definition::Environment(_), Definition::Path(_))
76 | (Definition::Environment(_), Definition::BuiltIn)
77 | (Definition::Path(_), Definition::BuiltIn)
78 )
79 }
80}
81
82impl PartialEq for Definition {
83 fn eq(&self, other: &Definition) -> bool {
84 mem::discriminant(self) == mem::discriminant(other)
89 }
90}
91
92impl fmt::Display for Definition {
93 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94 match self {
95 Definition::Path(p) | Definition::Cli(Some(p)) => p.display().fmt(f),
96 Definition::Environment(key) => write!(f, "environment variable `{}`", key),
97 Definition::Cli(None) => write!(f, "--config cli option"),
98 Definition::BuiltIn => write!(f, "default"),
99 }
100 }
101}