nixgreety/src/gather.rs

105 lines
2.6 KiB
Rust
Raw Normal View History

2025-02-21 17:34:31 +00:00
use std::{
fs::{read_dir, read_link, DirEntry},
path::{Path, PathBuf},
};
use crate::{Session, User};
#[derive(Debug)]
struct PasswdUser {
name: String,
uid: u32,
gid: u32,
gecos: String,
home: String,
shell: String,
}
pub fn gather_users() -> Vec<User> {
let passwd = std::fs::read_to_string("/etc/passwd").unwrap();
passwd
.lines()
.map(|line| {
let fields: Vec<&str> = line.split(":").collect();
let name = fields[0].to_owned();
let uid = fields[2].parse().unwrap();
let gid = fields[3].parse().unwrap();
let gecos = fields[4].to_owned();
let home = fields[5].to_owned();
let shell = fields[6].to_owned();
PasswdUser {
name,
uid,
gid,
gecos,
home,
shell,
}
})
.filter(|user| !user.shell.ends_with("nologin"))
.map(|user| User {
name: user.name,
home: user.home.into(),
shell: user.shell.into(),
})
.collect()
}
pub fn gather_sessions(user: &User) -> Vec<Session> {
let hm_profile = user.home.join(".local/state/nix/profiles/home-manager");
match hm_profile.exists() {
true => gather_hm_sessions(&hm_profile),
false => vec![Session {
name: String::from("Shell"),
path: user.shell.clone(),
}],
}
}
#[allow(clippy::ptr_arg)]
fn resolve_link(path: &PathBuf) -> PathBuf {
let mut location = path.clone();
while let Ok(next) = read_link(&location) {
let base_path = location.parent().unwrap();
let next_path = base_path.join(next);
location = next_path;
}
location
}
fn gather_hm_sessions(path: &PathBuf) -> Vec<Session> {
let generation = resolve_link(path);
let mut sessions = vec![Session {
name: String::from("Home Manager"),
path: generation,
}];
sessions.append(&mut gather_specialisations(&sessions[0]));
sessions
}
fn gather_specialisations(session: &Session) -> Vec<Session> {
let specialisation_path = session.path.join("specialisation");
if !specialisation_path.exists() {
return vec![];
}
read_dir(specialisation_path)
.unwrap()
.flatten()
.map(|entry| {
let path = resolve_link(&entry.path());
let name = entry
.path()
.file_name()
.unwrap()
.to_str()
.unwrap()
.to_owned();
Session { name, path }
})
.collect()
}