nix_data/config/configfile.rs
1
2use crate::{CONFIG, SYSCONFIG, CONFIGDIR};
3use anyhow::{Result, anyhow};
4use serde::{Deserialize, Serialize};
5use std::{
6 fs::{self, File},
7 io::{Write, BufReader},
8 path::Path,
9};
10
11/// Struct containing locations of system configuration files and some user configuration.
12#[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug, Default)]
13pub struct NixDataConfig {
14 /// Path to the NixOS configuration file. Typically `/etc/nixos/configuration.nix`.
15 pub systemconfig: Option<String>,
16 /// Path to the NixOS flake file. Typically `/etc/nixos/flake.nix`.
17 pub flake: Option<String>,
18 /// Specifies which configuration should be user from the `nixosConfigurations` attribute set in the flake file.
19 /// If not set, NixOS defaults to the hostname of the system.
20 pub flakearg: Option<String>,
21 /// Specifies how many NixOS generations to keep. If set to 0, all generations will be kept.
22 /// If not set, the default is 5.
23 pub generations: Option<u32>,
24}
25
26
27/// Type of package management used by the user.
28/// - [Profile](UserPkgType::Profile) refers to the `nix profile` command.
29/// - [Env](UserPkgType::Env) refers to the `nix-env` command.
30#[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug)]
31pub enum UserPkgType {
32 Profile,
33 Env,
34}
35
36/// Reads the config file and returns the config struct.
37/// If the config file doesn't exist in both the user (`~/.config/nix-data`) and system (`/etc/nix-data`) config directories,
38/// this function will return an error.
39pub fn getconfig() -> Result<NixDataConfig> {
40 // Check if user config exists
41 if Path::new(&*CONFIG).exists() {
42 // Read user config
43 let config: NixDataConfig = serde_json::from_reader(BufReader::new(File::open(&*CONFIG)?))?;
44 Ok(config)
45 } else if Path::new(SYSCONFIG).exists() {
46 // Read system config
47 let config: NixDataConfig = serde_json::from_reader(BufReader::new(File::open(SYSCONFIG)?))?;
48 Ok(config)
49 } else {
50 Err(anyhow!("No config file found"))
51 }
52}
53
54/// Writes the config struct to the config file in the user config directory (`~/.config/nix-data`).
55pub fn setuserconfig(config: NixDataConfig) -> Result<()> {
56 // Check if config directory exists
57 if !Path::new(&*CONFIGDIR).exists() {
58 fs::create_dir_all(&*CONFIGDIR)?;
59 }
60
61 // Write user config
62 let mut file = File::create(&*CONFIG)?;
63 file.write_all(serde_json::to_string_pretty(&config)?.as_bytes())?;
64 Ok(())
65}