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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
extern crate curl;
extern crate dirs;
extern crate flate2;
extern crate tar;

mod os_detect;

use std::io::Write;
use std::error::Error as StdError;


static ENV_INSTALL_DEST: &'static str = "VULKAN_INSTALL_DEST";
static ENV_REINSTALL: &'static str = "VULKAN_REINSTALL";
static ENV_KEEP_SOURCE: &'static str = "VULKAN_KEEP_SOURCE";

static SUCCESS_FILE_FLAG: &'static str = ".success";

type InnerError = (dyn std::error::Error + std::marker::Send + std::marker::Sync);


fn extract_inner_error<'a>(err: &'a std::io::Error) -> &'a InnerError {
    match err.get_ref() {
        Some(e) => { e }
        None => { err }
    }
}

pub enum Error {
    IO(std::io::Error),
    Tar(std::io::Error),
    Env(std::env::VarError),
    Curl(curl::Error),
    Unimplemented(String),
    NoHome
}
impl Error {
    pub fn new_tar(err: std::io::Error) -> Error {
        Error::Tar(err)
    }
}
impl std::error::Error for Error {}
impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
        let as_str = match self {
            Error::IO(e) => { format!("{}", e) }
            Error::Tar(e) => { format!("{}", extract_inner_error(e)) }
            Error::Env(e) => { format!("{}", e) }
            Error::Curl(e) => { format!("{}", e) }
            Error::Unimplemented(e) => { e.clone() }
            Error::NoHome => { "could not find/detect home directory for user".to_string() }
        };

        match self.source() {
            Some(c) => {
                write!(f, "{}: {}", c, as_str)
            }
            None => {
                write!(f, "{}", as_str)
            }
        }
    }
}
impl std::fmt::Debug for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
        write!(f, "{}", self)
    }
}
impl From<std::io::Error> for Error {
    fn from(e: std::io::Error) -> Error {
        Error::IO(e)
    }
}
impl From<curl::Error> for Error {
    fn from(e: curl::Error) -> Error {
        Error::Curl(e)
    }
}
impl From<std::env::VarError> for Error {
    fn from(e: std::env::VarError) -> Error {
        Error::Env(e)
    }
}

fn default_install_root() -> Result<std::path::PathBuf, Error> {
    let home = dirs::home_dir();
    match home {
        Some(h) => { Ok(h) }
        None => { Err(Error::NoHome) }
    }
}

pub fn get_install_root() -> Result<std::path::PathBuf, Error> {
    let mut root = match std::env::var(ENV_INSTALL_DEST) {
        Ok(p) => {
            let mut buf = std::path::PathBuf::new();
            buf.push(p);
            buf
        }
        Err(e) => {
            if std::env::VarError::NotPresent == e {
                default_install_root()?
            } else {
                return Err(e.into()); // bad juju, get out now
            }
        }
    };

    root.push(".vulkan_sdk");
    Ok(root)
}

fn get_tmp_file_path(ver: &String) -> Result<std::path::PathBuf, Error> {
    let mut file_dest = get_install_root()?;
    file_dest.push(os_detect::vk_versioned_filename(&ver));
    Ok(file_dest)
}

fn env_too_bool(key: &'static str) -> bool {
    let val = std::env::var(key).unwrap_or("".to_string());
    match val.as_str() {
        "1" | "true" => { true }
        _ => { false }
    }
}

fn colon_separate_env(key: &'static str, value: String) -> String {
    std::env::var(key).map(|v| format!("{}:{}", value, v)).unwrap_or(value)
}

pub struct SDK {
    version: String,
    fetch_url: String,
    dest: std::path::PathBuf,
}
impl SDK {
    pub fn with_version(ver: &String) -> Result<SDK, Error> {
        let mut dest = get_install_root()?;
        dest.push(ver);

        let fmt_url = SDK::make_fetch_url(ver);
        Ok(SDK {
            version: ver.clone(),
            fetch_url: fmt_url,
            dest: dest,
        })
    }

    fn fetch(&self, tmp_loc: &std::path::PathBuf) -> Result<(), Error> {
        // if the temp file exists, use that instead of downloading
        if tmp_loc.exists() {
            eprintln!("reusing existing source file: {}", tmp_loc.display());
            return Ok(());
        }

        eprintln!("fetching Vulkan SDK from: {}", &self.fetch_url);

        let mut file = std::fs::File::create(tmp_loc)?;
        let mut handle = curl::easy::Easy::new();
        handle.url(&self.fetch_url)?;

        { // scope to make the buffer sharing okay
            let mut tx = handle.transfer();
            tx.write_function(|data| {
                // allow this to panic on write failure -- nothing we can do
                let len = match file.write(data) {
                    Ok(l) => { l }
                    Err(e) => {
                        panic!("failed to write installation source: {}", e);
                    }
                };
                Ok(len)
            })?;
            tx.perform()?;
        }

        file.sync_all()?;
        Ok(())
    }

