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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
/*!

[![Build status](https://ci.appveyor.com/api/projects/status/xlkq8rd73cla4ixw/branch/master?svg=true)](https://ci.appveyor.com/project/jaemk/self-update/branch/master)
[![Build Status](https://travis-ci.org/jaemk/self_update.svg?branch=master)](https://travis-ci.org/jaemk/self_update)
[![crates.io:clin](https://img.shields.io/crates/v/self_update.svg?label=self_update)](https://crates.io/crates/self_update)
[![docs](https://docs.rs/self_update/badge.svg)](https://docs.rs/self_update)


`self_update` provides updaters for updating rust executables in-place from various release
distribution backends.

```shell
self_update = "0.3"
```

## Usage

Update (replace) the current executable with the latest release downloaded
from `https://api.github.com/repos/jaemk/self_update/releases/latest`

```
#[macro_use] extern crate self_update;

fn update() -> Result<(), Box<::std::error::Error>> {
    let target = self_update::get_target()?;
    let status = self_update::backends::github::UpdateLatest::configure()?
        .repo_owner("jaemk")
        .repo_name("self_update")
        .target(&target)
        .bin_name("self_update_example")
        .show_download_progress(true)
        .current_version(cargo_crate_version!())
        .build()?
        .update()?;
    println!("Update status: `v{}`!", status.version());
    Ok(())
}
# fn main() { }
```

Run the above example to see `self_update` in action: `cargo run --example github`

Separate utilities are also exposed:

```
extern crate self_update;

fn update() -> Result<(), Box<::std::error::Error>> {
    let target = self_update::get_target()?;
    let releases = self_update::backends::github::ReleaseList::configure()
        .repo_owner("jaemk")
        .repo_name("self_update")
        .with_target(&target)
        .build()?
        .fetch()?;
    println!("found releases:");
    println!("{:#?}\n", releases);

    // get the first available release
    let asset = releases[0]
        .asset_for(&target).unwrap();

    let tmp_dir = self_update::TempDir::new_in(::std::env::current_dir()?, "self_update")?;
    let tmp_tarball_path = tmp_dir.path().join(&asset.name);
    let tmp_tarball = ::std::fs::File::open(&tmp_tarball_path)?;

    self_update::Download::from_url(&asset.download_url)
        .download_to(&tmp_tarball)?;

    self_update::Extract::from_source(&tmp_tarball_path)
        .archive(self_update::ArchiveKind::Tar)
        .encoding(self_update::EncodingKind::Gz)
        .extract_into(&tmp_dir.path())?;

    let tmp_file = tmp_dir.path().join("replacement_tmp");
    let bin_name = "self_update_bin";
    let bin_path = tmp_dir.path().join(bin_name);
    self_update::Move::from_source(&bin_path)
        .replace_using_temp(&tmp_file)
        .to_dest(&::std::env::current_exe()?)?;

    Ok(())
}
# fn main() { }
```

*/
extern crate serde_json;
extern crate reqwest;
extern crate tempdir;
extern crate flate2;
extern crate tar;
extern crate semver;

pub use tempdir::TempDir;

use std::fs;
use std::io;
use std::path;


#[macro_use] pub mod macros;
pub mod errors;
pub mod backends;

use errors::*;


/// Try to determine the current target triple.
///
/// Returns a target triple (e.g. `x86_64-unknown-linux-gnu` or `i686-pc-windows-msvc`) or an
/// `Error::Config` if the current config cannot be determined or is not some combination of the
/// following values:
/// `linux, mac, windows` -- `i686, x86, armv7` -- `gnu, musl, msvc`
///
/// * Errors:
///     * Unexpected system config
pub fn get_target() -> Result<String> {
    let arch_config = (cfg!(target_arch = "x86"), cfg!(target_arch = "x86_64"), cfg!(target_arch = "arm"));
    let arch = match arch_config {
        (true, _, _) => "i686",
        (_, true, _) => "x86_64",
        (_, _, true) => "armv7",
        _ => bail!(Error::Update, "Unable to determine target-architecture"),
    };

    let os_config = (cfg!(target_os = "linux"), cfg!(target_os = "macos"), cfg!(target_os = "windows"));
    let os = match os_config {
        (true, _, _) => "unknown-linux",
        (_, true, _) => "apple-darwin",
        (_, _, true) => "pc-windows",
        _ => bail!(Error::Update, "Unable to determine target-os"),
    };

    let s;
    let os = if cfg!(target_os = "macos") {
        os
    } else {
        let env_config = (cfg!(target_env = "gnu"), cfg!(target_env = "musl"), cfg!(target_env = "msvc"));
        let env = match env_config {
            (true, _, _) => "gnu",
            (_, true, _) => "musl",
            (_, _, true) => "msvc",
            _ => bail!(Error::Update, "Unable to determine target-environment"),
        };
        s = format!("{}-{}", os, env);
        &s
    };

    Ok(format!("{}-{}", arch, os))
}


