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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
/*!
Simple functions intended to use in __Rust__ `build.rs` scripts for tasks which related to fetching from _HTTP_ and unrolling `.tar.gz` archives with precompiled binaries and etc.

```
use fetch_unroll::Fetch;

let pack_url = format!(
    concat!("{base}/{user}/{repo}/releases/download/",
            "{package}-{version}/{package}_{target}_{profile}.tar.gz"),
    base = "https://github.com",
    user = "katyo",
    repo = "aubio-rs",
    package = "libaubio",
    version = "0.5.0-alpha",
    target = "armv7-linux-androideabi",
    profile = "debug",
);

let dest_dir = "target/test_download";

// Fetching and unrolling archive
Fetch::from(pack_url)
    .unroll().strip_components(1).to(dest_dir)
    .unwrap();
```
 */

#![warn(
    clippy::all,
    clippy::pedantic,
    clippy::nursery,
    //clippy::cargo,
)]

use std::{
    error::Error as StdError,
    fmt::{Display, Formatter, Result as FmtResult},
    fs::{create_dir_all, remove_dir_all, remove_file, File},
    io::{copy, Cursor, Error as IoError, Read},
    path::{Path, PathBuf},
    result::Result as StdResult,
};

use libflate::gzip::Decoder as GzipDecoder;
use tar::{Archive as TarArchive, EntryType as TarEntryType};
use ureq::{get as http_get, Error as HttpError};

/// Result type
pub type Result<T> = StdResult<T, Error>;

/// Status type
///
/// The result without payload
pub type Status = Result<()>;

/// Error type
#[derive(Debug)]
pub enum Error {
    /// Generic HTTP error
    Http(String),

    /// Generic IO error
    Io(IoError),
}

impl StdError for Error {}

impl Display for Error {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        match self {
            Self::Http(error) => {
                "Http error: ".fmt(f)?;
                error.fmt(f)
            }
            Self::Io(error) => {
                "IO error: ".fmt(f)?;
                error.fmt(f)
            }
        }
    }
}

impl From<&HttpError> for Error {
    #[must_use]
    fn from(error: &HttpError) -> Self {
        // Map the error to our error type.
        Self::Http(match error {
            HttpError::Status(code, _) => {
                format!("Invalid status: {}", code)
            }
            HttpError::Transport(transport) => {
                format!("Transport error: {}", transport)
            }
        })
    }
}

impl From<IoError> for Error {
    #[must_use]
    fn from(error: IoError) -> Self {
        Self::Io(error)
    }
}

type Flag = u8;

const CREATE_DEST_PATH: Flag = 1 << 0;
const FORCE_OVERWRITE: Flag = 1 << 1;
const FIX_INVALID_DEST: Flag = 1 << 2;
const CLEANUP_ON_ERROR: Flag = 1 << 3;
const CLEANUP_DEST_DIR: Flag = 1 << 4;
const STRIP_WHEN_ALONE: Flag = 1 << 5;

const DEFAULT_SAVE_FLAGS: Flag =
    CREATE_DEST_PATH | FORCE_OVERWRITE | FIX_INVALID_DEST | CLEANUP_ON_ERROR;
const DEFAULT_UNROLL_FLAGS: Flag =
    CREATE_DEST_PATH | FIX_INVALID_DEST | CLEANUP_ON_ERROR | CLEANUP_DEST_DIR;

macro_rules! flag {
    // Get flag
    ($($var:ident).* [$key:ident]) => {
        ($($var).* & $key) == $key
    };

    // Set flag
    ($($var:ident).* [$key:ident] = $val:expr) => {
        if $val {
            $($var).* |= $key;
        } else {
            $($var).* &= !$key;
        }
    };
}

/// HTTP(S) fetcher
pub struct Fetch<R> {
    source: Result<R>,
}

#[allow(clippy::use_self)]
impl Fetch<()> {
    /// Fetch data from url
    pub fn from<U>(url: U) -> Fetch<impl Read>
    where
        U: AsRef<str>,
    {
        Fetch {
            source: http_fetch(url.as_ref()),
        }
    }
}

fn http_fetch(url: &str) -> Result<impl Read> {
    match http_get(url).call() {
        Ok(response) => Ok(response.into_reader()),
        Err(error) => {
            // Map the error to our error type.
            Err(Error::from(&error))
        }
    }
}

impl<R> Fetch<R>
where
    R: Read,
{
    /// Write fetched data to file
    pub fn save(self) -> Save<impl Read> {
        Save::from(self.source)
    }

    /// Unroll fetched archive
    pub fn unroll(self) -> Unroll<impl Read> {
        Unroll::from(self.source)
    }
}

/// File writer
pub struct Save<R> {
    source: Result<R>,
    options: SaveOptions,
}

struct SaveOptions {
    flags: Flag,
}

impl Default for SaveOptions {
    fn default() -> Self {
        Self {
            flags: DEFAULT_SAVE_FLAGS,
        }
    }
}

