hostcraft_core/
platform.rs1use crate::error::{HostCraftError, Result};
2use crate::file;
3use crate::host::HostEntry;
4use std::path::{Path, PathBuf};
5
6pub fn get_hosts_path() -> Result<PathBuf> {
7 match std::env::consts::OS {
8 "windows" => {
9 let root = std::env::var("SystemRoot").unwrap_or_else(|_| "C:\\Windows".to_string());
10 Ok(PathBuf::from(root)
11 .join("System32")
12 .join("drivers")
13 .join("etc")
14 .join("hosts"))
15 }
16 "macos" | "linux" => Ok(PathBuf::from("/etc/hosts")),
17 other => Err(HostCraftError::UnsupportedPlatform(other.to_string())),
18 }
19}
20
21pub fn write_hosts_to(path: &Path, entries: &[HostEntry]) -> Result<()> {
22 file::write_file(path, entries).map_err(|e| {
23 if e.kind() == std::io::ErrorKind::PermissionDenied {
24 if cfg!(target_os = "windows") {
25 HostCraftError::PermissionDenied(format!(
26 "Permission denied: run as Administrator to modify '{}'",
27 path.display()
28 ))
29 } else {
30 HostCraftError::PermissionDenied(format!(
31 "Permission denied: run with sudo to modify '{}'",
32 path.display()
33 ))
34 }
35 } else {
36 HostCraftError::Io(e)
37 }
38 })
39}
40
41pub fn write_hosts(entries: &[HostEntry]) -> Result<()> {
42 write_hosts_to(&get_hosts_path()?, entries)
43}