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
//! The `zoi alt` command: inspecting and choosing alternative implementations.
//!
//! `awk`, `vi` and `editor` each have several interchangeable implementations,
//! and the system still has to put *something* at the canonical path. This
//! command is how an administrator sees what is registered and changes which
//! one is current, without reinstalling anything.
//!
//! See `crates/core/src/alternatives.rs` for the mechanism and the layout.
use anyhow::{Result, bail};
use colored::Colorize;
use comfy_table::Table;
use comfy_table::presets::UTF8_FULL;
use zoi_core::alternatives::{self, AlternativeStatus};
use crate::cli::AltCommand;
/// Runs the `alt` subcommand.
///
/// The argument is the clap-generated enum rather than a hand-rolled one, so
/// `zoi alt --help` and the shell completions stay in step with the
/// implementation automatically.
///
/// # Errors
///
/// Returns an error if the named alternative does not exist, if `set` names a
/// path that is not registered for it, or if the registry state cannot be read
/// or written. Every failure is reported without touching the current
/// selection, because group state is written to a temporary file and renamed.
pub fn run(args: &AltCommand) -> Result<()> {
match args {
AltCommand::List { verbose } => list(*verbose),
AltCommand::Get { name } => get(name),
AltCommand::Set { name, path } => set(name, path),
AltCommand::Auto { name } => auto(name),
AltCommand::Remove { name, path } => remove(name, path)
}
}
/// Prints every registered alternative group.
fn list(verbose: bool) -> Result<()> {
let statuses = alternatives::status()?;
if statuses.is_empty() {
println!(
"No alternatives are registered. A package registers one by \
declaring an 'alternatives' block in its .pkg.lua."
);
return Ok(());
}
if !verbose {
let mut table = Table::new();
table.load_style(UTF8_FULL);
table.set_header(vec![
"Name",
"Link",
"Current",
"Source",
"Registered",
]);
for status in &statuses {
let current = status.current.clone().unwrap_or_else(|| "-".into());
table.add_row(vec![
status.name.clone(),
status.link.clone(),
current,
if status.manual { "manual" } else { "auto" }.to_string(),
status
.alternatives
.iter()
.map(|a| format!("{} ({})", a.path, a.priority))
.collect::<Vec<_>>()
.join("\n"),
]);
}
println!("{table}");
return Ok(());
}
// Verbose output groups by name so every candidate and its owner is
// legible.
for status in &statuses {
print_group(status);
}
Ok(())
}
/// Prints one group in full.
fn print_group(status: &AlternativeStatus) {
println!("{} -> {}", status.name.bold(), status.link);
let current = status.current.clone().unwrap_or_else(|| "-".into());
let mut table = Table::new();
table.load_style(UTF8_FULL);
table.set_header(vec!["Priority", "Path", "Package", "Current"]);
// Highest priority first, so the listing reads in the order a reader cares
// about rather than in registration order.
let mut sorted = status.alternatives.clone();
sorted.sort_by_key(|a| std::cmp::Reverse(a.priority));
for alternative in sorted {
let is_current = Some(&alternative.path) == status.current.as_ref();
table.add_row(vec![
alternative.priority.to_string(),
alternative.path.clone(),
alternative.package.clone(),
if is_current {
"*".to_string()
} else {
String::new()
},
]);
}
println!("{table}");
println!(
" selected: {} ({})\n",
current,
if status.manual {
"manual"
} else {
"highest priority"
}
);
}
/// Shows one group.
fn get(name: &str) -> Result<()> {
let Some(group) = alternatives::get(name)? else {
bail!("No such alternative: '{name}'. Run 'zoi alt list' to see them.");
};
print_group(&group.status());
Ok(())
}
/// Manually selects an implementation.
fn set(name: &str, path: &str) -> Result<()> {
alternatives::set(name, path)?;
let group = alternatives::get(name)?
.ok_or_else(|| anyhow::anyhow!("Alternative '{name}' disappeared"))?;
println!(
"{} '{}' now points to {}",
"Updated".green().bold(),
group.link,
path.bold()
);
Ok(())
}
/// Returns to priority-based selection.
fn auto(name: &str) -> Result<()> {
if let Some(selected) = alternatives::auto(name)? {
println!(
"{} '{}' now points to {} (highest priority)",
"Updated".green().bold(),
name,
selected.bold()
);
Ok(())
} else {
println!("Alternative '{name}' has no registered implementations.");
Ok(())
}
}
/// Removes one implementation from a group.
fn remove(name: &str, path: &str) -> Result<()> {
alternatives::remove_implementation(name, path)?;
println!(
"{} '{path}' from alternative '{name}'",
"Removed".green().bold()
);
// Report what is now current, so the user is not left guessing.
if let Some(group) = alternatives::get(name)?
&& let Some(current) = group.current()
{
println!("{} now points to {}", name, current.path.as_str().bold());
}
Ok(())
}
/// Announces alternative changes after a transaction.
///
/// Called from the install, update and uninstall paths. Kept here rather than
/// inlined at each call site so the wording stays consistent, and quiet when
/// nothing changed, because most transactions touch no alternatives at all.
pub fn announce_changes(changed: &[String]) {
if changed.is_empty() {
return;
}
for name in changed {
match alternatives::get(name) {
Ok(Some(group)) => match group.current() {
Some(current) => println!(
"{} alternative '{}' -> {}",
"::".blue().bold(),
name,
current.path.as_str().bold()
),
None => println!(
"{} alternative '{}' has no implementations",
"::".blue().bold(),
name
)
},
Ok(None) => {
println!("{} alternative '{name}' removed", "::".blue().bold());
}
// Reporting must never fail a transaction that already succeeded.
Err(_) => {}
}
}
}