impl<R> From<Result<R>> for Save<R> {
    fn from(source: Result<R>) -> Self {
        Self {
            source,
            options: SaveOptions::default(),
        }
    }
}

impl<R> Save<R> {
    /// Create destination directory when it doesn't exists
    ///
    /// Default: `true`
    pub const fn create_dest_path(mut self, flag: bool) -> Self {
        flag! { self.options.flags[CREATE_DEST_PATH] = flag }
        self
    }

    /// Overwrite existing file
    ///
    /// Default: `true`
    pub const fn force_overwrite(mut self, flag: bool) -> Self {
        flag! { self.options.flags[FORCE_OVERWRITE] = flag }
        self
    }

    /// Try to fix destination path when it is not a valid
    ///
    /// For example, when destination already exists
    /// and it is a directory, it will be removed
    ///
    /// Default: `true`
    pub const fn fix_invalid_dest(mut self, flag: bool) -> Self {
        flag! { self.options.flags[FIX_INVALID_DEST] = flag }
        self
    }

    /// Cleanup already written data when errors occurs
    ///
    /// Default: `true`
    pub const fn cleanup_on_error(mut self, flag: bool) -> Self {
        flag! { self.options.flags[CLEANUP_ON_ERROR] = flag }
        self
    }
}

impl<R> Save<R> {
    /// Save file to specified path
    ///
    /// # Errors
    /// - Destination directory does not exists when `create_dest_path` is not set
    /// - File already exist at destination directory when `force_overwrite` is not set
    /// - Destination path is not a file when `fix_invalid_dest` is not set
    pub fn to<D>(self, path: D) -> Status
    where
        R: Read,
        D: AsRef<Path>,
    {
        let Self { source, options } = self;

        let mut source = source?;

        let path = path.as_ref();

        if path.is_file() {
            if flag!(options.flags[FORCE_OVERWRITE]) {
                remove_file(path)?;
            } else {
                return Ok(());
            }
        } else if path.is_dir() {
            if flag!(options.flags[FIX_INVALID_DEST]) {
                remove_dir_all(path)?;
            }
        } else {
            // not exists
            if flag!(options.flags[CREATE_DEST_PATH]) {
                if let Some(path) = path.parent() {
                    create_dir_all(path)?;
                }
            }
        }

        copy(&mut source, &mut File::create(path)?)
            .map(|_| ())
            .or_else(|error| {
                if flag!(options.flags[CLEANUP_ON_ERROR]) && path.is_file() {
                    remove_file(path)?;
                }
                Err(error)
            })?;

        Ok(())
    }
}

/// Archive unroller
///
/// *NOTE*: Currently supported __.tar.gz__ archives only.
pub struct Unroll<R> {
    source: Result<R>,
    options: UnrollOptions,
}

struct UnrollOptions {
    strip_components: usize,
    flags: Flag,
}

impl Default for UnrollOptions {
    fn default() -> Self {
        Self {
            strip_components: 0,
            flags: DEFAULT_UNROLL_FLAGS,
        }
    }
}

impl<R> From<Result<R>> for Unroll<R> {
    fn from(source: Result<R>) -> Self {
        Self {
            source,
            options: UnrollOptions::default(),
        }
    }
}

impl<R> Unroll<R> {
    /// Create destination directory when it doesn't exists
    ///
    /// Default: `true`
    pub const fn create_dest_path(mut self, flag: bool) -> Self {
        flag! { self.options.flags[CREATE_DEST_PATH] = flag }
        self
    }

    /// Cleanup destination directory before extraction
    ///
    /// Default: `true`
    pub const fn cleanup_dest_dir(mut self, flag: bool) -> Self {
        flag! { self.options.flags[CLEANUP_DEST_DIR] = flag }
        self
    }

    /// Try to fix destination path when it is not a valid
    ///
    /// For example, when destination already exists
    /// and it is not a directory, it will be removed
    ///
    /// Default: `true`
    pub const fn fix_invalid_dest(mut self, flag: bool) -> Self {
        flag! { self.options.flags[FIX_INVALID_DEST] = flag }
        self
    }

    /// Cleanup already extracted data when errors occurs
    ///
    /// Default: `true`
    pub const fn cleanup_on_error(mut self, flag: bool) -> Self {
        flag! { self.options.flags[CLEANUP_ON_ERROR] = flag }
        self
    }

    /// Strip the number of leading components from file names on extraction
    ///
    /// Default: `0`
    pub const fn strip_components(mut self, num_of_components: usize) -> Self {
        self.options.strip_components = num_of_components;
        self
    }

    /// Strip the leading components only when it's alone
    ///
    /// Default: `false`
    pub const fn strip_when_alone(mut self, flag: bool) -> Self {
        flag! { self.options.flags[STRIP_WHEN_ALONE] = flag }
        self
    }
}

