1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
/*! [`BuiltinPlanner`]s and traits to create new types which can be used to plan out an [`InstallPlan`]

It's a [`Planner`]s job to construct (if possible) a valid [`InstallPlan`] for the host. Some planners are operating system specific, others are device specific.

[`Planner`]s contain their planner specific settings, typically alongside a [`CommonSettings`][crate::settings::CommonSettings].

[`BuiltinPlanner::default()`] offers a way to get the default builtin planner for a given host.

Custom Planners can also be used to create a platform, project, or organization specific install.

A custom [`Planner`] can be created:

```rust,no_run
use std::{error::Error, collections::HashMap};
use nix_installer::{
    InstallPlan,
    settings::{CommonSettings, InstallSettingsError},
    planner::{Planner, PlannerError},
    action::{Action, StatefulAction, base::CreateFile},
};

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct MyPlanner {
    pub common: CommonSettings,
}


#[async_trait::async_trait]
#[typetag::serde(name = "my-planner")]
impl Planner for MyPlanner {
    async fn default() -> Result<Self, PlannerError> {
        Ok(Self {
            common: CommonSettings::default().await?,
        })
    }

    async fn plan(&self) -> Result<Vec<StatefulAction<Box<dyn Action>>>, PlannerError> {
        Ok(vec![
            // ...

                CreateFile::plan("/example", None, None, None, "Example".to_string(), false)
                    .await
                    .map_err(PlannerError::Action)?.boxed(),
        ])
    }

    fn settings(&self) -> Result<HashMap<String, serde_json::Value>, InstallSettingsError> {
        let Self { common } = self;
        let mut map = std::collections::HashMap::default();

        map.extend(common.settings()?.into_iter());

        Ok(map)
    }
}

# async fn custom_planner_install() -> color_eyre::Result<()> {
let planner = MyPlanner::default().await?;
let mut plan = InstallPlan::plan(planner).await?;
match plan.install(None).await {
    Ok(()) => tracing::info!("Done"),
    Err(e) => {
        match e.source() {
            Some(source) => tracing::error!("{e}: {}", source),
            None => tracing::error!("{e}"),
        };
        plan.uninstall(None).await?;
    },
};

#    Ok(())
# }
```

*/
#[cfg(target_os = "linux")]
pub mod linux;
#[cfg(target_os = "macos")]
pub mod macos;
#[cfg(target_os = "linux")]
pub mod steam_deck;

use std::{collections::HashMap, string::FromUtf8Error};

use crate::{
    action::{ActionError, StatefulAction},
    error::HasExpectedErrors,
    settings::{CommonSettings, InstallSettingsError},
    Action, InstallPlan, NixInstallerError,
};

/// Something which can be used to plan out an [`InstallPlan`]
#[async_trait::async_trait]
#[typetag::serde(tag = "planner")]
pub trait Planner: std::fmt::Debug + Send + Sync + dyn_clone::DynClone {
    /// Instantiate the planner with default settings, if possible
    async fn default() -> Result<Self, PlannerError>
    where
        Self: Sized;
    /// Plan out the [`Action`]s for an [`InstallPlan`]
    async fn plan(&self) -> Result<Vec<StatefulAction<Box<dyn Action>>>, PlannerError>;
    /// The settings being used by the planner
    fn settings(&self) -> Result<HashMap<String, serde_json::Value>, InstallSettingsError>;
    /// A boxed, type erased planner
    fn boxed(self) -> Box<dyn Planner>
    where
        Self: Sized + 'static,
    {
        Box::new(self)
    }
}

dyn_clone::clone_trait_object!(Planner);

/// Planners built into this crate
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "cli", derive(clap::Subcommand))]
pub enum BuiltinPlanner {
    #[cfg(target_os = "linux")]
    /// A planner for Linux installs
    Linux(linux::Linux),
    /// A planner MacOS (Darwin) for installs
    #[cfg(target_os = "macos")]
    Macos(macos::Macos),
    /// A planner suitable for the Valve Steam Deck running SteamOS
    #[cfg(target_os = "linux")]
    SteamDeck(steam_deck::SteamDeck),
}

impl BuiltinPlanner {
    /// Heuristically determine the default planner for the target system
    pub async fn default() -> Result<Self, PlannerError> {
        use target_lexicon::{Architecture, OperatingSystem};
        match (Architecture::host(), OperatingSystem::host()) {
            #[cfg(target_os = "linux")]
            (Architecture::X86_64, OperatingSystem::Linux) => {
                Ok(Self::Linux(linux::Linux::default().await?))
            },
            #[cfg(target_os = "linux")]
            (Architecture::X86_32(_), OperatingSystem::Linux) => {
                Ok(Self::Linux(linux::Linux::default().await?))
            },
            #[cfg(target_os = "linux")]
            (Architecture::Aarch64(_), OperatingSystem::Linux) => {
                Ok(Self::Linux(linux::Linux::default().await?))
            },
            #[cfg(target_os = "macos")]
            (Architecture::X86_64, OperatingSystem::MacOSX { .. })
            | (Architecture::X86_64, OperatingSystem::Darwin) => {
                Ok(Self::Macos(macos::Macos::default().await?))
            },
            #[cfg(target_os = "macos")]
            (Architecture::Aarch64(_), OperatingSystem::MacOSX { .. })
            | (Architecture::Aarch64(_), OperatingSystem::Darwin) => {
                Ok(Self::Macos(macos::Macos::default().await?))
            },
            _ => Err(PlannerError::UnsupportedArchitecture(target_lexicon::HOST)),
        }
    }

