-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathhistory.rs
More file actions
287 lines (252 loc) · 9.05 KB
/
Copy pathhistory.rs
File metadata and controls
287 lines (252 loc) · 9.05 KB
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
use chrono::{DateTime, Utc};
use color_eyre::eyre::{Context, Result, eyre};
use log::{debug, warn};
use serde::{Deserialize, Serialize};
use std::{
cmp::Ordering,
collections::HashMap,
fs::{self, File},
path::PathBuf,
sync::atomic::AtomicUsize,
};
use crate::launch::Behavior;
/// The maximum number of entries to keep in the history
// This is an arbitrary number, but it should be enough to keep the history manageable
const MAX_HISTORY_ENTRIES: usize = 35;
/// An entry in the history
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Entry {
/// The name of the workspace
pub workspace_name: String,
/// The name of the dev container, if it exists
pub dev_container_name: Option<String>,
/// The name of the external config used, if any
#[serde(default)]
pub config_name: Option<String>,
/// The path to the vscode workspace
pub workspace_path: PathBuf,
/// The remote SSH host alias, if the workspace was opened remotely.
#[serde(default)]
pub remote_host: Option<String>,
/// The path to the dev container config, if it exists
pub config_path: Option<PathBuf>,
/// The launch behavior
pub behavior: Behavior,
/// The time this entry was last opened
pub last_opened: DateTime<Utc>, // not used in PartialEq, Eq, Hash
}
// Custom comparison which ignores `last_opened` (and `name`)
// This is used so that we don't add duplicate entries with different timestamps
impl PartialEq for Entry {
fn eq(&self, other: &Self) -> bool {
self.workspace_path == other.workspace_path
&& self.remote_host == other.remote_host
&& self.config_path == other.config_path
&& self.behavior == other.behavior
}
}
impl Eq for Entry {}
// Required by BTreeSet since it's sorted
impl Ord for Entry {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
// check if two are equal by comparing all properties, ignoring `last_opened` (calling custom `.eq()`)
if self.eq(other) {
return Ordering::Equal;
}
// If they are not equal, the ordering is given by `last_opened`
self.last_opened.cmp(&other.last_opened)
}
}
// Same as `Ord`
impl PartialOrd for Entry {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct EntryId(usize);
impl EntryId {
pub fn new() -> Self {
static GLOBAL_ID: AtomicUsize = AtomicUsize::new(0);
Self(GLOBAL_ID.fetch_add(1, std::sync::atomic::Ordering::SeqCst))
}
}
/// Contains the recent used workspaces
///
/// # Note
/// We use a `BTreeSet` so it's sorted and does not contain duplicates
#[derive(Default, Debug, Clone)]
pub struct History(HashMap<EntryId, Entry>);
impl History {
pub fn from_entries(entries: Vec<Entry>) -> Self {
Self(
entries
.into_iter()
.map(|entry| (EntryId::new(), entry))
.collect(),
)
}
pub fn insert(&mut self, entry: Entry) -> EntryId {
let id = EntryId::new();
assert_eq!(self.0.insert(id, entry), None);
id
}
pub fn update(&mut self, id: EntryId, entry: Entry) -> Option<Entry> {
if let std::collections::hash_map::Entry::Occupied(mut e) = self.0.entry(id) {
return Some(e.insert(entry));
}
None
}
pub fn delete(&mut self, id: EntryId) -> Option<Entry> {
self.0.remove(&id)
}
pub fn upsert(&mut self, entry: Entry) -> EntryId {
if let Some(id) = self
.0
.iter_mut()
.find_map(|(id, history_entry)| (history_entry == &entry).then_some(*id))
{
assert!(
self.update(id, entry).is_some(),
"Existing history entry to be replaced"
);
id
} else {
self.insert(entry)
}
}
pub fn iter(&self) -> std::collections::hash_map::Iter<'_, EntryId, Entry> {
self.0.iter()
}
pub fn into_entries(self) -> Vec<Entry> {
self.0.into_values().collect()
}
}
/// Manages the history and tracks the recently used workspaces
pub struct Tracker {
/// The path to the history file
path: PathBuf,
/// The history struct
pub history: History,
}
impl Tracker {
/// Loads the history from a file
pub fn load<P: Into<PathBuf>>(path: P) -> Result<Self> {
// Code size optimization: With rusts monomorphization it would generate
// a "new/separate" function for each generic argument used to call this function.
// Having this inner function does not prevent it but can drastically cuts down on generated code size.
fn load_inner(path: PathBuf) -> Result<Tracker> {
if !path.exists() {
// cap of 1, because in the application lifetime, we only ever add one element before exiting
return Ok(Tracker {
path,
history: History::default(),
});
}
let file = File::open(&path)?;
match serde_json::from_reader::<_, Vec<Entry>>(file) {
Ok(entries) => {
debug!("Imported {:?} history entries", entries.len());
Ok(Tracker {
path,
history: History::from_entries(entries),
})
}
Err(err) => {
// ignore parsing errors
// move the file and start from scratch
// find a non-existent backup file
let new_path = (0..10_000) // Set an upper limit of filename checks.
.map(|i| path.with_file_name(format!(".history_{i}.json.bak")))
.find(|path| !path.exists())
.unwrap_or_else(|| path.with_file_name(".history.json.bak"));
fs::rename(&path, &new_path).wrap_err_with(|| {
format!(
"Could not move history file from `{}` to `{}`",
path.display(),
new_path.display()
)
})?;
warn!(
"Could not read history file: {err}\nMoved broken file to `{}`",
new_path.display()
);
Ok(Tracker {
path,
history: History::default(),
})
}
}
}
let path = path.into();
load_inner(path)
}
/// Saves the history, guaranteeing a size of `MAX_HISTORY_ENTRIES`
pub fn store(self) -> Result<()> {
fs::create_dir_all(
self.path
.parent()
.ok_or_else(|| eyre!("Parent directory not found"))?,
)?;
let file = File::create(self.path)?;
// since history is sorted, we can remove the first entries to limit the max size
let entries: Vec<Entry> = self
.history
.into_entries()
.into_iter()
.take(MAX_HISTORY_ENTRIES)
.collect();
serde_json::to_writer_pretty(file, &entries)?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::{Entry, History, Tracker};
use crate::launch::{Behavior, ContainerStrategy};
use chrono::Utc;
use std::ffi::OsString;
use std::path::PathBuf;
fn unique_test_path(name: &str) -> PathBuf {
let unique = format!(
"vscli-history-{name}-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
);
std::env::temp_dir().join(unique).join("history.json")
}
#[test]
fn tracker_store_and_load_preserve_remote_host_entries() {
let path = unique_test_path("remote-host");
let mut tracker = Tracker {
path: path.clone(),
history: History::default(),
};
tracker.history.upsert(Entry {
workspace_name: "workspace".to_string(),
dev_container_name: None,
config_name: None,
workspace_path: PathBuf::from("/home/dev/workspace"),
remote_host: Some("vscli-remote-test".to_string()),
config_path: None,
behavior: Behavior {
strategy: ContainerStrategy::ForceClassic,
args: vec![OsString::from("--reuse-window")],
command: "code".to_string(),
},
last_opened: Utc::now(),
});
tracker.store().unwrap();
let loaded = Tracker::load(path).unwrap();
let entries = loaded.history.into_entries();
assert_eq!(entries.len(), 1);
assert_eq!(entries[0].remote_host.as_deref(), Some("vscli-remote-test"));
assert_eq!(
entries[0].behavior.strategy,
ContainerStrategy::ForceClassic
);
}
}