/// Check if the latest version tag is greater than the current
pub fn should_update(current: &str, latest: &str) -> Result<bool> {
    use semver::Version;
    Ok(Version::parse(latest)? > Version::parse(current)?)
}


/// Flush a message to stdout and check if they respond `yes`
///
/// * Errors:
///     * Io flushing
///     * User entered anything other than Y/y
fn prompt_ok(msg: &str) -> Result<()> {
    print_flush!("{}", msg);

    let stdin = io::stdin();
    let mut s = String::new();
    stdin.read_line(&mut s)?;
    if s.trim().to_lowercase() != "y" {
        bail!(Error::Update, "Update aborted");
    }
    Ok(())
}


/// Status returned after updating
///
/// Wrapped `String`s are version tags
#[derive(Debug, Clone)]
pub enum Status {
    UpToDate(String),
    Updated(String),
}
impl Status {
    /// Return the version tag
    pub fn version(&self) -> &str {
        use Status::*;
        match *self {
            UpToDate(ref s) => s,
            Updated(ref s) => s,
        }
    }

    /// Returns `true` if `Status::UpToDate`
    pub fn uptodate(&self) -> bool {
        match *self {
            Status::UpToDate(_) => true,
            _ => false,
        }
    }

    /// Returns `true` if `Status::Updated`
    pub fn updated(&self) -> bool {
        match *self {
            Status::Updated(_) => true,
            _ => false,
        }
    }
}

impl std::fmt::Display for Status {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        use Status::*;
        match *self {
            UpToDate(ref s) => write!(f, "UpToDate({})", s),
            Updated(ref s) => write!(f, "Updated({})", s),
        }
    }
}


/// Supported archive formats
#[derive(Debug)]
pub enum ArchiveKind {
    Tar,
    Plain,
}


/// Supported encoding formats
#[derive(Debug)]
pub enum EncodingKind {
    Gz,
    Plain,
}


/// Extract contents of an encoded archive (e.g. tar.gz) file to a specified directory
///
/// * Errors:
///     * Io - opening files
///     * Io - gzip decoding
///     * Io - archive unpacking
#[derive(Debug)]
pub struct Extract<'a> {
    source: &'a path::Path,
    archive: ArchiveKind,
    encoding: EncodingKind,
}
impl<'a> Extract<'a> {
    pub fn from_source(source: &'a path::Path) -> Extract<'a> {
        Self {
            source: source,
            archive: ArchiveKind::Plain,
            encoding: EncodingKind::Plain,
        }
    }
    pub fn archive(&mut self, kind: ArchiveKind) -> &mut Self {
        self.archive = kind;
        self
    }
    pub fn encoding(&mut self, kind: EncodingKind) -> &mut Self {
        self.encoding = kind;
        self
    }
    pub fn extract_into(&self, into_dir: &path::Path) -> Result<()> {
        let source = fs::File::open(self.source)?;
        let archive: Box<io::Read> = match self.encoding {
            EncodingKind::Plain => Box::new(source),
            EncodingKind::Gz => {
                let reader = flate2::read::GzDecoder::new(source)?;
                Box::new(reader)
            },
        };
        match self.archive {
            ArchiveKind::Plain => (),
            ArchiveKind::Tar => {
                let mut archive = tar::Archive::new(archive);
                archive.unpack(into_dir)?;
            }
        };
        Ok(())
    }
}


/// Moves a file from the given path to the specified destination.
///
/// If `replace_using_temp` is provided, the destination file will be
/// replaced using the given temp path as a backup.
///
/// * Errors:
///     * Io - copying / renaming
#[derive(Debug)]
pub struct Move<'a> {
    source: &'a path::Path,
    temp: Option<&'a path::Path>,
}
impl<'a> Move<'a> {
    /// Specify source file
    pub fn from_source(source: &'a path::Path) -> Move<'a> {
        Self {
            source: source,
            temp: None,
        }
    }

    /// If specified and the destination file already exists, the destination
    /// file will be "safely" replaced using a temp path.
    /// The `temp` dir should must be explicitly provided since `replace` operations require
    /// files to live on the same filesystem.
    pub fn replace_using_temp(&mut self, temp: &'a path::Path) -> &mut Self {
        self.temp = Some(temp);
        self
    }

    /// Move source file to specified destination
    pub fn to_dest(&self, dest: &path::Path) -> Result<()> {
        match self.temp {
            None => {
                fs::rename(self.source, dest)?;
            }
            Some(temp) => {
                if dest.exists() {
                    fs::rename(dest, temp)?;
                    match fs::rename(self.source, dest) {
                        Err(e) => {
                            fs::rename(temp, dest)?;
                            return Err(Error::from(e))
                        }
                        Ok(_) => (),
                    };
                } else {
                    fs::rename(self.source, dest)?;
                }
            }
        };
        Ok(())
    }
}


/// Download things into files
#[derive(Debug)]
pub struct Download {
    show_progress: bool,
    url: String,
}
impl Download {
    /// Specify download url
    pub fn from_url(url: &str) -> Self {
        Self {
            show_progress: false,
            url: url.to_owned(),
        }
    }

