-
Notifications
You must be signed in to change notification settings - Fork 902
/
Copy pathsettings.rs
237 lines (206 loc) · 6.29 KB
/
settings.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
use std::cell::RefCell;
use std::collections::BTreeMap;
use std::fmt;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use crate::cli::self_update::SelfUpdateMode;
use crate::dist::Profile;
use crate::errors::*;
use crate::notifications::*;
use crate::utils::utils;
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SettingsFile {
path: PathBuf,
cache: RefCell<Option<Settings>>,
}
impl SettingsFile {
pub(crate) fn new(path: PathBuf) -> Self {
Self {
path,
cache: RefCell::new(None),
}
}
fn write_settings(&self) -> Result<()> {
let settings = self.cache.borrow();
utils::write_file(
"settings",
&self.path,
&settings.as_ref().unwrap().stringify()?,
)?;
Ok(())
}
fn read_settings(&self) -> Result<()> {
let mut needs_save = false;
{
let b = self.cache.borrow();
if b.is_none() {
drop(b);
*self.cache.borrow_mut() = Some(if utils::is_file(&self.path) {
let content = utils::read_file("settings", &self.path)?;
Settings::parse(&content).with_context(|| RustupError::ParsingFile {
name: "settings",
path: self.path.clone(),
})?
} else {
needs_save = true;
Default::default()
});
}
}
if needs_save {
self.write_settings()?;
}
Ok(())
}
pub(crate) fn with<T, F: FnOnce(&Settings) -> Result<T>>(&self, f: F) -> Result<T> {
self.read_settings()?;
// Settings can no longer be None so it's OK to unwrap
f(self.cache.borrow().as_ref().unwrap())
}
pub(crate) fn with_mut<T, F: FnOnce(&mut Settings) -> Result<T>>(&self, f: F) -> Result<T> {
self.read_settings()?;
// Settings can no longer be None so it's OK to unwrap
let result = { f(self.cache.borrow_mut().as_mut().unwrap())? };
self.write_settings()?;
Ok(result)
}
}
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub struct Settings {
pub version: MetadataVersion,
#[serde(skip_serializing_if = "Option::is_none")]
pub default_host_triple: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub default_toolchain: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub profile: Option<Profile>,
#[serde(default)]
pub overrides: BTreeMap<String, String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub pgp_keys: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub auto_self_update: Option<SelfUpdateMode>,
}
impl Settings {
fn path_to_key(path: &Path, notify_handler: &dyn Fn(Notification<'_>)) -> String {
if path.exists() {
utils::canonicalize_path(path, notify_handler)
.display()
.to_string()
} else {
path.display().to_string()
}
}
pub(crate) fn remove_override(
&mut self,
path: &Path,
notify_handler: &dyn Fn(Notification<'_>),
) -> bool {
let key = Self::path_to_key(path, notify_handler);
self.overrides.remove(&key).is_some()
}
pub(crate) fn add_override(
&mut self,
path: &Path,
toolchain: String,
notify_handler: &dyn Fn(Notification<'_>),
) {
let key = Self::path_to_key(path, notify_handler);
notify_handler(Notification::SetOverrideToolchain(path, &toolchain));
self.overrides.insert(key, toolchain);
}
pub(crate) fn dir_override(
&self,
dir: &Path,
notify_handler: &dyn Fn(Notification<'_>),
) -> Option<String> {
let key = Self::path_to_key(dir, notify_handler);
self.overrides.get(&key).cloned()
}
pub(crate) fn parse(data: &str) -> Result<Self> {
toml::from_str(data).context("error parsing settings")
}
fn stringify(&self) -> Result<String> {
Ok(toml::to_string(self)?)
}
}
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub(crate) enum MetadataVersion {
#[serde(rename = "2")]
V2,
#[serde(rename = "12")]
#[default]
V12,
}
impl MetadataVersion {
fn as_str(&self) -> &'static str {
match self {
Self::V2 => "2",
Self::V12 => "12",
}
}
}
impl FromStr for MetadataVersion {
type Err = RustupError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"2" => Ok(Self::V2),
"12" => Ok(Self::V12),
_ => Err(RustupError::UnknownMetadataVersion(s.to_owned())),
}
}
}
impl fmt::Display for MetadataVersion {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.as_str())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn serialize_default() {
let settings = Settings::default();
let toml = settings.stringify().unwrap();
assert_eq!(
toml,
r#"version = "12"
[overrides]
"#
);
}
#[test]
fn deserialize_default() {
let toml = r#"version = "12""#;
let settings = Settings::parse(toml).unwrap();
assert_eq!(settings.version, MetadataVersion::V12);
}
#[test]
fn serialize_basic() {
let settings = Settings {
version: MetadataVersion::V12,
default_toolchain: Some("stable-aarch64-apple-darwin".to_owned()),
profile: Some(Profile::Default),
..Default::default()
};
let toml = settings.stringify().unwrap();
assert_eq!(toml, BASIC);
}
#[test]
fn deserialize_basic() {
let settings = Settings::parse(BASIC).unwrap();
assert_eq!(settings.version, MetadataVersion::V12);
assert_eq!(
settings.default_toolchain,
Some("stable-aarch64-apple-darwin".to_owned())
);
assert_eq!(settings.profile, Some(Profile::Default));
}
const BASIC: &str = r#"version = "12"
default_toolchain = "stable-aarch64-apple-darwin"
profile = "default"
[overrides]
"#;
}