Skip to main content

iphone_cli/
paths.rs

1//! Where iph keeps its files.
2
3use std::path::PathBuf;
4
5pub fn home() -> PathBuf {
6    std::env::var_os("HOME")
7        .or_else(|| std::env::var_os("USERPROFILE"))
8        .map(PathBuf::from)
9        .unwrap_or_else(|| PathBuf::from("."))
10}
11
12/// Sockets, logs and the operation record. `IPH_STATE_DIR` overrides it (tests).
13/// `~/Library/Application Support/iph` on macOS, `%LOCALAPPDATA%\iph` on Windows.
14pub fn state_dir() -> PathBuf {
15    if let Some(dir) = std::env::var_os("IPH_STATE_DIR") {
16        return PathBuf::from(dir);
17    }
18    if cfg!(windows) {
19        return std::env::var_os("LOCALAPPDATA")
20            .map(PathBuf::from)
21            .unwrap_or_else(|| home().join("AppData/Local"))
22            .join("iph");
23    }
24    home().join("Library/Application Support/iph")
25}
26
27/// `config.toml` and personal scripts. `IPH_CONFIG_DIR` overrides it (tests).
28/// `~/.config/iph` on macOS, `%APPDATA%\iph` on Windows.
29pub fn config_dir() -> PathBuf {
30    if let Some(dir) = std::env::var_os("IPH_CONFIG_DIR") {
31        return PathBuf::from(dir);
32    }
33    if cfg!(windows) {
34        return std::env::var_os("APPDATA")
35            .map(PathBuf::from)
36            .unwrap_or_else(|| home().join("AppData/Roaming"))
37            .join("iph");
38    }
39    home().join(".config/iph")
40}
41
42/// Developer disk images fetched when no Xcode copy is around.
43pub fn ddi_cache() -> PathBuf {
44    state_dir().join("ddi")
45}
46
47pub fn socket(udid: &str) -> PathBuf {
48    state_dir().join(format!("{udid}.sock"))
49}
50
51pub fn daemon_pid(udid: &str) -> PathBuf {
52    state_dir().join(format!("{udid}.pid"))
53}
54
55pub fn daemon_log(udid: &str) -> PathBuf {
56    state_dir().join(format!("{udid}.log"))
57}
58
59/// The Focus `iph dnd on` replaced with Do Not Disturb on this phone, for `off`.
60pub fn dnd_record(udid: &str) -> PathBuf {
61    state_dir().join(format!("{udid}.dnd.json"))
62}
63
64pub fn config_file() -> PathBuf {
65    config_dir().join("config.toml")
66}
67
68pub fn personal_scripts() -> PathBuf {
69    config_dir().join("scripts")
70}
71
72/// Create a directory only the user can enter. On Windows the folders under
73/// the user's profile are private already.
74pub fn ensure_private_dir(dir: &std::path::Path) -> std::io::Result<()> {
75    std::fs::create_dir_all(dir)?;
76    #[cfg(unix)]
77    {
78        use std::os::unix::fs::PermissionsExt;
79        std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))?;
80    }
81    Ok(())
82}
83
84/// Open options for a file only the user can read (0600 on macOS).
85pub fn private_file() -> std::fs::OpenOptions {
86    #[allow(unused_mut)]
87    let mut options = std::fs::OpenOptions::new();
88    #[cfg(unix)]
89    {
90        use std::os::unix::fs::OpenOptionsExt;
91        options.mode(0o600);
92    }
93    options
94}