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
//! Things to do.

use crate::{
    environment as e, git, packages, state::State, Data, Facts, FileSystem, Opts, SystemUnit,
    Timestamp, UnitAllocator, UnitId,
};
use anyhow::Error;
use directories::BaseDirs;
use serde::Deserialize;
use std::collections::HashMap;
use std::fmt;
use std::path::Path;

#[macro_use]
mod macros;
mod copy_dir;
mod download;
mod download_and_run;
mod from_db;
mod git_sync;
mod install;
mod link;
mod link_dir;
mod only_for;

use self::copy_dir::CopyDir;
use self::download::Download;
use self::download_and_run::DownloadAndRun;
use self::from_db::FromDb;
use self::git_sync::GitSync;
use self::install::Install;
use self::link::Link;
use self::link_dir::LinkDir;
use self::only_for::OnlyFor;

/// What should happen after a system has been translated.
pub enum Translation<'a> {
    /// Keep the current system.
    Keep,
    /// Discard the current system.
    Discard,
    /// Expand and discard the current system into the given collection of systems.
    Expand(&'a [System]),
}

macro_rules! system_impl {
    ($($name:ident,)*) => {
        impl System {
            pub fn translate(&self) -> Translation<'_> {
                use self::System::*;

                match self {
                    $($name(system) => system.translate(),)*
                }
            }

            /// Get the id of this system.
            pub fn id(&self) -> Option<&str> {
                use self::System::*;

                match self {
                    $($name(system) => system.id(),)*
                }
            }

            /// Get all things that this system depends on.
            pub fn requires(&self) -> &[String] {
                use self::System::*;

                match self {
                    $($name(system) => system.requires(),)*
                }
            }

            /// Apply changes for this system.
            #[allow(unused)]
            pub fn apply<E>(&self, input: $crate::system::SystemInput<E>)
                -> Result<Vec<$crate::system::SystemUnit>, Error>
            where
                E: Copy + $crate::environment::Environment,
            {
                use anyhow::{Context as _, anyhow};
                use self::System::*;

                let res = match self {
                    $($name(system) => system.apply(input),)*
                };

                res.with_context(|| anyhow!("Failed to run system: {:?}", self))
            }
        }

        impl fmt::Display for System {
            fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
                match *self {
                    $(
                    System::$name(ref system) => {
                        if let Some(id) = system.id() {
                            write!(fmt, "{}: {}", id, system)
                        } else {
                            system.fmt(fmt)
                        }
                    }
                    )*
                }
            }
        }
    }
}

#[derive(Deserialize, Debug, PartialEq, Eq)]
#[serde(tag = "type")]
pub enum System {
    #[serde(rename = "copy-dir")]
    CopyDir(CopyDir),
    #[serde(rename = "link-dir")]
    LinkDir(LinkDir),
    #[serde(rename = "install")]
    Install(Install),
    #[serde(rename = "download-and-run")]
    DownloadAndRun(DownloadAndRun),
    #[serde(rename = "download")]
    Download(Download),
    #[serde(rename = "link")]
    Link(Link),
    #[serde(rename = "git-sync")]
    GitSync(GitSync),
    #[serde(rename = "only-for")]
    OnlyFor(OnlyFor),
    #[serde(rename = "from-db")]
    FromDb(FromDb),
}

system_impl![
    CopyDir,
    LinkDir,
    Install,
    DownloadAndRun,
    Download,
    Link,
    GitSync,
    OnlyFor,
    FromDb,
];

/// All inputs for a system.
#[derive(Clone, Copy)]
pub struct SystemInput<'a, 'f, E>
where
    E: e::Environment,
{
    /// The root directory of the project being built.
    pub root: &'a Path,
    /// Known base directories to use.
    pub base_dirs: Option<&'a BaseDirs>,
    /// Set of facts.
    pub facts: &'a Facts,
    /// Data loaded from hierarchy.
    pub data: &'a Data,
    /// Source of environment variables.
    pub environment: E,
    /// Detected primary package manager for the system.
    pub packages: &'a packages::Provider,
    /// Unit allocator to use.
    pub allocator: &'a UnitAllocator,
    /// File utilities.
    pub file_system: &'a FileSystem<'f>,
    /// State accessor.
    pub state: &'a State<'a>,
    /// Current time.
    pub now: Timestamp,
    /// Current optsion.
    pub opts: &'a Opts,
    /// The current git system.
    pub git_system: &'a dyn git::GitSystem,
}

/// Helper structure used to resolve dependencies.
#[derive(Default)]
pub enum Dependency<'a> {
    /// Transitive dependency, where we have to look up other systems to fully resolve.
    Transitive(&'a [String]),
    /// Direct dependency to another unit.
    Direct(UnitId),
    /// No dependencies.
    #[default]
    None,
}

impl<'a> Dependency<'a> {
    /// Resolve all unit dependencies for the current dependency.
    pub fn resolve(
        &self,
        systems: &HashMap<&'a str, Dependency<'a>>,
    ) -> impl IntoIterator<Item = crate::unit::Dependency> {
        use std::collections::VecDeque;

        let mut ids = Vec::new();

        let mut queue = VecDeque::new();
        queue.push_back(self);

        while let Some(dependency) = queue.pop_front() {
            match *dependency {
                Dependency::Transitive(requires) => {
                    for id in requires {
                        queue.extend(systems.get(id.as_str()));
                    }
                }
                Dependency::Direct(id) => ids.push(crate::unit::Dependency::Unit(id)),
                Dependency::None => continue,
            }
        }

        ids
    }
}