    pub fn check_if_installed(&self) -> bool {
        if !self.dest.exists() {
            return false;
        }

        let mut test = self.dest.clone();
        test.push(SUCCESS_FILE_FLAG);

        if !test.exists() {
            eprintln!("found dirty install in {}, reinstalling...", self.dest.display());
            return false
        }

        return true;
    }

    fn mark_installed(&self) -> Result<(), Error> {
        let mut test = self.dest.clone();
        test.push(SUCCESS_FILE_FLAG);

        std::fs::File::create(test).map(|_| Ok(()))?
    }

    fn install_gzip(&self, from: &std::path::PathBuf) -> Result<(), Error> {
        let tarball = flate2::read::GzDecoder::new(std::fs::File::open(from)?);
        let mut archive = tar::Archive::new(tarball);
        let entries = archive.entries().expect("could not get entries");

        for (_, entry) in entries.enumerate() {
            let mut file = entry.expect("could not get file from entry");
            let p = file.path().expect("could not get path from file");;

            // skip top-level directory
            let mut anc = p.ancestors();
            if let None = anc.next() { // next to skip self
                continue
            }
            if anc.count() < 2 {
                continue
            }

            // remove the leading directory from this file's output path
            let mut trimmed = p.components();
            trimmed.next(); // skip the then top-level directory

            // append the now-relative path to our destination and unpack
            let mut dest = self.dest.clone();
            dest.push(trimmed.as_path());
            file.unpack(&dest).expect("could not unpack");
        }

        Ok(())
    }

    pub fn install(&self) -> Result<(), Error> {
        let is_installed = self.check_if_installed();
        let reinstall = env_too_bool(ENV_REINSTALL);

        if is_installed && !reinstall {
            eprintln!("found existing Vulkan SDK installation at: {}",
                &self.dest.display());
            return Ok(());
        } else if is_installed && reinstall {
            // clean up the existing directory on reinstall
            std::fs::remove_dir_all(&self.dest)?;
        }

        eprintln!("installing Vulkan SDK v{} to: {}",
            &self.version, &self.dest.display());

        // pre-create any intermediate directories to the install dest
        std::fs::create_dir_all(&self.dest)?;

        eprintln!("starting fetch+install...");
        let tmp_file_loc = get_tmp_file_path(&self.version)?;
        self.fetch(&tmp_file_loc)?;

        let ext = os_detect::vk_extension();
        match ext.as_str() {
            "tar.gz" => {
                eprintln!("starting extraction...");
                self.install_gzip(&tmp_file_loc)?;
                eprintln!("finished extraction...");
            }
            "exe" => {
                return Err(Error::Unimplemented(
                    "Windows exe installation currently unsupported".to_string()));
            }
            _ => {
                return Err(Error::Unimplemented(
                    format!("installation of file type {} unimplemented", ext)));
            }
        }
        eprintln!("finished fetch+install...");
        eprintln!(" fetch+install...");

        if env_too_bool(ENV_KEEP_SOURCE) {
            eprintln!("INFO: keeping the source installation file: {}", tmp_file_loc.display());
        } else {
            std::fs::remove_file(&tmp_file_loc)?;
        }
        eprintln!("finished post-cleanup");
        self.mark_installed()
    }

    fn sdk_dir(&self) -> std::path::PathBuf {
        let mut result = self.dest.clone();
        result.push(os_detect::vulkan_sdk_dir());
        result
    }

    pub fn print_cargo_env(&self) {
        let sdk_path = self.sdk_dir();
        let sdk_path_str = sdk_path.display();
        //println!("cargo:rerun-if-changed={}", sdk_path_str);
        println!("cargo:rustc-env=VULKAN_SDK={}", sdk_path_str);
        println!("cargo:rustc-env=PATH={}",
            colon_separate_env("PATH", format!("{}/bin",sdk_path_str)));
        println!("cargo:rustc-env=DYLD_LIBRARY_PATH={}",
            colon_separate_env("DYLD_LIBRARY_PATH", format!("{}/lib",sdk_path_str)));

        os_detect::print_cargo_env(&sdk_path)
    }

    fn make_fetch_url(ver: &String) -> String {
        format!(
            "https://sdk.lunarg.com/sdk/download/{ver}/{os_short}/{file}?Human=true",
            ver=ver,
            os_short=os_detect::os_name(),
            file=os_detect::vk_versioned_filename(ver),
        )
    }
}

pub fn ensure(ver: String) -> Result<SDK, Error> {
    eprintln!("handling Vulkan SDK version: {}", &ver);

    let sdk = SDK::with_version(&ver)?;
    sdk.install()?;

    Ok(sdk)
}