    pub async fn from_common_settings(settings: CommonSettings) -> Result<Self, PlannerError> {
        let mut built = Self::default().await?;
        match &mut built {
            #[cfg(target_os = "linux")]
            BuiltinPlanner::Linux(inner) => inner.settings = settings,
            #[cfg(target_os = "linux")]
            BuiltinPlanner::SteamDeck(inner) => inner.settings = settings,
            #[cfg(target_os = "macos")]
            BuiltinPlanner::Macos(inner) => inner.settings = settings,
        }
        Ok(built)
    }

    pub async fn plan(self) -> Result<InstallPlan, NixInstallerError> {
        match self {
            #[cfg(target_os = "linux")]
            BuiltinPlanner::Linux(planner) => InstallPlan::plan(planner).await,
            #[cfg(target_os = "linux")]
            BuiltinPlanner::SteamDeck(planner) => InstallPlan::plan(planner).await,
            #[cfg(target_os = "macos")]
            BuiltinPlanner::Macos(planner) => InstallPlan::plan(planner).await,
        }
    }
    pub fn boxed(self) -> Box<dyn Planner> {
        match self {
            #[cfg(target_os = "linux")]
            BuiltinPlanner::Linux(i) => i.boxed(),
            #[cfg(target_os = "linux")]
            BuiltinPlanner::SteamDeck(i) => i.boxed(),
            #[cfg(target_os = "macos")]
            BuiltinPlanner::Macos(i) => i.boxed(),
        }
    }

    pub fn typetag_name(&self) -> &'static str {
        match self {
            #[cfg(target_os = "linux")]
            BuiltinPlanner::Linux(i) => i.typetag_name(),
            #[cfg(target_os = "linux")]
            BuiltinPlanner::SteamDeck(i) => i.typetag_name(),
            #[cfg(target_os = "macos")]
            BuiltinPlanner::Macos(i) => i.typetag_name(),
        }
    }

    pub fn settings(&self) -> Result<HashMap<String, serde_json::Value>, InstallSettingsError> {
        match self {
            #[cfg(target_os = "linux")]
            BuiltinPlanner::Linux(i) => i.settings(),
            #[cfg(target_os = "linux")]
            BuiltinPlanner::SteamDeck(i) => i.settings(),
            #[cfg(target_os = "macos")]
            BuiltinPlanner::Macos(i) => i.settings(),
        }
    }
}

/// An error originating from a [`Planner`]
#[derive(thiserror::Error, Debug)]
pub enum PlannerError {
    /// `nix-installer` does not have a default planner for the target architecture right now
    #[error("`nix-installer` does not have a default planner for the `{0}` architecture right now, pass a specific archetype")]
    UnsupportedArchitecture(target_lexicon::Triple),
    /// Error executing action
    #[error("Error executing action")]
    Action(
        #[source]
        #[from]
        ActionError,
    ),
    /// An [`InstallSettingsError`]
    #[error(transparent)]
    InstallSettings(#[from] InstallSettingsError),
    /// A MacOS (Darwin) plist related error
    #[error(transparent)]
    Plist(#[from] plist::Error),
    /// A Linux SELinux related error
    #[error("This installer doesn't yet support SELinux in `Enforcing` mode. If SELinux is important to you, please see https://github.com/DeterminateSystems/nix-installer/issues/124. You can also try again after setting SELinux to `Permissive` mode with `setenforce Permissive`")]
    SelinuxEnforcing,
    /// A UTF-8 related error
    #[error("UTF-8 error")]
    Utf8(#[from] FromUtf8Error),
    /// Custom planner error
    #[error("Custom planner error")]
    Custom(#[source] Box<dyn std::error::Error + Send + Sync>),
    #[error("NixOS already has Nix installed")]
    NixOs,
    #[error("`nix` is already a valid command, so it is installed")]
    NixExists,
}

impl HasExpectedErrors for PlannerError {
    fn expected<'a>(&'a self) -> Option<Box<dyn std::error::Error + 'a>> {
        match self {
            this @ PlannerError::UnsupportedArchitecture(_) => Some(Box::new(this)),
            PlannerError::Action(_) => None,
            PlannerError::InstallSettings(_) => None,
            PlannerError::Plist(_) => None,
            PlannerError::Utf8(_) => None,
            PlannerError::SelinuxEnforcing => Some(Box::new(self)),
            PlannerError::Custom(_) => None,
            this @ PlannerError::NixOs => Some(Box::new(this)),
            this @ PlannerError::NixExists => Some(Box::new(this)),
        }
    }
}