impl<R> Unroll<R> {
    /// Extract contents to specified directory
    ///
    /// # Errors
    /// - Destination directory does not exists when `create_dest_path` is not set
    /// - Destination directory is not empty when `cleanup_dest_dir` is not set
    /// - Destination path is not a directory when `fix_invalid_dest` is not set
    /// - Required number of path components cannot be stripped  when `strip_when_alone` is not set
    pub fn to<D>(self, path: D) -> Status
    where
        R: Read,
        D: AsRef<Path>,
    {
        let Self { source, options } = self;

        let source = source?;

        let path = path.as_ref();
        let mut dest_already_exists = false;

        if path.is_dir() {
            dest_already_exists = true;

            if flag!(options.flags[CLEANUP_DEST_DIR]) {
                remove_dir_entries(path)?;
            }
        } else if path.is_file() {
            //dest_already_exists = true;

            if flag!(options.flags[FIX_INVALID_DEST]) {
                remove_file(path)?;

                if flag!(options.flags[CREATE_DEST_PATH]) {
                    create_dir_all(path)?;
                }
            }
        } else {
            // not exists
            if flag!(options.flags[CREATE_DEST_PATH]) {
                create_dir_all(path)?;
            }
        }

        unroll_archive_to(source, &options, path).or_else(|error| {
            if flag!(options.flags[CLEANUP_ON_ERROR]) && path.is_dir() {
                if dest_already_exists {
                    remove_dir_entries(path)?;
                } else {
                    remove_dir_all(path)?;
                }
            }
            Err(error)
        })
    }
}

fn unroll_archive_to<R>(source: R, options: &UnrollOptions, destin: &Path) -> Status
where
    R: Read,
{
    let mut decoder = GzipDecoder::new(source)?;

    if options.strip_components < 1 {
        let mut archive = TarArchive::new(decoder);
        archive.unpack(destin)?;
        Ok(())
    } else {
        let mut decoded_data = Vec::new();
        decoder.read_to_end(&mut decoded_data)?;

        let strip_components = if flag!(options.flags[STRIP_WHEN_ALONE]) {
            let mut archive = TarArchive::new(Cursor::new(&decoded_data));
            options
                .strip_components
                .min(count_common_components(&mut archive)?)
        } else {
            options.strip_components
        };

        let mut archive = TarArchive::new(Cursor::new(decoded_data));
        let entries = archive.entries()?;

        for entry in entries {
            let mut entry = entry?;
            let type_ = entry.header().entry_type();

            {
                let entry_path = entry.path()?;

                match type_ {
                    TarEntryType::Directory => {
                        let stripped_path = entry_path
                            .iter()
                            .skip(strip_components)
                            .collect::<PathBuf>();
                        if stripped_path.iter().count() < 1 {
                            continue;
                        }
                        let dest_path = destin.join(stripped_path);

                        //create_dir_all(dest_path);
                        entry.unpack(dest_path)?;
                    }
                    TarEntryType::Regular => {
                        let strip_components = strip_components.min(entry_path.iter().count() - 1);
                        let stripped_path = entry_path
                            .iter()
                            .skip(strip_components)
                            .collect::<PathBuf>();
                        let dest_path = destin.join(stripped_path);

                        entry.unpack(dest_path)?;
                    }
                    _ => println!("other: {:?}", entry_path),
                }
            }
        }

        Ok(())
    }
}

fn count_common_components<R>(archive: &mut TarArchive<R>) -> StdResult<usize, IoError>
where
    R: Read,
{
    let mut common_ancestor = None;

    for entry in archive.entries()? {
        let entry = entry?;
        let entry_path = entry.path()?;

        match entry.header().entry_type() {
            TarEntryType::Directory | TarEntryType::Regular => {
                if common_ancestor.is_none() {
                    common_ancestor = Some(entry_path.to_path_buf());
                } else {
                    let common_ancestor = common_ancestor.as_mut().unwrap();

                    *common_ancestor = common_ancestor
                        .iter()
                        .zip(entry_path.iter())
                        .take_while(|(common_component, entry_component)| {
                            common_component == entry_component
                        })
                        .map(|(common_component, _)| common_component)
                        .collect();
                }
            }
            _ => (),
        }
    }

    Ok(common_ancestor.map_or(0, |path| path.iter().count()))
}

fn remove_dir_entries(path: &Path) -> StdResult<(), IoError> {
    for entry in path.read_dir()? {
        let path = entry?.path();
        if path.is_file() {
            remove_file(path)?;
        } else {
            remove_dir_all(path)?;
        }
    }
    Ok(())
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn github_archive_new() {
        let src_url = format!(
            "{base}/{user}/{repo}/archive/{ver}.tar.gz",
            base = "https://github.com",
            user = "katyo",
            repo = "fluidlite",
            ver = "1.2.0",
        );

        let dst_dir = "target/test_archive_new";

        // Fetching and unrolling archive (new way)
        Fetch::from(src_url)
            .unroll()
            .strip_components(1)
            .strip_when_alone(true)
            .to(dst_dir)
            .unwrap();

        //std::fs::remove_dir_all(dst_dir).unwrap();
    }
}