/
store.rs
281 lines (237 loc) · 8.72 KB
/
store.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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
use anyhow::{anyhow, Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
use std::fmt::{self, Display};
use std::fs;
use std::io;
use std::path::PathBuf;
use crate::importfinder;
static AUTOGEN_HEADER: &str = "# WARNING: this file is managed with `elm-forbid-imports`. Manual edits will\n# be overwritten!\n\n";
#[derive(Debug, Deserialize, Serialize)]
pub struct Store {
#[serde(skip)]
config_path: PathBuf,
#[serde(default, skip_serializing_if = "btreeset_is_empty")]
roots: BTreeSet<PathBuf>,
#[serde(default, skip_serializing_if = "forbidden_is_empty")]
forbidden: BTreeMap<String, ForbiddenImport>,
}
#[derive(Debug, Deserialize, Serialize)]
struct ForbiddenImport {
hint: Option<String>,
#[serde(default, skip_serializing_if = "btreeset_is_empty")]
usages: BTreeSet<PathBuf>,
}
fn btreeset_is_empty(roots: &BTreeSet<PathBuf>) -> bool {
roots.is_empty()
}
fn forbidden_is_empty(forbidden: &BTreeMap<String, ForbiddenImport>) -> bool {
forbidden.is_empty()
}
impl Store {
pub fn from_file_or_empty(path: &PathBuf) -> Result<Store> {
match fs::read(&path) {
Ok(source) => {
let mut out: Store = toml::from_slice(&source)
.context("could not read TOML from the config file")?;
out.config_path = path.to_owned();
Ok(out)
}
Err(err) => match err.kind() {
io::ErrorKind::NotFound => Ok(Store {
config_path: path.to_owned(),
roots: BTreeSet::new(),
forbidden: BTreeMap::new(),
}),
_ => Err(anyhow!(err)),
},
}
}
pub fn forbid(&mut self, name: String, hint: Option<String>) {
if let Some(value) = self.forbidden.get_mut(&name) {
value.hint = hint
} else {
self.forbidden.insert(
name,
ForbiddenImport {
hint,
usages: BTreeSet::new(),
},
);
};
}
pub fn unforbid(&mut self, name: String) {
self.forbidden.remove(&name);
}
fn relative_to_config_path(&self, path: PathBuf) -> Result<PathBuf> {
match self.config_path.parent() {
Some(parent) => match pathdiff::diff_paths(&path.to_owned(), parent) {
Some(relative) => Ok(relative),
None => Err(anyhow!(
"could not compute a relative path between {} and {}",
self.config_path.display(),
path.display()
)),
},
None => Err(anyhow!(
"root config path ({}) does not have a parent.",
self.config_path.display()
)),
}
}
fn absolute_from_config_path(&self, path: PathBuf) -> Result<PathBuf> {
match self.config_path.parent() {
Some(parent) => {
let out = parent.join(&path).canonicalize().with_context(|| {
format!(
"could not make an absolute path with the config file and {}",
path.display()
)
})?;
Ok(out)
}
None => Err(anyhow!(
"root config path ({}) does not have a parent.",
self.config_path.display(),
)),
}
}
pub fn add_root(&mut self, path: PathBuf) -> Result<()> {
self.roots.insert(
self.relative_to_config_path(path)
.context("could not find a path from the config file to the new root")?,
);
Ok(())
}
pub fn remove_root(&mut self, path: PathBuf) -> Result<()> {
self.roots.remove(
&self
.relative_to_config_path(path)
.context("could not find a path from the config file to the root to remove")?,
);
Ok(())
}
pub fn write(&self) -> Result<()> {
let serialized =
toml::to_string_pretty(self).context("could not serialize the store to TOML")?;
if serialized.is_empty() && self.config_path.exists() {
fs::remove_file(&self.config_path)
.context("could not remove the newly-empty config file")?;
} else {
fs::write(
&self.config_path,
String::from(AUTOGEN_HEADER) + &serialized,
)
.context("could not write the new config file to disk")?;
}
Ok(())
}
pub fn update(&mut self) -> Result<()> {
let imports_to_files = self
.scan()
.context("could not scan the roots for Elm files")?;
for (import, existing) in self.forbidden.iter_mut() {
existing.usages = match imports_to_files.get(import) {
Some(new_usages) => new_usages
.iter()
.map(|found| found.path.to_owned())
.collect(),
None => BTreeSet::new(),
}
}
Ok(())
}
pub fn check(&mut self) -> Result<Vec<CheckResult>> {
let imports_to_files = self
.scan()
.context("could not scan the roots for Elm files")?;
let mut out = Vec::new();
for (import, existing) in self.forbidden.iter() {
if let Some(found_imports) = imports_to_files.get(import) {
let new_usages = found_imports
.iter()
.map(|found| found.path.to_owned())
.collect::<BTreeSet<PathBuf>>();
let mut to_positions: BTreeMap<&PathBuf, importfinder::Position> = BTreeMap::new();
for import in found_imports.iter() {
to_positions.insert(&import.path, import.position);
}
for file in new_usages.difference(&existing.usages) {
out.push(CheckResult {
file: file.to_path_buf(),
position: to_positions.get(file).copied(),
import: import.to_string(),
error_location: ErrorLocation::InElmSource {
hint: existing.hint.as_ref(),
},
});
}
for file in existing.usages.difference(&new_usages) {
out.push(CheckResult {
file: file.to_path_buf(),
position: None,
import: import.to_string(),
error_location: ErrorLocation::InConfig,
})
}
}
}
Ok(out)
}
pub fn scan(&mut self) -> Result<BTreeMap<String, BTreeSet<importfinder::FoundImport>>> {
let mut absolute_roots = BTreeSet::new();
for root in self.roots.iter() {
absolute_roots.insert(self.absolute_from_config_path(root.to_owned())?);
}
let finder = importfinder::ImportFinder::new(absolute_roots);
finder.find()
}
}
#[derive(Debug, Serialize)]
pub struct CheckResult<'a> {
file: PathBuf,
position: Option<importfinder::Position>,
import: String,
error_location: ErrorLocation<'a>,
}
#[derive(Debug, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
enum ErrorLocation<'a> {
InElmSource { hint: Option<&'a String> },
InConfig,
}
impl CheckResult<'_> {
pub fn error_is_in_config(&self) -> bool {
self.error_location == ErrorLocation::InConfig
}
}
impl Display for CheckResult<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.error_location {
ErrorLocation::InElmSource { hint } => {
let hint_string = match hint {
Some(an_actual_hint) => format!(" ({})", an_actual_hint),
None => String::new(),
};
let position_string = match &self.position {
Some(position) => format!(":{}:{}", position.row, position.column),
None => String::new(),
};
write!(
f,
"{}{}:forbidden import {}{}",
self.file.to_str().unwrap_or("<unprintable file path>"),
position_string,
self.import,
hint_string,
)
}
ErrorLocation::InConfig => write!(
f,
"{}: removed forbidden import {}! (Run me with `update` to fix this.)",
self.file.to_str().unwrap_or("<unprintable file path>"),
self.import,
),
}
}
}