-
-
Notifications
You must be signed in to change notification settings - Fork 92
Expand file tree
/
Copy pathdarwin.rs
More file actions
331 lines (287 loc) · 9.32 KB
/
darwin.rs
File metadata and controls
331 lines (287 loc) · 9.32 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
use std::{convert::Into, path::PathBuf};
use color_eyre::eyre::{Context, bail};
use tracing::{debug, info, warn};
use crate::{
Result,
commands,
commands::{Command, ElevationStrategy},
installable::{CommandContext, Installable},
interface::{
DarwinArgs,
DarwinRebuildArgs,
DarwinReplArgs,
DarwinSubcommand,
DiffType,
},
remote::{self, RemoteBuildConfig, RemoteHost},
update::update,
util::{get_hostname, print_dix_diff},
};
const SYSTEM_PROFILE: &str = "/nix/var/nix/profiles/system";
const CURRENT_PROFILE: &str = "/run/current-system";
impl DarwinArgs {
/// Run the `darwin` subcommand.
///
/// # Parameters
///
/// * `self` - The Darwin operation arguments
/// * `elevation` - The privilege elevation strategy (sudo/doas/none)
///
/// # Returns
///
/// Returns `Ok(())` if the operation succeeds.
///
/// # Errors
///
/// Returns an error if:
///
/// - Build or activation operations fail
/// - Remote operations encounter network or SSH issues
/// - Nix evaluation or building fails
/// - File system operations fail
pub fn run(self, elevation: ElevationStrategy) -> Result<()> {
use DarwinRebuildVariant::{Build, Switch};
match self.subcommand {
DarwinSubcommand::Switch(args) => args.rebuild(&Switch, elevation),
DarwinSubcommand::Build(args) => {
if args.common.ask || args.common.dry {
warn!("`--ask` and `--dry` have no effect for `nh darwin build`");
}
args.rebuild(&Build, elevation)
},
DarwinSubcommand::Repl(args) => args.run(),
}
}
}
enum DarwinRebuildVariant {
Switch,
Build,
}
impl DarwinRebuildArgs {
fn rebuild(
self,
variant: &DarwinRebuildVariant,
elevation: ElevationStrategy,
) -> Result<()> {
use DarwinRebuildVariant::{Build, Switch};
if nix::unistd::Uid::effective().is_root() && !self.bypass_root_check {
bail!(
"Don't run nh darwin as root. I will call sudo internally as needed"
);
}
let hostname = get_hostname(self.hostname)?;
let (out_path, _tempdir_guard): (PathBuf, Option<tempfile::TempDir>) =
if let Some(ref p) = self.common.out_link {
(p.clone(), None)
} else {
let dir = tempfile::Builder::new().prefix("nh-darwin").tempdir()?;
(dir.as_ref().join("result"), Some(dir))
};
debug!("Output path: {out_path:?}");
let installable = self
.common
.installable
.clone()
.resolve(CommandContext::Darwin)?;
let installable = match installable {
Installable::Unspecified => Installable::try_find_default_for_darwin()?,
other => other,
};
if self.update_args.update_all || self.update_args.update_input.is_some() {
update(
&installable,
self.update_args.update_input,
self.common.passthrough.commit_lock_file,
)?;
}
let toplevel = toplevel_for(hostname, installable, "toplevel")?;
info!("Building Darwin configuration");
// If a build host is specified, use remote build semantics
if let Some(ref build_host_str) = self.build_host {
let build_host = RemoteHost::parse(build_host_str)
.wrap_err("Invalid build host specification")?;
let config = RemoteBuildConfig {
build_host,
target_host: None,
use_nom: !self.common.no_nom,
use_substitutes: self.common.passthrough.use_substitutes,
extra_args: self
.extra_args
.iter()
.map(Into::into)
.chain(
self
.common
.passthrough
.generate_passthrough_args()
.into_iter()
.map(Into::into),
)
.collect(),
};
// Initialize SSH control - guard will cleanup connections on drop
let _ssh_guard = remote::init_ssh_control();
remote::build_remote(&toplevel, &config, Some(&out_path))
.wrap_err("Failed to build Darwin configuration")?;
} else {
commands::Build::new(toplevel)
.extra_arg("--out-link")
.extra_arg(&out_path)
.extra_args(&self.extra_args)
.passthrough(&self.common.passthrough)
.nom(!self.common.no_nom)
.run()
.wrap_err("Failed to build Darwin configuration")?;
}
let target_profile = out_path.clone();
target_profile.try_exists().context("Doesn't exist")?;
debug!(
"Comparing with target profile: {}",
target_profile.display()
);
// Compare changes between current and target generation
if matches!(self.common.diff, DiffType::Never) {
debug!("Not running dix as the --diff flag is set to never.");
} else {
debug!(
"Comparing with target profile: {}",
target_profile.display()
);
let _ = print_dix_diff(&PathBuf::from(CURRENT_PROFILE), &target_profile);
}
if self.common.ask && !self.common.dry && !matches!(variant, Build) {
let confirmation = inquire::Confirm::new("Apply the config?")
.with_default(false)
.prompt()?;
if !confirmation {
bail!("User rejected the new config");
}
}
if matches!(variant, Switch) {
Command::new("nix")
.args(["build", "--no-link", "--profile", SYSTEM_PROFILE])
.arg(&out_path)
.elevate(Some(elevation.clone()))
.dry(self.common.dry)
.with_required_env()
.run()
.wrap_err("Failed to set Darwin system profile")?;
let darwin_rebuild = out_path.join("sw/bin/darwin-rebuild");
let activate_user = out_path.join("activate-user");
// Determine if we need to elevate privileges
let needs_elevation = !activate_user
.try_exists()
.context("Failed to check if activate-user file exists")?
|| std::fs::read_to_string(&activate_user)
.context("Failed to read activate-user file")?
.contains("# nix-darwin: deprecated");
// Create and run the activation command with or without elevation
Command::new(darwin_rebuild)
.arg("activate")
.message("Activating configuration")
.elevate(needs_elevation.then_some(elevation))
.dry(self.common.dry)
.show_output(self.show_activation_logs)
.with_required_env()
.run()
.wrap_err("Darwin activation failed")?;
}
debug!("Completed operation with output path: {out_path:?}");
Ok(())
}
}
impl DarwinReplArgs {
fn run(self) -> Result<()> {
let target_installable =
self.installable.resolve(CommandContext::Darwin)?;
let mut target_installable = match target_installable {
Installable::Unspecified => Installable::try_find_default_for_darwin()?,
other => other,
};
if matches!(target_installable, Installable::Store { .. }) {
bail!("Nix doesn't support nix store installables.");
}
let hostname = get_hostname(self.hostname)?;
if let Installable::Flake {
ref mut attribute, ..
} = target_installable
{
if attribute.is_empty() {
attribute.push(String::from("darwinConfigurations"));
attribute.push(hostname);
}
}
Command::new("nix")
.arg("repl")
.args(target_installable.to_args())
.with_required_env()
.show_output(true)
.run()?;
Ok(())
}
}
pub fn toplevel_for<S: AsRef<str>>(
hostname: S,
installable: Installable,
final_attr: &str,
) -> Result<Installable> {
let mut res = installable;
let hostname_str = hostname.as_ref();
let toplevel = ["config", "system", "build", final_attr]
.into_iter()
.map(String::from);
match res {
Installable::Flake {
ref mut attribute, ..
} => {
if attribute.is_empty() {
attribute.push(String::from("darwinConfigurations"));
attribute.push(hostname_str.to_owned());
} else if attribute.len() == 1 && attribute[0] == "darwinConfigurations" {
info!("Inferring hostname '{hostname_str}' for darwinConfigurations");
attribute.push(hostname_str.to_owned());
} else if attribute[0] == "darwinConfigurations" {
if attribute.len() == 2 {
// darwinConfigurations.hostname - fine
} else if attribute.len() > 2 {
if attribute[2] == "config" {
bail!(
"Attribute path is too specific: {}. Please either:\n 1. Use \
the flake reference without attributes (e.g., '.')\n 2. \
Specify only the configuration name (e.g., '.#{}')",
attribute.join("."),
attribute[1]
);
} else {
bail!(
"Unexpected attribute path: {}. Please specify only the \
configuration name (e.g., '.#{}')",
attribute.join("."),
attribute[1]
);
}
}
} else {
// User provided ".#myhost" - prepend darwinConfigurations
attribute.insert(0, String::from("darwinConfigurations"));
}
attribute.extend(toplevel);
},
Installable::File {
ref mut attribute, ..
}
| Installable::Expression {
ref mut attribute, ..
} => attribute.extend(toplevel),
Installable::Store { .. } => {
bail!("Nix doesn't support nix store installables.");
},
Installable::Unspecified => {
unreachable!(
"Unspecified installable should have been resolved before calling \
toplevel_for"
)
},
}
Ok(res)
}