    /// Toggle download progress bar
    pub fn show_progress(&mut self, b: bool) -> &mut Self {
        self.show_progress = b;
        self
    }

    /// Display a download progress bar, returning the size of the
    /// bar that needs to be cleared on the next run
    ///
    /// * Errors:
    ///     * Io flushing
    fn display_dl_progress(total_size: u64, bytes_read: u64, clear_size: usize) -> Result<usize> {
        let bar_width = 75;
        let ratio = bytes_read as f64 / total_size as f64;
        let percent = (ratio * 100.) as u8;
        let n_complete = (bar_width as f64 * ratio) as usize;
        let mut complete_bars = std::iter::repeat("=").take(n_complete).collect::<String>();
        if ratio != 1. { complete_bars.push('>'); }

        let clear_chars = std::iter::repeat("\x08").take(clear_size).collect::<String>();
        print_flush!("{}\r", clear_chars);

        let bar = format!("{percent: >3}% [{compl: <full_size$}] {total}kB", percent=percent, compl=complete_bars, full_size=bar_width, total=total_size/1000);
        print_flush!("{}", bar);

        Ok(bar.len())
    }

    /// Download the file behind the given `url` into the specified `dest`.
    /// Show a sliding progress bar if specified.
    /// If the resource doesn't specify a content-length, the progress bar will not be shown
    ///
    /// * Errors:
    ///     * `reqwest` network errors
    ///     * Unsuccessful response status
    ///     * Progress-bar errors
    ///     * Reading from response to `BufReader`-buffer
    ///     * Writing from `BufReader`-buffer to `File`
    pub fn download_to<T: io::Write>(&self, mut dest: T) -> Result<()> {
        use io::BufRead;

        set_ssl_vars!();
        let resp = reqwest::get(&self.url)?;
        let size = resp.headers()
            .get::<reqwest::header::ContentLength>()
            .map(|ct_len| **ct_len)
            .unwrap_or(0);
        if !resp.status().is_success() { bail!(Error::Update, "Download request failed with status: {:?}", resp.status()) }
        let show_progress = if size == 0 { false } else { self.show_progress };

        let mut bytes_read = 0;
        let mut clear_size = 0;
        let mut src = io::BufReader::new(resp);
        loop {
            if show_progress {
                clear_size = Self::display_dl_progress(size, bytes_read as u64, clear_size)?;
            }
            let n = {
                let mut buf = src.fill_buf()?;
                dest.write_all(&mut buf)?;
                buf.len()
            };
            if n == 0 { break; }
            src.consume(n);
            bytes_read += n;
        }
        if show_progress { println!(" ... Done"); }
        Ok(())
    }
}


#[cfg(test)]
mod tests {
    use super::*;
    use std::env;
    #[test]
    fn can_determine_target_arch() {
        let target = get_target();
        assert!(target.is_ok(), "{:?}", target);
        let target = target.unwrap();
        if let Ok(env_target) = env::var("TARGET") {
            assert_eq!(target, env_target);
        }
    }
}