-
-
Notifications
You must be signed in to change notification settings - Fork 92
Expand file tree
/
Copy pathhome.rs
More file actions
256 lines (216 loc) · 7.62 KB
/
home.rs
File metadata and controls
256 lines (216 loc) · 7.62 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
use std::env;
use std::path::PathBuf;
use color_eyre::eyre::bail;
use color_eyre::Result;
use tracing::{debug, info};
use crate::commands;
use crate::commands::Command;
use crate::installable::Installable;
use crate::interface::{self, HomeRebuildArgs, HomeReplArgs, HomeSubcommand};
use crate::update::update;
impl interface::HomeArgs {
pub fn run(self) -> Result<()> {
use HomeRebuildVariant::*;
match self.subcommand {
HomeSubcommand::Switch(args) => args.rebuild(Switch),
HomeSubcommand::Build(args) => args.rebuild(Build),
HomeSubcommand::Repl(args) => args.run(),
}
}
}
#[derive(Debug)]
enum HomeRebuildVariant {
Build,
Switch,
}
impl HomeRebuildArgs {
fn rebuild(self, variant: HomeRebuildVariant) -> Result<()> {
use HomeRebuildVariant::*;
if self.update_args.update {
update(&self.common.installable, self.update_args.update_input)?;
}
let out_path: Box<dyn crate::util::MaybeTempPath> = match self.common.out_link {
Some(ref p) => Box::new(p.clone()),
None => Box::new({
let dir = tempfile::Builder::new().prefix("nh-os").tempdir()?;
(dir.as_ref().join("result"), dir)
}),
};
debug!(?out_path);
let toplevel = toplevel_for(self.common.installable.clone(), true, &self.extra_args)?;
commands::Build::new(toplevel)
.extra_arg("--out-link")
.extra_arg(out_path.get_path())
.extra_args(&self.extra_args)
.message("Building Home-Manager configuration")
.nom(!self.common.no_nom)
.run()?;
let prev_generation: Option<PathBuf> = [
PathBuf::from("/nix/var/nix/profiles/per-user")
.join(env::var("USER").expect("Couldn't get username"))
.join("home-manager"),
PathBuf::from(env::var("HOME").expect("Couldn't get home directory"))
.join(".local/state/nix/profiles/home-manager"),
]
.into_iter()
.take_while(|next| next.exists())
.next();
debug!(?prev_generation);
let spec_location =
PathBuf::from(std::env::var("HOME")?).join(".local/share/home-manager/specialisation");
let current_specialisation = std::fs::read_to_string(spec_location.to_str().unwrap()).ok();
let target_specialisation = if self.no_specialisation {
None
} else {
current_specialisation.or(self.specialisation)
};
debug!("target_specialisation: {target_specialisation:?}");
let target_profile = match &target_specialisation {
None => out_path,
Some(spec) => Box::new(out_path.get_path().join("specialisation").join(spec)),
};
// just do nothing for None case (fresh installs)
if let Some(generation) = prev_generation {
Command::new("nvd")
.arg("diff")
.arg(generation)
.arg(target_profile.get_path())
.message("Comparing changes")
.run()?;
}
if self.common.dry || matches!(variant, Build) {
return Ok(());
}
if self.common.ask {
info!("Apply the config?");
let confirmation = dialoguer::Confirm::new().default(false).interact()?;
if !confirmation {
bail!("User rejected the new config");
}
}
if let Some(ext) = &self.backup_extension {
info!("Using {} as the backup extension", ext);
env::set_var("HOME_MANAGER_BACKUP_EXT", ext);
}
Command::new(target_profile.get_path().join("activate"))
.message("Activating configuration")
.run()?;
// Make sure out_path is not accidentally dropped
// https://docs.rs/tempfile/3.12.0/tempfile/index.html#early-drop-pitfall
drop(target_profile);
Ok(())
}
}
fn toplevel_for<I, S>(
installable: Installable,
push_drv: bool,
extra_args: I,
) -> Result<Installable>
where
I: IntoIterator<Item = S>,
S: AsRef<std::ffi::OsStr>,
{
let mut res = installable.clone();
let extra_args = {
let mut vec = Vec::new();
for elem in extra_args.into_iter() {
vec.push(elem.as_ref().to_owned());
}
vec
};
let toplevel = ["config", "home", "activationPackage"]
.into_iter()
.map(String::from);
match res {
Installable::Flake {
ref reference,
ref mut attribute,
} => 'flake: {
// If user explicitely selects some other attribute, don't push homeConfigurations
if !attribute.is_empty() {
break 'flake;
}
attribute.push(String::from("homeConfigurations"));
// check for <user> and <user@hostname>
let username = std::env::var("USER").expect("Couldn't get username");
let hostname = hostname::get()
.expect("Couldn't get hostname")
.to_str()
.unwrap()
.to_string();
let mut tried = vec![];
for attr in [format!("{username}@{hostname}"), username.to_string()] {
let func = format!(r#" x: x ? "{}" "#, attr);
let res = commands::Command::new("nix")
.arg("eval")
.args(&extra_args)
.arg("--apply")
.arg(func)
.args(
(Installable::Flake {
reference: reference.clone(),
attribute: attribute.clone(),
})
.to_args(),
)
.run_capture()
.expect("Checking home-manager output");
tried.push({
let mut attribute = attribute.clone();
attribute.push(attr.clone());
attribute
});
match res.map(|s| s.trim().to_owned()).as_deref() {
Some("true") => {
attribute.push(attr.clone());
if push_drv {
attribute.extend(toplevel);
}
break 'flake;
}
_ => {
continue;
}
}
}
let tried_str = tried
.into_iter()
.map(|a| {
let f = Installable::Flake {
reference: reference.clone(),
attribute: a,
};
f.to_args().join(" ")
})
.collect::<Vec<_>>()
.join(", ");
bail!("Couldn't find home-manager configuration, tried {tried_str}");
}
Installable::File {
ref mut attribute, ..
} => {
if push_drv {
attribute.extend(toplevel);
}
}
Installable::Expression {
ref mut attribute, ..
} => {
if push_drv {
attribute.extend(toplevel);
}
}
Installable::Store { .. } => {}
}
Ok(res)
}
impl HomeReplArgs {
fn run(self) -> Result<()> {
let toplevel = toplevel_for(self.installable, false, &self.extra_args)?;
Command::new("nix")
.arg("repl")
.args(toplevel.to_args())
.run()?;
Ok(())
}
}