Repository navigation
Expand file tree
/
Copy pathdirs.rs
More file actions
475 lines (449 loc) · 16.1 KB
/
Copy pathdirs.rs
File metadata and controls
475 lines (449 loc) · 16.1 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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
//! `minimal dirs` — print the important directories and files a user
//! might want to inspect when debugging.
use std::path::PathBuf;
use crate::GlobalArgs;
use crate::config::resolve_minimal_config_dir;
#[cfg(feature = "remote-access")]
use crate::mesh_enrolment_path;
/// Print the important directories and files a user might want to
/// inspect when debugging. Grouped by role (config / state / cache)
/// with an "exists?" marker so unused paths don't look identical to
/// misconfigured ones.
pub fn cmd_dirs(global: &GlobalArgs) -> Result<(), anyhow::Error> {
print!("{}", report(global));
Ok(())
}
/// The `cmd_dirs` table as a string — also captured verbatim into `min bug`
/// diagnostic bundles as `host/dirs.txt`.
pub(crate) fn report(global: &GlobalArgs) -> String {
let dirs = DirsLookup {
config: resolve_minimal_config_dir(global),
#[cfg(feature = "remote-access")]
mesh_enrolment: mesh_enrolment_path(global),
// `mesh_enrolment_path` follows `--minimal-dir` when set,
// so the row groups with State in that case rather than
// Config — otherwise a user reading `minimal dirs` would
// find the mesh file under the wrong header.
#[cfg(feature = "remote-access")]
mesh_group: if global.minimal_dir.is_some() {
MeshGroup::State
} else {
MeshGroup::Config
},
state: match &global.minimal_dir {
Some(dir) => dir.clone(),
None => paths::minimal_state_dir()
.as_utf8_path()
.as_std_path()
.to_path_buf(),
},
cache: paths::minimal_cache_dir()
.as_utf8_path()
.as_std_path()
.to_path_buf(),
host_kind: crate::client::client_host_kind(global.use_minvmd()),
};
format_dir_rows(&build_dir_rows(&dirs))
}
/// Resolved locations `cmd_dirs` prints, materialized once so
/// [`build_dir_rows`] stays a pure function of its inputs (easy to
/// snapshot-test without touching env or the filesystem).
struct DirsLookup {
/// `<config>/minimal` — root for `config.toml`, `loadouts/`,
/// mTLS certs.
config: PathBuf,
/// The specific path `min mesh join` writes to. Kept separate
/// so a `--minimal-dir` override that redirects the mesh file
/// (but not the loadouts subsystem) still shows up correctly.
#[cfg(feature = "remote-access")]
mesh_enrolment: PathBuf,
/// Which group heading the mesh row prints under —
/// `Config` in the common case, `State` when
/// `--minimal-dir` redirected the mesh file to the state tree.
#[cfg(feature = "remote-access")]
mesh_group: MeshGroup,
/// `<state>/minimal` (or the `--minimal-dir` override).
state: PathBuf,
/// `<cache>/minimal`.
cache: PathBuf,
/// The backend whose host dir the CLI would connect to, so the SSH
/// socket row names the right `providers/local-<kind>0` path.
host_kind: paths::HostKind,
}
/// Which top-level group the mesh-enrolment row prints under. Values
/// match the row group labels one-to-one via [`Self::as_row_group`].
#[cfg(feature = "remote-access")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum MeshGroup {
Config,
State,
}
#[cfg(feature = "remote-access")]
impl MeshGroup {
/// Group label used in [`DirRow::group`] and printed as the
/// column header. Kept as a method (not `Display`) so the mapping
/// is grep-friendly and callers can't accidentally pass an
/// unrelated `&str`.
fn as_row_group(self) -> &'static str {
match self {
Self::Config => "Config",
Self::State => "State",
}
}
}
/// Build the `cmd_dirs` row list from a resolved [`DirsLookup`].
/// Pure function of its input — no env reads, no filesystem stat
/// calls beyond what [`DirRow::existence_marker`] does at print
/// time.
fn build_dir_rows(dirs: &DirsLookup) -> Vec<DirRow> {
#[cfg(feature = "remote-access")]
let mesh_row = || {
(
dirs.mesh_group.as_row_group(),
"Mesh enrolment",
Some(dirs.mesh_enrolment.clone()),
None,
)
.into_row()
};
let mut rows = vec![
("Config", "Config dir", Some(dirs.config.clone()), None).into_row(),
(
"Config",
"config.toml",
Some(dirs.config.join("config.toml")),
None,
)
.into_row(),
(
"Config",
"Loadouts dir",
Some(dirs.config.join("loadouts")),
None,
)
.into_row(),
];
#[cfg(feature = "remote-access")]
if dirs.mesh_group == MeshGroup::Config {
rows.push(mesh_row());
}
rows.extend([("State", "State dir", Some(dirs.state.clone()), None).into_row()]);
// The session store lives inside the VM on minvmd-backed hosts, so the
// host sessions path is never created there; show the in-VM note instead.
rows.push(match dirs.host_kind {
paths::HostKind::Minvmd => (
"State",
"Sessions",
None,
Some("inside the VM; not on this host".to_string()),
)
.into_row(),
paths::HostKind::Minimald => {
("State", "Sessions", Some(dirs.state.join("sessions")), None).into_row()
}
});
rows.extend([
(
"State",
"Daemon logs",
Some(dirs.state.join("logs")),
Some("daily-rotated: minimald.log*, minvmd.log*".to_string()),
)
.into_row(),
(
"State",
"SSH socket",
Some(dirs.state.join(format!(
"providers/{}/ssh.sock",
paths::host_name(dirs.host_kind, 0)
))),
None,
)
.into_row(),
]);
#[cfg(feature = "remote-access")]
if dirs.mesh_group == MeshGroup::State {
// After the SSH-socket row so the mesh file lands at the
// tail of the State group — visually adjacent to the state
// dir root it lives under.
rows.push(mesh_row());
}
rows.extend([
("Cache", "Cache dir", Some(dirs.cache.clone()), None).into_row(),
(
"Cache",
"Built artifacts",
Some(dirs.cache.join("built")),
None,
)
.into_row(),
]);
rows
}
/// Format the row list produced by [`build_dir_rows`] with per-column
/// width-alignment and a blank line between groups.
fn format_dir_rows(rows: &[DirRow]) -> String {
use std::fmt::Write as _;
let group_w = rows.iter().map(|r| r.group.len()).max().unwrap_or(6);
let name_w = rows.iter().map(|r| r.name.len()).max().unwrap_or(4).max(4);
let path_w = rows
.iter()
.map(|r| r.path_display().len())
.max()
.unwrap_or(4);
let mut out = String::new();
let _ = writeln!(
out,
"{group:<group_w$} {name:<name_w$} {path:<path_w$}",
group = "GROUP",
name = "NAME",
path = "PATH",
);
let mut current_group = "";
for row in rows {
if row.group != current_group {
if !current_group.is_empty() {
out.push('\n');
}
current_group = row.group;
}
let mark = row.existence_marker();
let path = row.path_display();
let note = row
.note
.as_deref()
.map(|n| format!(" ({n})"))
.unwrap_or_default();
let _ = writeln!(
out,
"{group:<group_w$} {mark} {name:<name_w$} {path:<path_w$}{note}",
group = row.group,
name = row.name,
);
}
out.push('\n');
out.push_str(" * = exists - = missing ? = unknown (path unresolved)\n");
out
}
/// One row emitted by [`cmd_dirs`]. Kept as a struct rather than
/// a tuple so the group / mark / path / note columns can be widened
/// independently at print time.
struct DirRow {
group: &'static str,
name: &'static str,
path: Option<PathBuf>,
note: Option<String>,
}
impl DirRow {
fn path_display(&self) -> String {
match &self.path {
Some(p) => p.display().to_string(),
None => "<unresolved>".to_string(),
}
}
fn existence_marker(&self) -> char {
match &self.path {
None => '?',
Some(p) if p.exists() => '*',
Some(_) => '-',
}
}
}
trait IntoDirRow {
fn into_row(self) -> DirRow;
}
impl IntoDirRow for (&'static str, &'static str, Option<PathBuf>, Option<String>) {
fn into_row(self) -> DirRow {
DirRow {
group: self.0,
name: self.1,
path: self.2,
note: self.3,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// `build_dir_rows` produces the fixed layout [Config, State × 4,
/// Cache × 2] — plus a "Mesh enrolment" row under Config (the
/// common case) only when the `remote-access` feature is compiled
/// in — each with the right group tag, name, and derived path.
/// Guards against a future edit that drops a row or shuffles
/// groups without noticing.
#[test]
fn build_dir_rows_layout_is_stable() {
let dirs = DirsLookup {
config: PathBuf::from("/home/u/.config/minimal"),
#[cfg(feature = "remote-access")]
mesh_enrolment: PathBuf::from("/home/u/.config/minimal/mesh-enrolment"),
#[cfg(feature = "remote-access")]
mesh_group: MeshGroup::Config,
state: PathBuf::from("/home/u/.local/state/minimal"),
cache: PathBuf::from("/home/u/.cache/minimal"),
host_kind: paths::HostKind::Minimald,
};
let rows = build_dir_rows(&dirs);
let shape: Vec<(&str, &str, String)> = rows
.iter()
.map(|r| (r.group, r.name, r.path_display()))
.collect();
#[allow(unused_mut)]
let mut expected = vec![
(
"Config",
"Config dir",
"/home/u/.config/minimal".to_string(),
),
(
"Config",
"config.toml",
"/home/u/.config/minimal/config.toml".to_string(),
),
(
"Config",
"Loadouts dir",
"/home/u/.config/minimal/loadouts".to_string(),
),
(
"State",
"State dir",
"/home/u/.local/state/minimal".to_string(),
),
(
"State",
"Sessions",
"/home/u/.local/state/minimal/sessions".to_string(),
),
(
"State",
"Daemon logs",
"/home/u/.local/state/minimal/logs".to_string(),
),
(
"State",
"SSH socket",
"/home/u/.local/state/minimal/providers/local-minimald0/ssh.sock".to_string(),
),
("Cache", "Cache dir", "/home/u/.cache/minimal".to_string()),
(
"Cache",
"Built artifacts",
"/home/u/.cache/minimal/built".to_string(),
),
];
// Mesh enrolment prints under Config, right after "Loadouts
// dir", only in `remote-access` builds where `min mesh` exists.
#[cfg(feature = "remote-access")]
expected.insert(
3,
(
"Config",
"Mesh enrolment",
"/home/u/.config/minimal/mesh-enrolment".to_string(),
),
);
assert_eq!(shape, expected);
}
/// The "Daemon logs" row's note names both daemons' rotated files so
/// operators know which filenames to look at.
#[test]
fn build_dir_rows_daemon_logs_note_names_both_daemons() {
let dirs = DirsLookup {
config: PathBuf::from("/c"),
#[cfg(feature = "remote-access")]
mesh_enrolment: PathBuf::from("/c/mesh-enrolment"),
#[cfg(feature = "remote-access")]
mesh_group: MeshGroup::Config,
state: PathBuf::from("/s"),
cache: PathBuf::from("/x"),
host_kind: paths::HostKind::Minimald,
};
let rows = build_dir_rows(&dirs);
let daemon_logs = rows.iter().find(|r| r.name == "Daemon logs").unwrap();
assert_eq!(
daemon_logs.note.as_deref(),
Some("daily-rotated: minimald.log*, minvmd.log*"),
);
}
/// On a minvmd-backed host the session store lives inside the VM, so the
/// Sessions row must carry no host path and the in-VM note; the native
/// minimald keeps the host sessions path.
#[test]
fn build_dir_rows_sessions_row_depends_on_host_kind() {
let native = DirsLookup {
config: PathBuf::from("/c"),
#[cfg(feature = "remote-access")]
mesh_enrolment: PathBuf::from("/c/mesh-enrolment"),
#[cfg(feature = "remote-access")]
mesh_group: MeshGroup::Config,
state: PathBuf::from("/s"),
cache: PathBuf::from("/x"),
host_kind: paths::HostKind::Minimald,
};
let native_sessions = build_dir_rows(&native)
.into_iter()
.find(|r| r.name == "Sessions")
.unwrap();
assert_eq!(native_sessions.path_display(), "/s/sessions");
assert_eq!(native_sessions.note, None);
let vm = DirsLookup {
config: PathBuf::from("/c"),
#[cfg(feature = "remote-access")]
mesh_enrolment: PathBuf::from("/c/mesh-enrolment"),
#[cfg(feature = "remote-access")]
mesh_group: MeshGroup::Config,
state: PathBuf::from("/s"),
cache: PathBuf::from("/x"),
host_kind: paths::HostKind::Minvmd,
};
let vm_sessions = build_dir_rows(&vm)
.into_iter()
.find(|r| r.name == "Sessions")
.unwrap();
assert_eq!(vm_sessions.path, None);
assert_eq!(
vm_sessions.note.as_deref(),
Some("inside the VM; not on this host"),
);
}
/// `DirRow::existence_marker` returns `?` when path is `None`,
/// `-` for a resolved-but-missing file, `*` for one that exists.
#[test]
fn dir_row_existence_marker_covers_all_three_states() {
let tmp = tempfile::tempdir().unwrap();
let real = tmp.path().join("here");
std::fs::write(&real, "x").unwrap();
let missing = tmp.path().join("gone");
let row_present = ("_", "_", Some(real), None).into_row();
let row_missing = ("_", "_", Some(missing), None).into_row();
let row_unresolved = ("_", "_", None, None).into_row();
assert_eq!(row_present.existence_marker(), '*');
assert_eq!(row_missing.existence_marker(), '-');
assert_eq!(row_unresolved.existence_marker(), '?');
}
/// When `--minimal-dir` redirects the mesh file to the state
/// tree, the Mesh row must render under the State group so the
/// output stays semantically honest. Guards the `mesh_group`
/// branching added to `build_dir_rows`.
#[cfg(feature = "remote-access")]
#[test]
fn build_dir_rows_places_mesh_under_state_when_minimal_dir_overrides() {
let dirs = DirsLookup {
config: PathBuf::from("/c"),
mesh_enrolment: PathBuf::from("/override/mesh-enrolment"),
mesh_group: MeshGroup::State,
state: PathBuf::from("/override"),
cache: PathBuf::from("/x"),
host_kind: paths::HostKind::Minimald,
};
let rows = build_dir_rows(&dirs);
let mesh = rows.iter().find(|r| r.name == "Mesh enrolment").unwrap();
assert_eq!(mesh.group, "State");
assert_eq!(mesh.path_display(), "/override/mesh-enrolment");
// And there must be no "Mesh enrolment" row under Config
// (bug: the row was duplicated when we introduced the flag).
let mesh_count = rows.iter().filter(|r| r.name == "Mesh enrolment").count();
assert_eq!(mesh_count, 1, "mesh row must appear exactly once");
}
}