1use std::path::{Path, PathBuf};
2
3use anyhow::{bail, Context, Result};
4use serde::{Deserialize, Serialize};
5
6use crate::discover::{self, Platform};
7
8pub const CONFIG_FILE: &str = "config.pkl";
9pub const CONFIG_TOML_COMPAT_FILE: &str = "config.toml";
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12enum LocalConfigFormat {
13 Pkl,
14 TomlCompat,
15}
16
17struct LocalConfigSource {
18 path: PathBuf,
19 format: LocalConfigFormat,
20}
21
22pub struct Config {
24 pub repo: PathBuf,
26 pub hostname: String,
28 pub nix_packages_file: PathBuf,
30 pub homebrew_file: PathBuf,
32 pub module_files: Vec<(String, PathBuf)>,
34 pub prefer_nix_on_equal: bool,
36 pub platform: Platform,
38 pub registries: Vec<RegistryConfig>,
40}
41
42#[derive(Deserialize, Serialize, Default)]
44struct FileConfig {
45 repo_path: Option<String>,
46 hostname: Option<String>,
47 prefer_nix_on_equal: Option<bool>,
48 identity: Option<IdentityConfig>,
49 registries: Option<Vec<RegistryConfig>>,
50}
51
52#[derive(Deserialize, Serialize, Default, Clone)]
54pub struct IdentityConfig {
55 pub git: Option<IdentityGitConfig>,
57 pub ssh: Option<IdentitySshConfig>,
59}
60
61#[derive(Deserialize, Serialize, Default, Clone)]
63pub struct IdentityGitConfig {
64 pub name: Option<String>,
65 pub email: Option<String>,
66}
67
68#[derive(Deserialize, Serialize, Default, Clone)]
70pub struct IdentitySshConfig {
71 pub labels: Option<Vec<String>>,
72}
73
74#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
75pub struct RegistryConfig {
76 pub name: String,
77 pub url: String,
78 pub trust: Option<String>,
79}
80
81impl Config {
82 pub fn resolve(cli_repo: Option<PathBuf>, cli_hostname: Option<String>) -> Result<Self> {
84 tracing::debug!(cli_repo = ?cli_repo, cli_hostname = ?cli_hostname, "resolving config");
85 let file_config = load_file_config().unwrap_or_default();
86 let platform = discover::detect_platform();
87
88 let not_found_msg = match platform {
89 Platform::Darwin => {
90 "Could not find nix-darwin repo. Run `nex init`, set NEX_REPO, \
91 or create ~/.config/nex/config.pkl with repo_path."
92 }
93 Platform::Linux => {
94 "Could not find NixOS config repo. Run `nex init`, set NEX_REPO, \
95 or create ~/.config/nex/config.pkl with repo_path."
96 }
97 };
98
99 let repo = cli_repo
100 .or_else(|| file_config.repo_path.map(PathBuf::from))
101 .or_else(|| discover::find_repo().ok())
102 .context(not_found_msg)?;
103
104 tracing::debug!(repo = %repo.display(), "config repo resolved");
105
106 let hostname = cli_hostname
107 .or(file_config.hostname)
108 .or_else(|| discover::hostname().ok())
109 .context("Could not detect hostname. Set NEX_HOSTNAME.")?;
110
111 tracing::debug!(%hostname, "hostname resolved");
112
113 if hostname.is_empty()
115 || hostname.starts_with('-')
116 || hostname.ends_with('-')
117 || !hostname
118 .chars()
119 .all(|c| c.is_ascii_alphanumeric() || c == '-')
120 {
121 anyhow::bail!(
122 "invalid hostname \"{hostname}\": must be alphanumeric with hyphens, \
123 no leading/trailing hyphen"
124 );
125 }
126
127 let scaffolded = repo.join("nix/modules/home").exists();
129
130 let nix_packages_file = if scaffolded {
131 repo.join("nix/modules/home/base.nix")
132 } else if repo.join("home.nix").exists() {
133 repo.join("home.nix")
134 } else {
135 repo.join("nix/modules/home/base.nix") };
137
138 let homebrew_file = match platform {
139 Platform::Darwin => repo.join("nix/modules/darwin/homebrew.nix"),
140 Platform::Linux => {
141 if scaffolded {
142 repo.join("nix/modules/nixos/packages.nix")
143 } else {
144 repo.join("configuration.nix")
145 }
146 }
147 };
148
149 let mut module_files = Vec::new();
151 let home_modules_dir = repo.join("nix/modules/home");
152 if home_modules_dir.is_dir() {
153 if let Ok(entries) = std::fs::read_dir(&home_modules_dir) {
154 for entry in entries.flatten() {
155 let path = entry.path();
156 if path.extension().and_then(|e| e.to_str()) != Some("nix") {
157 continue;
158 }
159 let stem = path
160 .file_stem()
161 .and_then(|s| s.to_str())
162 .unwrap_or("")
163 .to_string();
164 if stem == "base" || stem == "default" {
166 continue;
167 }
168 tracing::debug!(module = %stem, path = %path.display(), "discovered module");
169 module_files.push((stem, path));
170 }
171 }
172 module_files.sort_by(|a, b| a.0.cmp(&b.0));
173 }
174
175 let prefer_nix_on_equal = file_config.prefer_nix_on_equal.unwrap_or(false);
176 let registries = file_config
177 .registries
178 .filter(|registries| !registries.is_empty())
179 .unwrap_or_else(|| vec![crate::armory::default_registry()]);
180
181 Ok(Config {
182 repo,
183 hostname,
184 nix_packages_file,
185 homebrew_file,
186 module_files,
187 prefer_nix_on_equal,
188 platform,
189 registries,
190 })
191 }
192
193 pub fn all_nix_package_files(&self) -> Vec<&PathBuf> {
195 let mut files = vec![&self.nix_packages_file];
196 for (_, path) in &self.module_files {
197 files.push(path);
198 }
199 files
200 }
201}
202
203pub fn set_preference(key: &str, value: &str) -> Result<()> {
205 tracing::debug!(%key, %value, "setting preference");
206 let path = writable_config_path()?;
207 let content = read_config_value_for_write(&path)?;
208
209 let mut table = match content {
210 toml::Value::Table(table) => table,
211 _ => bail!("local Nex config root must be a table"),
212 };
213
214 let parsed_value: toml::Value =
215 toml::from_str::<toml::map::Map<String, toml::Value>>(&format!("v = {value}"))
216 .with_context(|| format!("invalid TOML value: {value}"))
217 .and_then(|t| {
218 t.into_iter()
219 .next()
220 .map(|(_, v)| v)
221 .context("empty TOML parse result")
222 })?;
223
224 table.insert(key.to_string(), parsed_value);
225 write_config_value(&path, &toml::Value::Table(table))
226}
227
228pub fn config_dir() -> Result<PathBuf> {
230 let home = dirs::home_dir().context("no home directory")?;
231 Ok(home.join(".config/nex"))
232}
233
234pub fn canonical_config_path() -> Result<PathBuf> {
235 Ok(config_dir()?.join(CONFIG_FILE))
236}
237
238pub fn toml_compat_config_path() -> Result<PathBuf> {
239 Ok(config_dir()?.join(CONFIG_TOML_COMPAT_FILE))
240}
241
242pub fn load_identity_config() -> Result<IdentityConfig> {
244 let fc = load_file_config().unwrap_or_default();
245 Ok(fc.identity.unwrap_or_default())
246}
247
248pub fn set_nested_preference(dotted_key: &str, value: toml::Value) -> Result<()> {
251 let path = writable_config_path()?;
252 let mut root = read_config_value_for_write(&path)?;
253
254 let parts: Vec<&str> = dotted_key.split('.').collect();
255 let mut current = &mut root;
256 for part in &parts[..parts.len() - 1] {
257 if !current.is_table() {
258 bail!("config key '{part}' is not a table");
259 }
260 current = current
261 .as_table_mut()
262 .expect("checked above")
263 .entry(part.to_string())
264 .or_insert_with(|| toml::Value::Table(toml::map::Map::new()));
265 }
266
267 let leaf = parts.last().context("empty key")?;
268 current
269 .as_table_mut()
270 .context("leaf parent is not a table")?
271 .insert(leaf.to_string(), value);
272
273 write_config_value(&path, &root)
274}
275
276pub fn append_to_list(dotted_key: &str, item: &str) -> Result<()> {
279 let path = writable_config_path()?;
280 let mut root = read_config_value_for_write(&path)?;
281
282 let parts: Vec<&str> = dotted_key.split('.').collect();
283 let mut current = &mut root;
284 for part in &parts[..parts.len() - 1] {
285 current = current
286 .as_table_mut()
287 .context("not a table")?
288 .entry(part.to_string())
289 .or_insert_with(|| toml::Value::Table(toml::map::Map::new()));
290 }
291
292 let leaf = parts.last().context("empty key")?;
293 let table = current
294 .as_table_mut()
295 .context("leaf parent is not a table")?;
296 let arr = table
297 .entry(leaf.to_string())
298 .or_insert_with(|| toml::Value::Array(Vec::new()));
299
300 let arr = arr.as_array_mut().context("config key is not an array")?;
301 let item_val = toml::Value::String(item.to_string());
302 if !arr.contains(&item_val) {
303 arr.push(item_val);
304 }
305
306 write_config_value(&path, &root)
307}
308
309pub fn write_initial_config(repo_path: &Path, hostname: &str) -> Result<PathBuf> {
310 let path = canonical_config_path()?;
311 let mut table = toml::map::Map::new();
312 table.insert(
313 "repo_path".to_string(),
314 toml::Value::String(repo_path.display().to_string()),
315 );
316 table.insert(
317 "hostname".to_string(),
318 toml::Value::String(hostname.to_string()),
319 );
320 write_config_value(&path, &toml::Value::Table(table))?;
321 Ok(path)
322}
323
324pub fn migrate_to_pkl(keep_toml: bool) -> Result<PathBuf> {
325 let source = resolve_config_source()?;
326 let value = match source {
327 Some(LocalConfigSource {
328 path,
329 format: LocalConfigFormat::Pkl,
330 }) => read_config_value_for_write(&path)?,
331 Some(LocalConfigSource {
332 path,
333 format: LocalConfigFormat::TomlCompat,
334 }) => read_config_value_for_write(&path)?,
335 None => toml::Value::Table(toml::map::Map::new()),
336 };
337
338 let canonical = canonical_config_path()?;
339 write_config_value(&canonical, &value)?;
340
341 if keep_toml {
342 let compat = toml_compat_config_path()?;
343 let rendered = toml::to_string_pretty(&value).context("serializing compatibility TOML")?;
344 crate::edit::atomic_write_bytes(&compat, rendered.as_bytes())
345 .with_context(|| format!("writing {}", compat.display()))?;
346 }
347
348 Ok(canonical)
349}
350
351pub fn export_config_toml() -> Result<String> {
352 let config = load_file_config()?;
353 let value = toml::Value::try_from(config).context("converting config to TOML value")?;
354 toml::to_string_pretty(&value).context("serializing config TOML")
355}
356
357fn load_file_config() -> Result<FileConfig> {
358 match resolve_config_source()? {
359 Some(source) => match source.format {
360 LocalConfigFormat::Pkl => {
361 tracing::debug!(path = %source.path.display(), "loaded canonical Pkl config file");
362 crate::document::load_document::<FileConfig>(&source.path, "local Nex config")
363 .map(|loaded| loaded.value)
364 }
365 LocalConfigFormat::TomlCompat => {
366 tracing::debug!(path = %source.path.display(), "loaded compatibility TOML config file");
367 let content = std::fs::read_to_string(&source.path)
368 .with_context(|| format!("reading {}", source.path.display()))?;
369 toml::from_str(&content)
370 .with_context(|| format!("invalid config in {}", source.path.display()))
371 }
372 },
373 None => Ok(FileConfig::default()),
374 }
375}
376
377fn resolve_config_source() -> Result<Option<LocalConfigSource>> {
378 let canonical = canonical_config_path()?;
379 if canonical.exists() {
380 return Ok(Some(LocalConfigSource {
381 path: canonical,
382 format: LocalConfigFormat::Pkl,
383 }));
384 }
385
386 let compat = toml_compat_config_path()?;
387 if compat.exists() {
388 return Ok(Some(LocalConfigSource {
389 path: compat,
390 format: LocalConfigFormat::TomlCompat,
391 }));
392 }
393
394 if let Some(platform_dir) = dirs::config_dir() {
395 let legacy = platform_dir.join(format!("nex/{CONFIG_TOML_COMPAT_FILE}"));
396 if legacy.exists() {
397 return Ok(Some(LocalConfigSource {
398 path: legacy,
399 format: LocalConfigFormat::TomlCompat,
400 }));
401 }
402 }
403
404 Ok(None)
405}
406
407fn writable_config_path() -> Result<PathBuf> {
408 let canonical = canonical_config_path()?;
409 if canonical.exists() {
410 return Ok(canonical);
411 }
412 let compat = toml_compat_config_path()?;
413 if compat.exists() {
414 return Ok(compat);
415 }
416 Ok(canonical)
417}
418
419fn read_config_value_for_write(path: &Path) -> Result<toml::Value> {
420 if !path.exists() {
421 return Ok(toml::Value::Table(toml::map::Map::new()));
422 }
423 match config_format_for_path(path)? {
424 LocalConfigFormat::Pkl => {
425 let config =
426 crate::document::load_document::<FileConfig>(path, "local Nex config")?.value;
427 toml::Value::try_from(config).context("converting config to mutable value")
428 }
429 LocalConfigFormat::TomlCompat => {
430 let content = std::fs::read_to_string(path)
431 .with_context(|| format!("reading {}", path.display()))?;
432 if content.trim().is_empty() {
433 Ok(toml::Value::Table(toml::map::Map::new()))
434 } else {
435 toml::from_str(&content).with_context(|| format!("parsing {}", path.display()))
436 }
437 }
438 }
439}
440
441fn write_config_value(path: &Path, value: &toml::Value) -> Result<()> {
442 let serialized = serialize_config_value(value, config_format_for_path(path)?)?;
443 std::fs::create_dir_all(config_dir()?)?;
444 crate::edit::atomic_write_bytes(path, serialized.as_bytes())
445 .with_context(|| format!("writing {}", path.display()))
446}
447
448fn config_format_for_path(path: &Path) -> Result<LocalConfigFormat> {
449 match path.extension().and_then(|ext| ext.to_str()) {
450 Some("pkl") => Ok(LocalConfigFormat::Pkl),
451 Some("toml") => Ok(LocalConfigFormat::TomlCompat),
452 Some(ext) => bail!("unsupported config extension .{ext}; canonical Nex config uses .pkl"),
453 None => bail!("config path must have an extension"),
454 }
455}
456
457fn serialize_config_value(value: &toml::Value, format: LocalConfigFormat) -> Result<String> {
458 match format {
459 LocalConfigFormat::Pkl => serialize_pkl_document(value),
460 LocalConfigFormat::TomlCompat => {
461 toml::to_string_pretty(value).context("serializing config TOML")
462 }
463 }
464}
465
466fn serialize_pkl_document(value: &toml::Value) -> Result<String> {
467 let mut out =
468 String::from("// Generated by nex. Edit config.pkl as the canonical local config.\n");
469 let table = value.as_table().context("config root must be a table")?;
470 for (key, value) in table {
471 write_pkl_entry(&mut out, key, value, 0)?;
472 }
473 Ok(out)
474}
475
476fn write_pkl_entry(out: &mut String, key: &str, value: &toml::Value, indent: usize) -> Result<()> {
477 let padding = " ".repeat(indent);
478 match value {
479 toml::Value::Table(table) => {
480 out.push_str(&format!("{padding}{key} {{\n"));
481 for (child_key, child_value) in table {
482 write_pkl_entry(out, child_key, child_value, indent + 1)?;
483 }
484 out.push_str(&format!("{padding}}}\n"));
485 }
486 _ => {
487 out.push_str(&format!(
488 "{padding}{key} = {}\n",
489 pkl_literal(value).with_context(|| format!("serializing config key {key}"))?
490 ));
491 }
492 }
493 Ok(())
494}
495
496fn pkl_literal(value: &toml::Value) -> Result<String> {
497 match value {
498 toml::Value::String(value) => Ok(format!("{value:?}")),
499 toml::Value::Boolean(value) => Ok(value.to_string()),
500 toml::Value::Integer(value) => Ok(value.to_string()),
501 toml::Value::Float(value) => Ok(value.to_string()),
502 toml::Value::Array(values) => {
503 let rendered = values
504 .iter()
505 .map(pkl_literal)
506 .collect::<Result<Vec<_>>>()?
507 .join(", ");
508 Ok(format!("List({rendered})"))
509 }
510 toml::Value::Datetime(value) => Ok(format!("{:?}", value.to_string())),
511 toml::Value::Table(_) => bail!("nested table should be serialized as a Pkl block"),
512 }
513}
514
515#[cfg(test)]
516mod tests {
517 use super::*;
518 use std::fs;
519
520 #[test]
521 fn serializes_generated_pkl_config() {
522 let mut table = toml::map::Map::new();
523 table.insert(
524 "repo_path".to_string(),
525 toml::Value::String("/tmp/repo".to_string()),
526 );
527 table.insert(
528 "hostname".to_string(),
529 toml::Value::String("test-host".to_string()),
530 );
531 table.insert(
532 "prefer_nix_on_equal".to_string(),
533 toml::Value::Boolean(true),
534 );
535
536 let rendered = serialize_pkl_document(&toml::Value::Table(table)).unwrap();
537 assert!(rendered.contains("repo_path = \"/tmp/repo\""));
538 assert!(rendered.contains("hostname = \"test-host\""));
539 assert!(rendered.contains("prefer_nix_on_equal = true"));
540 }
541
542 #[test]
543 fn resolves_pkl_before_toml() {
544 let dir = tempfile::tempdir().unwrap();
545 fs::write(dir.path().join(CONFIG_FILE), "repo_path = \"/pkl\"\n").unwrap();
546 fs::write(
547 dir.path().join(CONFIG_TOML_COMPAT_FILE),
548 "repo_path = \"/toml\"\n",
549 )
550 .unwrap();
551
552 let pkl = dir.path().join(CONFIG_FILE);
553 let toml = dir.path().join(CONFIG_TOML_COMPAT_FILE);
554 assert!(pkl.exists());
555 assert!(toml.exists());
556 assert_eq!(
557 config_format_for_path(&pkl).unwrap(),
558 LocalConfigFormat::Pkl
559 );
560 assert_eq!(
561 config_format_for_path(&toml).unwrap(),
562 LocalConfigFormat::TomlCompat
563 );
564 }
565 #[test]
566 fn migrate_preserves_toml_export_shape() {
567 let mut table = toml::map::Map::new();
568 table.insert(
569 "repo_path".to_string(),
570 toml::Value::String("/tmp/repo".to_string()),
571 );
572 table.insert(
573 "hostname".to_string(),
574 toml::Value::String("test-host".to_string()),
575 );
576 let value = toml::Value::Table(table);
577 let pkl = serialize_config_value(&value, LocalConfigFormat::Pkl).unwrap();
578 let toml = serialize_config_value(&value, LocalConfigFormat::TomlCompat).unwrap();
579
580 assert!(pkl.contains("repo_path = \"/tmp/repo\""));
581 assert!(toml.contains("repo_path = \"/tmp/repo\""));
582 assert!(toml::from_str::<toml::Value>(&toml).is_ok());
583 }
584}