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
use crate::describer::*;
use crate::detector::*;
use crate::downloader::*;
use crate::errors::*;
use crate::executor::*;
use crate::installer::*;
use crate::manifest::*;
use crate::resolver::*;
use crate::shimmer::*;
use crate::verifier::*;
use std::any::Any;
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use tracing::debug;

#[async_trait::async_trait]
pub trait Tool<'tool>:
    Send
    + Sync
    + Describable<'tool>
    + Detector<'tool>
    + Resolvable<'tool>
    + Downloadable<'tool>
    + Verifiable<'tool>
    + Installable<'tool>
    + Executable<'tool>
    + Shimable<'tool>
{
    fn as_any(&self) -> &dyn Any;

    fn get_manifest(&self) -> Result<&Manifest, ProtoError>;

    fn get_manifest_mut(&mut self) -> Result<&mut Manifest, ProtoError>;

    fn get_manifest_path(&self) -> PathBuf {
        self.get_tool_dir().join(MANIFEST_NAME)
    }

    fn get_tool_dir(&self) -> &Path;

    async fn before_setup(&mut self) -> Result<(), ProtoError> {
        Ok(())
    }

    async fn setup(&mut self, initial_version: &str) -> Result<bool, ProtoError> {
        self.before_setup().await?;

        // Resolve a semantic version
        let version = self.resolve_version(initial_version).await?;

        // Download the archive
        let download_path = self.get_download_path()?;

        self.download(&download_path, None).await?;

        // Verify the archive
        let checksum_path = self.get_checksum_path()?;

        self.download_checksum(&checksum_path, None).await?;
        self.verify_checksum(&checksum_path, &download_path).await?;

        // Install the tool
        let install_dir = self.get_install_dir()?;

        if self.install(&install_dir, &download_path).await? {
            self.find_bin_path().await?;

            // Create shims after paths are found
            self.setup_shims(true).await?;

            // Update the manifest
            {
                let default_version = self.get_default_version().map(|v| v.to_owned());

                self.get_manifest_mut()?
                    .insert_version(&version, default_version)?;
            }

            self.after_setup().await?;

            return Ok(true);
        }

        Ok(false)
    }

    async fn setup_shims(&mut self, force: bool) -> Result<(), ProtoError> {
        let is_outdated = { self.get_manifest_mut()?.shim_version != SHIM_VERSION };
        let do_create = force || is_outdated || env::var("CI").is_ok();

        if do_create {
            debug!(
                tool = self.get_id(),
                "Creating shims as they either do not exist, or are outdated"
            );

            let manifest = self.get_manifest_mut()?;
            manifest.shim_version = SHIM_VERSION;
            manifest.save()?;
        }

        self.create_shims(!do_create).await?;

        Ok(())
    }

    async fn is_setup(&mut self, initial_version: &str) -> Result<bool, ProtoError> {
        self.resolve_version(initial_version).await?;

        let install_dir = self.get_install_dir()?;

        debug!(
            tool = self.get_id(),
            install_dir = ?install_dir,
            "Checking if tool is installed",
        );

        if install_dir.exists() {
            self.find_bin_path().await?;

            if self.get_bin_path().is_ok() {
                debug!(
                    tool = self.get_id(),
                    install_dir = ?install_dir,
                    "Tool has already been installed",
                );

                self.setup_shims(false).await?;

                return Ok(true);
            }
        } else {
            debug!(tool = self.get_id(), "Tool has not been installed");
        }

        Ok(false)
    }

    async fn after_setup(&mut self) -> Result<(), ProtoError> {
        Ok(())
    }

    async fn cleanup(&mut self) -> Result<(), ProtoError> {
        debug!(
            tool = self.get_id(),
            "Cleaning up temporary files and downloads"
        );

        let download_path = self.get_download_path()?;
        let checksum_path = self.get_checksum_path()?;

        if download_path.exists() {
            let _ = fs::remove_file(download_path);
        }

        if checksum_path.exists() {
            let _ = fs::remove_file(checksum_path);
        }

        Ok(())
    }

    async fn before_teardown(&mut self) -> Result<(), ProtoError> {
        Ok(())
    }

    async fn teardown(&mut self) -> Result<bool, ProtoError> {
        self.before_teardown().await?;

        self.cleanup().await?;

        let install_dir = self.get_install_dir()?;

        if self.uninstall(&install_dir).await? {
            let version = self.get_resolved_version().to_owned();

            self.get_manifest_mut()?.remove_version(&version)?;

            self.after_teardown().await?;

            return Ok(true);
        }

        Ok(false)
    }

    async fn after_teardown(&mut self) -> Result<(), ProtoError> {
        Ok(())
    }
}

#[macro_export]
macro_rules! impl_tool {
    ($tool:ident) => {
        impl Tool<'_> for $tool {
            fn as_any(&self) -> &dyn Any {
                self
            }

            fn get_manifest(&self) -> Result<&Manifest, ProtoError> {
                self.manifest
                    .get_or_try_init(|| Manifest::load(self.get_manifest_path()))
            }

            fn get_manifest_mut(&mut self) -> Result<&mut Manifest, ProtoError> {
                {
                    // Ensure that the manifest has been initialized
                    self.get_manifest()?;
                }

                Ok(self.manifest.get_mut().unwrap())
            }

            fn get_tool_dir(&self) -> &Path {
                &self.base_dir
            }
        }
    };
}