-
Notifications
You must be signed in to change notification settings - Fork 94
Expand file tree
/
Copy pathinstall.rs
More file actions
426 lines (380 loc) · 17.7 KB
/
install.rs
File metadata and controls
426 lines (380 loc) · 17.7 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
use std::{
io::IsTerminal as _,
os::unix::prelude::PermissionsExt,
path::{Path, PathBuf},
process::ExitCode,
};
use crate::{
cli::{
ensure_root,
interaction::{self, PromptChoice},
signal_channel,
subcommand::split_receipt::{PHASE1_RECEIPT_LOCATION, PHASE2_RECEIPT_LOCATION},
CommandExecute,
},
error::HasExpectedErrors,
plan::RECEIPT_LOCATION,
settings::CommonSettings,
util::OnMissing,
BuiltinPlanner, InstallPlan, NixInstallerError,
};
use clap::{ArgAction, Parser};
use color_eyre::{
eyre::{eyre, WrapErr},
Section,
};
use owo_colors::OwoColorize;
const EXISTING_INCOMPATIBLE_PLAN_GUIDANCE: &str = "\
If you are trying to upgrade Nix, try running `sudo -i nix upgrade-nix` instead.\n\
If you are trying to install Nix over an existing install (from an incompatible `nix-installer` install), try running `/nix/nix-installer uninstall` then try to install again.\n\
If you are using `nix-installer` in an automated curing process and seeing this message, consider pinning the version you use via https://github.com/DeterminateSystems/nix-installer#accessing-other-versions.\
";
const PRE_PKG_SUGGEST: &str = "For a more robust Nix installation, use the Determinate package for macOS: https://dtr.mn/determinate-nix";
const DETERMINATE_MSG_EXPLAINER: &str = "\
Determinate Nix is Determinate Systems' validated and secure downstream Nix distribution for enterprises. \
It comes bundled with Determinate Nixd, a helpful daemon that automates some otherwise-unpleasant aspects of using Nix, such as garbage collection, and enables you to easily authenticate with FlakeHub.
For more details: https://dtr.mn/determinate-nix\
";
/**
Install Nix using a planner
By default, an appropriate planner is heuristically determined based on the system.
Some planners have additional options which can be set from the planner's subcommand.
*/
#[derive(Debug, Parser)]
#[command(args_conflicts_with_subcommands = true)]
pub struct Install {
/// Run installation without requiring explicit user confirmation
#[clap(
long,
env = "NIX_INSTALLER_NO_CONFIRM",
action(ArgAction::SetTrue),
default_value = "false",
global = true
)]
pub no_confirm: bool,
#[clap(flatten)]
pub settings: CommonSettings,
/// Provide an explanation of the changes the installation process will make to your system
#[clap(
long,
env = "NIX_INSTALLER_EXPLAIN",
action(ArgAction::SetTrue),
default_value = "false",
global = true
)]
pub explain: bool,
/// A path to a non-default installer plan
#[clap(env = "NIX_INSTALLER_PLAN")]
pub plan: Option<PathBuf>,
#[clap(subcommand)]
pub planner: Option<BuiltinPlanner>,
}
#[async_trait::async_trait]
impl CommandExecute for Install {
#[tracing::instrument(level = "trace", skip_all)]
async fn execute<T>(self, mut feedback: T) -> eyre::Result<ExitCode>
where
T: crate::feedback::Feedback,
{
let Self {
no_confirm,
plan,
planner: maybe_planner,
settings,
explain,
} = self;
ensure_root()?;
let existing_receipt: Option<InstallPlan> = match Path::new(RECEIPT_LOCATION).exists() {
true => {
tracing::trace!("Reading existing receipt");
let install_plan_string = tokio::fs::read_to_string(&RECEIPT_LOCATION)
.await
.wrap_err("Reading plan")?;
Some(
serde_json::from_str(&install_plan_string).wrap_err_with(|| {
format!("Unable to parse existing receipt `{RECEIPT_LOCATION}`, it may be from an incompatible version of `nix-installer`. Try running `/nix/nix-installer uninstall`, then installing again.")
})?,
)
},
false => None,
};
let uninstall_command = match Path::new("/nix/nix-installer").exists() {
true => "/nix/nix-installer uninstall".into(),
false => format!("curl --proto '=https' --tlsv1.2 -sSf -L https://install.determinate.systems/nix/tag/v{} | sh -s -- uninstall", env!("CARGO_PKG_VERSION")),
};
if plan.is_some() && maybe_planner.is_some() {
return Err(eyre!("`--plan` conflicts with passing a planner, a planner creates plans, so passing an existing plan doesn't make sense"));
}
if matches!(
target_lexicon::OperatingSystem::host(),
target_lexicon::OperatingSystem::MacOSX { .. }
| target_lexicon::OperatingSystem::Darwin
) {
let msg = feedback
.get_feature_ptr_payload::<String>("dni-det-msg-start-pkg-ptr")
.await
.unwrap_or(PRE_PKG_SUGGEST.into());
tracing::info!("{}", msg.trim());
}
let mut post_install_message = None;
let mut install_plan = if let Some(plan_path) = plan {
let install_plan_string = tokio::fs::read_to_string(&plan_path)
.await
.wrap_err("Reading plan")?;
serde_json::from_str(&install_plan_string)?
} else {
let mut planner = match maybe_planner {
Some(planner) => planner,
None => BuiltinPlanner::from_common_settings(settings.clone())
.await
.map_err(|e| eyre::eyre!(e))?,
};
match existing_receipt {
Some(existing_receipt) => {
if let Err(e) = existing_receipt.check_compatible() {
eprintln!(
"{}",
format!("\
{e}\n\
\n\
Found existing plan in `{RECEIPT_LOCATION}` which was created by a version incompatible `nix-installer`.\n\
{EXISTING_INCOMPATIBLE_PLAN_GUIDANCE}\n\
").red()
);
return Ok(ExitCode::FAILURE);
}
if existing_receipt.planner.typetag_name() != planner.typetag_name() {
eprintln!("{}", format!("Found existing plan in `{RECEIPT_LOCATION}` which used a different planner, try uninstalling the existing install with `{uninstall_command}`").red());
return Ok(ExitCode::FAILURE);
}
if existing_receipt.planner.settings().map_err(|e| eyre!(e))?
!= planner.settings().map_err(|e| eyre!(e))?
{
eprintln!("{}", format!("Found existing plan in `{RECEIPT_LOCATION}` which used different planner settings, try uninstalling the existing install with `{uninstall_command}`").red());
return Ok(ExitCode::FAILURE);
}
eprintln!("{}", format!("Found existing plan in `{RECEIPT_LOCATION}`, with the same settings, already completed. Try uninstalling (`{uninstall_command}`) and reinstalling if Nix isn't working").red());
return Ok(ExitCode::SUCCESS);
},
None => {
let planner_settings = planner.common_settings_mut();
if !planner_settings.determinate_nix {
if !std::io::stdin().is_terminal() || no_confirm {
let msg = feedback
.get_feature_ptr_payload::<String>("dni-det-msg-noninteractive-ptr")
.await
.unwrap_or("Consider using Determinate Nix, for less fuss: https://dtr.mn/determinate-nix".into());
post_install_message = Some(msg);
} else {
let base_prompt = feedback
.get_feature_ptr_payload::<String>(
"dni-det-msg-interactive-prompt-ptr",
)
.await
.unwrap_or("Install Determinate Nix?".into());
let explanation = feedback
.get_feature_ptr_payload::<String>(
"dni-det-msg-interactive-explanation-ptr",
)
.await
.unwrap_or(DETERMINATE_MSG_EXPLAINER.into());
let mut currently_explaining = explain;
loop {
let prompt = if currently_explaining {
&format!(
"\n{}\n{}",
base_prompt.trim().green(),
explanation.trim()
)
} else {
&format!("\n{}", base_prompt.trim().green())
};
let response = interaction::prompt(
prompt.to_string(),
PromptChoice::Yes,
currently_explaining,
)
.await?;
match response {
PromptChoice::Explain => {
currently_explaining = true;
},
PromptChoice::Yes => {
planner_settings.determinate_nix = true;
break;
},
PromptChoice::No => {
break;
},
}
}
}
}
feedback.set_planner(&planner).await?;
let res = planner.plan().await;
match res {
Ok(plan) => plan,
Err(err) => {
feedback.planning_failed(&err).await;
if let Some(expected) = err.expected() {
eprintln!("{}", expected.red());
return Ok(ExitCode::FAILURE);
}
return Err(err)?;
},
}
},
}
};
feedback.planning_succeeded().await;
if let Err(err) = install_plan.pre_install_check().await {
if let Some(expected) = err.expected() {
eprintln!("{}", expected.red());
return Ok(ExitCode::FAILURE);
}
Err(err)?
}
if !no_confirm {
let mut currently_explaining = explain;
loop {
match interaction::prompt(
install_plan
.describe_install(currently_explaining)
.await
.map_err(|e| eyre!(e))?,
PromptChoice::Yes,
currently_explaining,
)
.await?
{
PromptChoice::Yes => break,
PromptChoice::Explain => currently_explaining = true,
PromptChoice::No => {
interaction::clean_exit_with_message(
"Okay, not continuing with the installation. Bye!",
)
.await
},
}
}
}
let (tx, rx1) = signal_channel().await?;
match install_plan.install(feedback.clone(), rx1).await {
Err(err) => {
// Attempt to copy self to the store if possible, but since the install failed, this might not work, that's ok.
copy_self_to_nix_dir().await.ok();
if !no_confirm {
let mut was_expected = false;
if let Some(expected) = err.expected() {
was_expected = true;
eprintln!("{}", expected.red())
}
if !was_expected {
let error = eyre!(err).wrap_err("Install failure");
tracing::error!("{:?}", error);
};
eprintln!("{}", "Installation failure, offering to revert...".red());
let mut currently_explaining = explain;
loop {
match interaction::prompt(
install_plan
.describe_uninstall(currently_explaining)
.await
.map_err(|e| eyre!(e))?,
PromptChoice::Yes,
currently_explaining,
)
.await?
{
PromptChoice::Yes => break,
PromptChoice::Explain => currently_explaining = true,
PromptChoice::No => {
interaction::clean_exit_with_message(
"Okay, didn't do anything! Bye!",
)
.await
},
}
}
let rx2 = tx.subscribe();
let res = install_plan.uninstall(feedback, rx2).await;
match res {
Err(NixInstallerError::ActionRevert(errs)) => {
let mut report = eyre!("Multiple errors");
for err in errs {
report = report.error(err);
}
return Err(report)?;
},
Err(err) => {
if let Some(expected) = err.expected() {
eprintln!("{}", expected.red());
return Ok(ExitCode::FAILURE);
}
return Err(err)?;
},
_ => {
println!(
"\
{message}\n\
",
message =
"Partial Nix install was uninstalled successfully!".bold(),
);
},
}
} else {
if let Some(expected) = err.expected() {
eprintln!("{}", expected.red());
return Ok(ExitCode::FAILURE);
}
let error = eyre!(err).wrap_err("Install failure");
return Err(error)?;
}
},
Ok(_) => {
copy_self_to_nix_dir()
.await
.wrap_err("Copying `nix-installer` to `/nix/nix-installer`")?;
let phase1_receipt_path = Path::new(PHASE1_RECEIPT_LOCATION);
if phase1_receipt_path.exists() {
tracing::debug!("Removing pre-existing uninstall phase 1 receipt at {PHASE1_RECEIPT_LOCATION} after successful install");
crate::util::remove_file(phase1_receipt_path, OnMissing::Ignore)
.await
.wrap_err_with(|| format!("Failed to remove uninstall phase 1 receipt at {PHASE1_RECEIPT_LOCATION}"))?;
}
let phase2_receipt_path = Path::new(PHASE2_RECEIPT_LOCATION);
if phase2_receipt_path.exists() {
tracing::debug!("Removing pre-existing uninstall phase 2 receipt at {PHASE2_RECEIPT_LOCATION} after successful install");
crate::util::remove_file(phase2_receipt_path, OnMissing::Ignore)
.await
.wrap_err_with(|| format!("Failed to remove uninstall phase 2 receipt at {PHASE2_RECEIPT_LOCATION}"))?;
}
println!(
"\
{success}\n\
To get started using Nix, open a new shell or run `{shell_reminder}`\n\
",
success = "Nix was installed successfully!".green().bold(),
shell_reminder = match std::env::var("SHELL") {
Ok(val) if val.contains("fish") =>
". /nix/var/nix/profiles/default/etc/profile.d/nix-daemon.fish".bold(),
Ok(_) | Err(_) =>
". /nix/var/nix/profiles/default/etc/profile.d/nix-daemon.sh".bold(),
},
);
if let Some(post_message) = post_install_message {
println!("{}\n", post_message.trim());
}
},
}
Ok(ExitCode::SUCCESS)
}
}
#[tracing::instrument(level = "debug")]
async fn copy_self_to_nix_dir() -> Result<(), std::io::Error> {
let path = std::env::current_exe()?;
tokio::fs::copy(path, "/nix/nix-installer").await?;
tokio::fs::set_permissions("/nix/nix-installer", PermissionsExt::from_mode(0o0755)).await?;
Ok(())
}