forked from DeterminateSystems/nix-installer
-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
settings.rs
735 lines (667 loc) · 24.5 KB
/
settings.rs
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
/*! Configurable knobs and their related errors
*/
use std::{collections::HashMap, fmt::Display, path::PathBuf, str::FromStr};
#[cfg(feature = "cli")]
use clap::{
error::{ContextKind, ContextValue},
ArgAction,
};
use indexmap::map::Entry;
use url::Url;
pub const SCRATCH_DIR: &str = "/nix/temp-install-dir";
pub const NIX_TARBALL_PATH: &str = env!("NIX_INSTALLER_TARBALL_PATH");
/// The NIX_INSTALLER_TARBALL_PATH environment variable should point to a target-appropriate
/// Nix installation tarball, like nix-2.21.2-aarch64-darwin.tar.xz. The contents are embedded
/// in the resulting binary.
pub const NIX_TARBALL: &[u8] = include_bytes!(env!("NIX_INSTALLER_TARBALL_PATH"));
#[cfg(feature = "determinate-nix")]
/// The DETERMINATE_NIXD_BINARY_PATH environment variable should point to a target-appropriate
/// static build of the Determinate Nixd binary. The contents are embedded in the resulting
/// binary if the determinate-nix feature is turned on.
pub const DETERMINATE_NIXD_BINARY: Option<&[u8]> =
Some(include_bytes!(env!("DETERMINATE_NIXD_BINARY_PATH")));
#[cfg(not(feature = "determinate-nix"))]
/// The DETERMINATE_NIXD_BINARY_PATH environment variable should point to a target-appropriate
/// static build of the Determinate Nixd binary. The contents are embedded in the resulting
/// binary if the determinate-nix feature is turned on.
pub const DETERMINATE_NIXD_BINARY: Option<&[u8]> = None;
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "cli", derive(clap::ValueEnum))]
pub enum InitSystem {
None,
Systemd,
Launchd,
}
impl std::fmt::Display for InitSystem {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
InitSystem::None => write!(f, "none"),
InitSystem::Systemd => write!(f, "systemd"),
InitSystem::Launchd => write!(f, "launchd"),
}
}
}
/** Common settings used by all [`BuiltinPlanner`](crate::planner::BuiltinPlanner)s
Settings which only apply to certain [`Planner`](crate::planner::Planner)s should be located in the planner.
*/
#[serde_with::serde_as]
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
#[cfg_attr(feature = "cli", derive(clap::Parser))]
pub struct CommonSettings {
/// Enable Determinate Nix. See: <https://determinate.systems/enterprise>
// setting skip = false means this always gets the value false, which is easier than completely removing this from the struct and changing all instances it is used
#[cfg_attr(
feature = "cli",
clap(
// long = "determinate",
// env = "NIX_INSTALLER_DETERMINATE",
// default_value = "false",
skip = false,
)
)]
pub determinate_nix: bool,
/// Modify the user profile to automatically load Nix
#[cfg_attr(
feature = "cli",
clap(
action(ArgAction::SetFalse),
default_value = "true",
global = true,
env = "NIX_INSTALLER_MODIFY_PROFILE",
long = "no-modify-profile"
)
)]
pub modify_profile: bool,
/// The Nix build group name
#[cfg_attr(
feature = "cli",
clap(
long,
default_value = "nixbld",
env = "NIX_INSTALLER_NIX_BUILD_GROUP_NAME",
global = true
)
)]
pub nix_build_group_name: String,
/// The Nix build group GID
#[cfg_attr(
feature = "cli",
clap(long, env = "NIX_INSTALLER_NIX_BUILD_GROUP_ID", global = true)
)]
#[cfg_attr(
all(feature = "cli"),
clap(default_value_t = default_nix_build_group_id())
)]
pub nix_build_group_id: u32,
/// The Nix build user prefix (user numbers will be postfixed)
#[cfg_attr(
feature = "cli",
clap(long, env = "NIX_INSTALLER_NIX_BUILD_USER_PREFIX", global = true)
)]
#[cfg_attr(
all(target_os = "macos", feature = "cli"),
clap(default_value = "_nixbld")
)]
#[cfg_attr(
all(target_os = "linux", feature = "cli"),
clap(default_value = "nixbld")
)]
pub nix_build_user_prefix: String,
/// The number of build users to create
#[cfg_attr(
feature = "cli",
clap(
long,
alias = "daemon-user-count",
env = "NIX_INSTALLER_NIX_BUILD_USER_COUNT",
global = true
)
)]
#[cfg_attr(all(target_os = "macos", feature = "cli"), clap(default_value = "32"))]
#[cfg_attr(all(target_os = "linux", feature = "cli"), clap(default_value = "32"))]
pub nix_build_user_count: u32,
/// The Nix build user base UID (ascending)
#[cfg_attr(
feature = "cli",
clap(long, env = "NIX_INSTALLER_NIX_BUILD_USER_ID_BASE", global = true)
)]
#[cfg_attr(
all(target_os = "macos", feature = "cli"),
doc = "Service users on Mac should be between 200-400"
)]
#[cfg_attr(
all(feature = "cli"),
clap(default_value_t = default_nix_build_user_id_base())
)]
pub nix_build_user_id_base: u32,
/// The Nix package URL
#[cfg_attr(
feature = "cli",
clap(long, env = "NIX_INSTALLER_NIX_PACKAGE_URL", global = true, value_parser = clap::value_parser!(UrlOrPath), default_value = None)
)]
pub nix_package_url: Option<UrlOrPath>,
/// The proxy to use (if any); valid proxy bases are `https://$URL`, `http://$URL` and `socks5://$URL`
#[cfg_attr(feature = "cli", clap(long, env = "NIX_INSTALLER_PROXY"))]
pub proxy: Option<Url>,
/// An SSL cert to use (if any); used for fetching Nix and sets `ssl-cert-file` in `/etc/nix/nix.conf`
#[cfg_attr(feature = "cli", clap(long, env = "NIX_INSTALLER_SSL_CERT_FILE"))]
pub ssl_cert_file: Option<PathBuf>,
/// Extra configuration lines for `/etc/nix.conf`
#[cfg_attr(feature = "cli", clap(long, action = ArgAction::Append, num_args = 0.., env = "NIX_INSTALLER_EXTRA_CONF", global = true))]
pub extra_conf: Vec<UrlOrPathOrString>,
/// If `nix-installer` should forcibly recreate files it finds existing
#[cfg_attr(
feature = "cli",
clap(
long,
action(ArgAction::SetTrue),
default_value = "false",
global = true,
env = "NIX_INSTALLER_FORCE"
)
)]
pub force: bool,
#[cfg(feature = "diagnostics")]
/// Relate the install diagnostic to a specific value
#[cfg_attr(
feature = "cli",
clap(
long,
default_value = None,
env = "NIX_INSTALLER_DIAGNOSTIC_ATTRIBUTION",
global = true
)
)]
pub diagnostic_attribution: Option<String>,
#[cfg(feature = "diagnostics")]
/// The URL or file path for an installation diagnostic to be sent
///
/// Sample of the data sent:
///
/// {
/// "attribution": null,
/// "version": "0.4.0",
/// "planner": "linux",
/// "configured_settings": [ "modify_profile" ],
/// "os_name": "Ubuntu",
/// "os_version": "22.04.1 LTS (Jammy Jellyfish)",
/// "triple": "x86_64-unknown-linux-gnu",
/// "is_ci": false,
/// "action": "Install",
/// "status": "Success"
/// }
///
/// To disable diagnostic reporting, unset the default with `--diagnostic-endpoint ""`, or `NIX_INSTALLER_DIAGNOSTIC_ENDPOINT=""`
#[clap(
long,
env = "NIX_INSTALLER_DIAGNOSTIC_ENDPOINT",
global = true,
value_parser = crate::diagnostics::diagnostic_endpoint_validator,
num_args = 0..=1, // Required to allow `--diagnostic-endpoint` or `NIX_INSTALLER_DIAGNOSTIC_ENDPOINT=""`
default_value = "https://install.determinate.systems/nix/diagnostic"
)]
pub diagnostic_endpoint: Option<String>,
/// Whether to setup system channels
#[cfg_attr(
feature = "cli",
clap(
action(ArgAction::SetFalse),
default_value = "true",
global = true,
env = "NIX_INSTALLER_ADD_CHANNEL",
long("no-add-channel"),
)
)]
pub add_channel: bool,
}
pub(crate) fn default_nix_build_user_id_base() -> u32 {
use target_lexicon::OperatingSystem;
match OperatingSystem::host() {
OperatingSystem::MacOSX { .. } | OperatingSystem::Darwin => 350,
_ => 30_000,
}
}
pub(crate) fn default_nix_build_group_id() -> u32 {
use target_lexicon::OperatingSystem;
match OperatingSystem::host() {
OperatingSystem::MacOSX { .. } | OperatingSystem::Darwin => 350,
_ => 30_000,
}
}
impl CommonSettings {
/// The default settings for the given Architecture & Operating System
pub async fn default() -> Result<Self, InstallSettingsError> {
let nix_build_user_prefix;
use target_lexicon::{Architecture, OperatingSystem};
match (Architecture::host(), OperatingSystem::host()) {
(Architecture::X86_64, OperatingSystem::Linux) => {
nix_build_user_prefix = "nixbld";
},
(Architecture::X86_32(_), OperatingSystem::Linux) => {
nix_build_user_prefix = "nixbld";
},
(Architecture::Aarch64(_), OperatingSystem::Linux) => {
nix_build_user_prefix = "nixbld";
},
(Architecture::X86_64, OperatingSystem::MacOSX { .. })
| (Architecture::X86_64, OperatingSystem::Darwin) => {
nix_build_user_prefix = "_nixbld";
},
(Architecture::Aarch64(_), OperatingSystem::MacOSX { .. })
| (Architecture::Aarch64(_), OperatingSystem::Darwin) => {
nix_build_user_prefix = "_nixbld";
},
_ => {
return Err(InstallSettingsError::UnsupportedArchitecture(
target_lexicon::HOST,
))
},
};
Ok(Self {
determinate_nix: false,
modify_profile: true,
nix_build_group_name: String::from("nixbld"),
nix_build_group_id: default_nix_build_group_id(),
nix_build_user_id_base: default_nix_build_user_id_base(),
nix_build_user_count: 32,
nix_build_user_prefix: nix_build_user_prefix.to_string(),
nix_package_url: None,
proxy: Default::default(),
extra_conf: Default::default(),
force: false,
ssl_cert_file: Default::default(),
#[cfg(feature = "diagnostics")]
diagnostic_attribution: None,
#[cfg(feature = "diagnostics")]
diagnostic_endpoint: Some("https://install.determinate.systems/nix/diagnostic".into()),
add_channel: false,
})
}
/// A listing of the settings, suitable for [`Planner::settings`](crate::planner::Planner::settings)
pub fn settings(&self) -> Result<HashMap<String, serde_json::Value>, InstallSettingsError> {
let Self {
determinate_nix,
modify_profile,
nix_build_group_name,
nix_build_group_id,
nix_build_user_prefix,
nix_build_user_id_base,
nix_build_user_count,
nix_package_url,
proxy,
extra_conf,
force,
ssl_cert_file,
#[cfg(feature = "diagnostics")]
diagnostic_attribution: _,
#[cfg(feature = "diagnostics")]
diagnostic_endpoint,
add_channel,
} = self;
let mut map = HashMap::default();
map.insert(
"determinate_nix".into(),
serde_json::to_value(determinate_nix)?,
);
map.insert(
"modify_profile".into(),
serde_json::to_value(modify_profile)?,
);
map.insert(
"nix_build_group_name".into(),
serde_json::to_value(nix_build_group_name)?,
);
map.insert(
"nix_build_group_id".into(),
serde_json::to_value(nix_build_group_id)?,
);
map.insert(
"nix_build_user_prefix".into(),
serde_json::to_value(nix_build_user_prefix)?,
);
map.insert(
"nix_build_user_id_base".into(),
serde_json::to_value(nix_build_user_id_base)?,
);
map.insert(
"nix_build_user_count".into(),
serde_json::to_value(nix_build_user_count)?,
);
map.insert(
"nix_package_url".into(),
serde_json::to_value(nix_package_url)?,
);
map.insert("proxy".into(), serde_json::to_value(proxy)?);
map.insert("ssl_cert_file".into(), serde_json::to_value(ssl_cert_file)?);
map.insert("extra_conf".into(), serde_json::to_value(extra_conf)?);
map.insert("force".into(), serde_json::to_value(force)?);
#[cfg(feature = "diagnostics")]
map.insert(
"diagnostic_endpoint".into(),
serde_json::to_value(diagnostic_endpoint)?,
);
map.insert("add_channel".into(), serde_json::to_value(add_channel)?);
Ok(map)
}
}
async fn linux_detect_systemd_started() -> bool {
use std::process::Stdio;
let mut started = false;
if std::path::Path::new("/run/systemd/system").exists() {
started = tokio::process::Command::new("systemctl")
.arg("status")
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.await
.ok()
.map(|exit| exit.success())
.unwrap_or(false)
}
// TODO: Other inits
started
}
#[serde_with::serde_as]
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
#[cfg_attr(feature = "cli", derive(clap::Parser))]
pub struct InitSettings {
/// Which init system to configure (if `--init none` Nix will be root-only)
#[cfg_attr(feature = "cli", clap(value_parser, long, env = "NIX_INSTALLER_INIT",))]
#[cfg_attr(
all(target_os = "macos", feature = "cli"),
clap(default_value_t = InitSystem::Launchd)
)]
#[cfg_attr(
all(target_os = "linux", feature = "cli"),
clap(default_value_t = InitSystem::Systemd)
)]
pub init: InitSystem,
/// Start the daemon (if not `--init none`)
#[cfg_attr(
feature = "cli",
clap(
value_parser,
long,
action(ArgAction::SetFalse),
env = "NIX_INSTALLER_START_DAEMON",
default_value_t = true,
long = "no-start-daemon"
)
)]
pub start_daemon: bool,
}
impl InitSettings {
/// The default settings for the given Architecture & Operating System
pub async fn default() -> Result<Self, InstallSettingsError> {
use target_lexicon::{Architecture, OperatingSystem};
let (init, start_daemon) = match (Architecture::host(), OperatingSystem::host()) {
(Architecture::X86_64, OperatingSystem::Linux) => {
(InitSystem::Systemd, linux_detect_systemd_started().await)
},
(Architecture::X86_32(_), OperatingSystem::Linux) => {
(InitSystem::Systemd, linux_detect_systemd_started().await)
},
(Architecture::Aarch64(_), OperatingSystem::Linux) => {
(InitSystem::Systemd, linux_detect_systemd_started().await)
},
(Architecture::X86_64, OperatingSystem::MacOSX { .. })
| (Architecture::X86_64, OperatingSystem::Darwin) => (InitSystem::Launchd, true),
(Architecture::Aarch64(_), OperatingSystem::MacOSX { .. })
| (Architecture::Aarch64(_), OperatingSystem::Darwin) => (InitSystem::Launchd, true),
_ => {
return Err(InstallSettingsError::UnsupportedArchitecture(
target_lexicon::HOST,
))
},
};
Ok(Self { init, start_daemon })
}
/// A listing of the settings, suitable for [`Planner::settings`](crate::planner::Planner::settings)
pub fn settings(&self) -> Result<HashMap<String, serde_json::Value>, InstallSettingsError> {
let Self { init, start_daemon } = self;
let mut map = HashMap::default();
map.insert("init".into(), serde_json::to_value(init)?);
map.insert("start_daemon".into(), serde_json::to_value(start_daemon)?);
Ok(map)
}
/// Which init system to configure
pub fn init(&mut self, init: InitSystem) -> &mut Self {
self.init = init;
self
}
/// Start the daemon (if one is configured)
pub fn start_daemon(&mut self, toggle: bool) -> &mut Self {
self.start_daemon = toggle;
self
}
}
/// An error originating from a [`Planner::settings`](crate::planner::Planner::settings)
#[non_exhaustive]
#[derive(thiserror::Error, Debug, strum::IntoStaticStr)]
pub enum InstallSettingsError {
/// `nix-installer` does not support the architecture right now
#[error("`nix-installer` does not support the `{0}` architecture right now")]
UnsupportedArchitecture(target_lexicon::Triple),
/// Parsing URL
#[error("Parsing URL")]
Parse(
#[source]
#[from]
url::ParseError,
),
/// JSON serialization or deserialization error
#[error("JSON serialization or deserialization error")]
SerdeJson(
#[source]
#[from]
serde_json::Error,
),
#[error("No supported init system found")]
InitNotSupported,
#[error(transparent)]
UrlOrPath(#[from] UrlOrPathError),
}
#[derive(Debug, thiserror::Error)]
pub enum UrlOrPathError {
#[error("Error parsing URL `{0}`")]
Url(String, #[source] url::ParseError),
#[error("The specified path `{0}` does not exist")]
PathDoesNotExist(PathBuf),
#[error("Error fetching URL `{0}`")]
Reqwest(Url, #[source] reqwest::Error),
#[error("I/O error when accessing `{0}`")]
Io(PathBuf, #[source] std::io::Error),
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize, Clone)]
pub enum UrlOrPath {
Url(Url),
Path(PathBuf),
}
impl Display for UrlOrPath {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
UrlOrPath::Url(url) => f.write_fmt(format_args!("{url}")),
UrlOrPath::Path(path) => f.write_fmt(format_args!("{}", path.display())),
}
}
}
impl FromStr for UrlOrPath {
type Err = UrlOrPathError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match Url::parse(s) {
Ok(url) => Ok(UrlOrPath::Url(url)),
Err(url::ParseError::RelativeUrlWithoutBase) => {
// This is most likely a relative path (`./boop` or `boop`)
// or an absolute path (`/boop`)
//
// So we'll see if such a path exists, and if so, use it
let path = PathBuf::from(s);
if path.exists() {
Ok(UrlOrPath::Path(path))
} else {
Err(UrlOrPathError::PathDoesNotExist(path))
}
},
Err(e) => Err(UrlOrPathError::Url(s.to_string(), e)),
}
}
}
#[cfg(feature = "cli")]
impl clap::builder::TypedValueParser for UrlOrPath {
type Value = UrlOrPath;
fn parse_ref(
&self,
cmd: &clap::Command,
_arg: Option<&clap::Arg>,
value: &std::ffi::OsStr,
) -> Result<Self::Value, clap::Error> {
let value_str = value.to_str().ok_or_else(|| {
let mut err = clap::Error::new(clap::error::ErrorKind::InvalidValue);
err.insert(
ContextKind::InvalidValue,
ContextValue::String(format!("`{value:?}` not a UTF-8 string")),
);
err
})?;
match UrlOrPath::from_str(value_str) {
Ok(v) => Ok(v),
Err(from_str_error) => {
let mut err = clap::Error::new(clap::error::ErrorKind::InvalidValue).with_cmd(cmd);
err.insert(
clap::error::ContextKind::Custom,
clap::error::ContextValue::String(from_str_error.to_string()),
);
Err(err)
},
}
}
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize, Clone)]
pub enum UrlOrPathOrString {
Url(Url),
Path(PathBuf),
String(String),
}
impl FromStr for UrlOrPathOrString {
type Err = url::ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match Url::parse(s) {
Ok(url) => Ok(UrlOrPathOrString::Url(url)),
Err(url::ParseError::RelativeUrlWithoutBase) => {
// This is most likely a relative path (`./boop` or `boop`)
// or an absolute path (`/boop`)
//
// So we'll see if such a path exists, and if so, use it
let path = PathBuf::from(s);
if path.exists() {
Ok(UrlOrPathOrString::Path(path))
} else {
// The path doesn't exist, so the user is providing us with a string
Ok(UrlOrPathOrString::String(s.into()))
}
},
Err(e) => Err(e),
}
}
}
#[cfg(feature = "cli")]
impl clap::builder::TypedValueParser for UrlOrPathOrString {
type Value = UrlOrPathOrString;
fn parse_ref(
&self,
cmd: &clap::Command,
_arg: Option<&clap::Arg>,
value: &std::ffi::OsStr,
) -> Result<Self::Value, clap::Error> {
let value_str = value.to_str().ok_or_else(|| {
let mut err = clap::Error::new(clap::error::ErrorKind::InvalidValue);
err.insert(
ContextKind::InvalidValue,
ContextValue::String(format!("`{value:?}` not a UTF-8 string")),
);
err
})?;
match UrlOrPathOrString::from_str(value_str) {
Ok(v) => Ok(v),
Err(from_str_error) => {
let mut err = clap::Error::new(clap::error::ErrorKind::InvalidValue).with_cmd(cmd);
err.insert(
clap::error::ContextKind::Custom,
clap::error::ContextValue::String(from_str_error.to_string()),
);
Err(err)
},
}
}
}
#[cfg(feature = "diagnostics")]
impl crate::diagnostics::ErrorDiagnostic for InstallSettingsError {
fn diagnostic(&self) -> String {
let static_str: &'static str = (self).into();
static_str.to_string()
}
}
#[cfg(test)]
mod tests {
use super::{FromStr, PathBuf, Url, UrlOrPath, UrlOrPathOrString};
#[test]
fn url_or_path_or_string_parses() -> Result<(), Box<dyn std::error::Error>> {
assert_eq!(
UrlOrPathOrString::from_str("https://boop.bleat")?,
UrlOrPathOrString::Url(Url::from_str("https://boop.bleat")?),
);
assert_eq!(
UrlOrPathOrString::from_str("file:///boop/bleat")?,
UrlOrPathOrString::Url(Url::from_str("file:///boop/bleat")?),
);
// The file *must* exist!
assert_eq!(
UrlOrPathOrString::from_str(file!())?,
UrlOrPathOrString::Path(PathBuf::from_str(file!())?),
);
assert_eq!(
UrlOrPathOrString::from_str("Boop")?,
UrlOrPathOrString::String(String::from("Boop")),
);
Ok(())
}
#[test]
fn url_or_path_parses() -> Result<(), Box<dyn std::error::Error>> {
assert_eq!(
UrlOrPath::from_str("https://boop.bleat")?,
UrlOrPath::Url(Url::from_str("https://boop.bleat")?),
);
assert_eq!(
UrlOrPath::from_str("file:///boop/bleat")?,
UrlOrPath::Url(Url::from_str("file:///boop/bleat")?),
);
// The file *must* exist!
assert_eq!(
UrlOrPath::from_str(file!())?,
UrlOrPath::Path(PathBuf::from_str(file!())?),
);
Ok(())
}
}
pub fn determinate_nix_settings() -> nix_config_parser::NixConfig {
let mut cfg = nix_config_parser::NixConfig::new();
let settings = cfg.settings_mut();
settings.insert("netrc-file".into(), "/nix/var/determinate/netrc".into());
let extra_substituters = ["https://cache.flakehub.com"];
match settings.entry("extra-substituters".to_string()) {
Entry::Occupied(mut slot) => {
let slot_mut = slot.get_mut();
for extra_substituter in extra_substituters {
if !slot_mut.contains(extra_substituter) {
*slot_mut += " ";
*slot_mut += extra_substituter;
}
}
},
Entry::Vacant(slot) => {
let _ = slot.insert(extra_substituters.join(" "));
},
};
cfg
}