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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
//! Adoption of files left behind by the `simon` → IronMonitor rename.
//!
//! The rename moved this crate's state from `<config>/simon/` to
//! `<config>/ironmon/`, which strands three files a user may already have: the
//! configuration, the consent record, and the profile audit log. Nothing read
//! the old location, so a rename that changed no behaviour still lost a user's
//! settings.
//!
//! **This is one module because there are three call sites.** Written per call
//! site it would be the same defect this crate has now recorded four times —
//! four parsers for `vm.swapusage`, three copies of one page size, eight copies
//! of one idle expression. The rule is to count the copies first.
//!
//! Two decisions worth keeping:
//!
//! - **Copy, never move.** The legacy file stays where it is. A user who
//! downgrades still has it, and a migration that goes wrong has destroyed
//! nothing. The cost is a duplicate file, which is cheap.
//! - **Consent is not adopted.** [`adopt`] is deliberately not called for
//! `consent.toml`. Copying it would silently restore a privilege grant the
//! user made to a program under a different name, and this crate's standing
//! rule is that absent consent is asked for rather than assumed.
//! [`legacy_consent_exists`] reports the file so a caller can *tell* the user
//! it is there, which is the honest half of the same job.
use std::path::{Path, PathBuf};
/// The directory name this crate's state used before the rename.
const LEGACY_DIR: &str = "simon";
/// The directory name it uses now.
const CURRENT_DIR: &str = "ironmon";
/// What [`adopt`] did.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Adoption {
/// The current file already existed and was left alone. Adoption never
/// overwrites: a file at the new path is the user's current state, whatever
/// sits at the old one.
AlreadyPresent,
/// The legacy file was copied to the current path, which is returned.
Adopted(PathBuf),
/// Neither path holds a file, or the legacy path could not be derived.
Nothing,
/// A legacy file was found but could not be copied. Carries the reason.
/// Adoption is best-effort — a caller that cannot copy still has a usable
/// default — so this is reported rather than raised.
Failed(String),
}
/// The path this file would have had before the rename, if it is one of ours.
///
/// Returns `None` when no path component is `ironmon`, so a caller that passes
/// an unrelated path gets nothing rather than a rewritten neighbour.
pub fn legacy_path(current: &Path) -> Option<PathBuf> {
let mut out = PathBuf::new();
let mut rewrote = false;
for component in current.components() {
if component.as_os_str() == CURRENT_DIR {
out.push(LEGACY_DIR);
rewrote = true;
} else {
out.push(component);
}
}
rewrote.then_some(out)
}
/// Copy the pre-rename file into place if the current one is absent.
///
/// Best-effort and idempotent: calling it on every load is correct, because the
/// second call finds the file it created and reports [`Adoption::AlreadyPresent`].
pub fn adopt(current: &Path) -> Adoption {
if current.exists() {
return Adoption::AlreadyPresent;
}
let Some(legacy) = legacy_path(current) else {
return Adoption::Nothing;
};
if !legacy.is_file() {
return Adoption::Nothing;
}
if let Some(parent) = current.parent() {
if let Err(e) = std::fs::create_dir_all(parent) {
return Adoption::Failed(format!(
"could not create {} to adopt {}: {e}",
parent.display(),
legacy.display()
));
}
}
match std::fs::copy(&legacy, current) {
Ok(_) => Adoption::Adopted(legacy),
Err(e) => Adoption::Failed(format!(
"could not copy {} to {}: {e}",
legacy.display(),
current.display()
)),
}
}
/// Whether a pre-rename consent record exists beside the current path.
///
/// Consent is reported, never adopted — see the module docs.
pub fn legacy_consent_exists(current: &Path) -> Option<PathBuf> {
if current.exists() {
return None;
}
legacy_path(current).filter(|p| p.is_file())
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
/// A directory this test owns, removed when it goes out of scope.
///
/// **The leak is what this fixes, and it is worth being precise about what
/// it does not.** The name was `pid + ThreadId` and nothing ever deleted the
/// directory, so runs accumulated — 200 were on the development machine when
/// this was written. Since the operating system reuses both process ids and
/// thread ids, a later run can build a name a previous run already used, and
/// the helper's `remove_dir_all` then `create_dir_all` is racy on Windows,
/// where a directory pending deletion answers a create with
/// `ERROR_ACCESS_DENIED`. The unique name removes both the collision and the
/// need to delete anything first.
///
/// **Why the six tests were failing took two wrong answers to reach.** They
/// failed with `PermissionDenied`; the first explanation was the collision
/// above, the second was a `%TEMP%` holding 32,471 entries in which creating
/// any file intermittently fails. The second was reached by noting the
/// linker failing at the same time on its own `lnk{GUID}.tmp`.
///
/// The nearer truth is narrower: on the sandboxed shell this was developed
/// under, **`%TEMP%` permits creating a directory and refuses to delete
/// one** — demonstrated by creating a directory there and failing to remove
/// it seconds later. So the old helper's `remove_dir_all` could not succeed,
/// and the `create_dir_all` that followed it on the same path failed. The
/// unique name is what fixes that, by removing the need to delete anything
/// before creating it.
///
/// The guard's `Drop` cannot delete either, under that sandbox. It is kept
/// because it costs nothing and works everywhere else, including CI. It is
/// not why these tests pass.
struct TempDir(PathBuf);
impl Drop for TempDir {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
impl std::ops::Deref for TempDir {
type Target = Path;
fn deref(&self) -> &Path {
&self.0
}
}
fn temp() -> TempDir {
use std::sync::atomic::{AtomicU64, Ordering};
static SEQ: AtomicU64 = AtomicU64::new(0);
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0);
let dir = std::env::temp_dir().join(format!(
"ironmon-legacy-{}-{:x}-{}",
std::process::id(),
nanos,
SEQ.fetch_add(1, Ordering::Relaxed)
));
// No `remove_dir_all` first: the name is unique, so there is nothing to
// remove, and asking would reintroduce the race this comment is about.
fs::create_dir_all(&dir).unwrap();
TempDir(dir)
}
#[test]
fn the_legacy_path_swaps_only_the_project_directory() {
let current = Path::new("/home/u/.config/ironmon/config.toml");
assert_eq!(
legacy_path(current),
Some(PathBuf::from("/home/u/.config/simon/config.toml"))
);
}
#[test]
fn a_path_that_is_not_ours_has_no_legacy_form() {
// Nothing to rewrite, so nothing is claimed. A helper that guessed here
// would happily point at a stranger's directory.
assert_eq!(legacy_path(Path::new("/home/u/.config/other/x.toml")), None);
assert_eq!(legacy_path(Path::new("/etc/passwd")), None);
}
#[test]
fn a_filename_that_merely_contains_the_name_is_not_a_component() {
// `ironmon_profile_audit.log` is a file name, not the project directory,
// and rewriting it would invent a path nothing ever wrote.
assert_eq!(
legacy_path(Path::new("/var/lib/ironmon_profile_audit.log")),
None
);
}
#[test]
fn an_existing_file_is_never_overwritten() {
let dir = temp();
let current = dir.join("ironmon").join("config.toml");
let legacy = dir.join("simon").join("config.toml");
fs::create_dir_all(current.parent().unwrap()).unwrap();
fs::create_dir_all(legacy.parent().unwrap()).unwrap();
fs::write(¤t, "current").unwrap();
fs::write(&legacy, "legacy").unwrap();
assert_eq!(adopt(¤t), Adoption::AlreadyPresent);
assert_eq!(fs::read_to_string(¤t).unwrap(), "current");
}
#[test]
fn a_stranded_file_is_adopted_and_the_original_is_left_in_place() {
let dir = temp();
let current = dir.join("ironmon").join("config.toml");
let legacy = dir.join("simon").join("config.toml");
fs::create_dir_all(legacy.parent().unwrap()).unwrap();
fs::write(&legacy, "settings").unwrap();
assert_eq!(adopt(¤t), Adoption::Adopted(legacy.clone()));
assert_eq!(fs::read_to_string(¤t).unwrap(), "settings");
assert!(
legacy.is_file(),
"adoption copies; a move would strand a downgrade"
);
}
#[test]
fn adoption_is_idempotent() {
let dir = temp();
let current = dir.join("ironmon").join("config.toml");
let legacy = dir.join("simon").join("config.toml");
fs::create_dir_all(legacy.parent().unwrap()).unwrap();
fs::write(&legacy, "settings").unwrap();
assert!(matches!(adopt(¤t), Adoption::Adopted(_)));
// The second call must find its own work rather than redo it, because
// this runs on every load.
assert_eq!(adopt(¤t), Adoption::AlreadyPresent);
}
#[test]
fn nothing_to_adopt_is_not_a_failure() {
let dir = temp();
let current = dir.join("ironmon").join("config.toml");
assert_eq!(adopt(¤t), Adoption::Nothing);
assert!(!current.exists(), "adoption must not create an empty file");
}
#[test]
fn a_legacy_directory_is_not_mistaken_for_a_file() {
let dir = temp();
let current = dir.join("ironmon").join("config.toml");
let legacy = dir.join("simon").join("config.toml");
// A *directory* at the legacy path is not a config file.
fs::create_dir_all(&legacy).unwrap();
assert_eq!(adopt(¤t), Adoption::Nothing);
}
#[test]
fn consent_is_reported_and_not_adopted() {
let dir = temp();
let current = dir.join("ironmon").join("consent.toml");
let legacy = dir.join("simon").join("consent.toml");
fs::create_dir_all(legacy.parent().unwrap()).unwrap();
fs::write(&legacy, "granted = true").unwrap();
assert_eq!(legacy_consent_exists(¤t), Some(legacy));
assert!(
!current.exists(),
"a privilege grant made under the old name must be re-asked, \
not silently restored"
);
}
#[test]
fn consent_already_answered_reports_nothing() {
let dir = temp();
let current = dir.join("ironmon").join("consent.toml");
fs::create_dir_all(current.parent().unwrap()).unwrap();
fs::write(¤t, "granted = false").unwrap();
assert_eq!(legacy_consent_exists(¤t), None);
}
}