-
-
Notifications
You must be signed in to change notification settings - Fork 93
Expand file tree
/
Copy pathdarwin.rs
More file actions
251 lines (214 loc) · 7.12 KB
/
darwin.rs
File metadata and controls
251 lines (214 loc) · 7.12 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
use std::{env, path::PathBuf};
use color_eyre::eyre::{Context, bail, eyre};
use tracing::{debug, warn};
use crate::{
Result,
commands,
commands::{Command, ElevationStrategy},
installable::Installable,
interface::{
DarwinArgs,
DarwinRebuildArgs,
DarwinReplArgs,
DarwinSubcommand,
DiffType,
},
nixos::toplevel_for,
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.
///
/// # Errors
///
/// Returns an error if the operation fails.
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 os as root. I will call sudo internally as needed");
}
if self.update_args.update_all || self.update_args.update_input.is_some() {
update(&self.common.installable, self.update_args.update_input)?;
}
let hostname = self.hostname.ok_or(()).or_else(|()| get_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-os").tempdir()?;
(dir.as_ref().join("result"), Some(dir))
};
debug!("Output path: {out_path:?}");
// Use NH_DARWIN_FLAKE if available, otherwise use the provided installable
let installable = if let Ok(darwin_flake) = env::var("NH_DARWIN_FLAKE") {
debug!("Using NH_DARWIN_FLAKE: {}", darwin_flake);
let mut elems = darwin_flake.splitn(2, '#');
let reference = match elems.next() {
Some(r) => r.to_owned(),
None => return Err(eyre!("NH_DARWIN_FLAKE missing reference part")),
};
let attribute = elems
.next()
.map(crate::installable::parse_attribute)
.unwrap_or_default();
Installable::Flake {
reference,
attribute,
}
} else {
self.common.installable.clone()
};
let mut processed_installable = installable;
if let Installable::Flake {
ref mut attribute, ..
} = processed_installable
{
// If user explicitly selects some other attribute, don't push
// darwinConfigurations
if attribute.is_empty() {
attribute.push(String::from("darwinConfigurations"));
attribute.push(hostname.clone());
}
}
let toplevel = toplevel_for(hostname, processed_installable, "toplevel");
commands::Build::new(toplevel)
.extra_arg("--out-link")
.extra_arg(&out_path)
.extra_args(&self.extra_args)
.passthrough(&self.common.passthrough)
.message("Building Darwin configuration")
.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) {
let profile_path = self.profile.as_ref().map_or_else(
|| std::ffi::OsStr::new(SYSTEM_PROFILE),
|p| p.as_os_str(),
);
Command::new("nix")
.args(["build", "--no-link", "--profile"])
.arg(profile_path)
.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(true)
.with_required_env()
.run()
.wrap_err("Darwin activation failed")?;
}
debug!("Completed operation with output path: {out_path:?}");
Ok(())
}
}
impl DarwinReplArgs {
fn run(self) -> Result<()> {
// Use NH_DARWIN_FLAKE if available, otherwise use the provided installable
let mut target_installable =
if let Ok(darwin_flake) = env::var("NH_DARWIN_FLAKE") {
debug!("Using NH_DARWIN_FLAKE: {}", darwin_flake);
let mut elems = darwin_flake.splitn(2, '#');
let reference = match elems.next() {
Some(r) => r.to_owned(),
None => return Err(eyre!("NH_DARWIN_FLAKE missing reference part")),
};
let attribute = elems
.next()
.map(crate::installable::parse_attribute)
.unwrap_or_default();
Installable::Flake {
reference,
attribute,
}
} else {
self.installable
};
if matches!(target_installable, Installable::Store { .. }) {
bail!("Nix doesn't support nix store installables.");
}
let hostname = self.hostname.ok_or(()).or_else(|()| get_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(())
}
}