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
//  Copyright (C) 2015 Steven Allen
//
//  This file is part of gazetta.
//
//  This program is free software: you can redistribute it and/or modify it under the terms of the
//  GNU General Public License as published by the Free Software Foundation version 3 of the
//  License.
//
//  This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
//  without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See
//  the GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License along with this program.  If
//  not, see <http://www.gnu.org/licenses/>.
//

use std::path::{Path, PathBuf};
use std::fs::{self, File};
use std::io;

use std::hash::Hasher;

use error::AnnotatedError;

/// Recursivly copy a directory.
///
/// Does not preserve permissions.
pub fn copy_recursive(src: &Path, dest: &Path) -> io::Result<()> {
    if fs::metadata(&src)?.is_dir() {
        copy_dir(src, dest)
    } else {
        copy_file(src, dest)
    }
}

fn copy_file(src: &Path, dest: &Path) -> io::Result<()> {
    io::copy(&mut File::open(&src)?, &mut File::create(&dest)?).map(|_| ())
}

fn copy_dir(src: &Path, dest: &Path) -> io::Result<()> {
    fs::create_dir(dest)?;
    for dir_entry in fs::read_dir(src)? {
        let dir_entry = dir_entry?;
        let file_name = dir_entry.file_name();
        let from = src.join(&file_name);
        let to = dest.join(&file_name);
        if exists(&to)? {
            return Err(io::Error::new(io::ErrorKind::AlreadyExists, "target path already exists"));
        }

        if dir_entry.file_type()?.is_dir() {
            copy_dir(&from, &to)?;
        } else {
            copy_file(&from, &to)?;
        }
    }
    Ok(())
}

/// Check if a file exists.
pub fn exists(path: &Path) -> io::Result<bool> {
    match fs::metadata(&path) {
        Ok(_) => Ok(true),
        Err(e) => {
            match e.kind() {
                io::ErrorKind::NotFound => Ok(false),
                _ => Err(e),
            }
        }
    }
}

/// Walk a file tree and return a sorted vector of paths.
pub fn walk_sorted(path: &Path) -> io::Result<Vec<PathBuf>> {
    let mut out = Vec::new();
    walk_into(path, &mut out)?;
    Ok(out)
}

fn walk_into(path: &Path, out: &mut Vec<PathBuf>) -> io::Result<()> {
    let mut files = fs::read_dir(path)?
        .map(|e| {
            let e = e?;
            Ok((e.path(), e.file_type()?.is_dir()))
        })
        .collect::<io::Result<Vec<_>>>()?;

    // Don't need to sort by whole path. We're walking in sort-order.
    files.sort_by(|a, b| a.0.file_name().unwrap().cmp(b.0.file_name().unwrap()));
    for (path, is_dir) in files {
        if is_dir {
            walk_into(&path, out)?;
        } else {
            out.push(path);
        }
    }
    Ok(())
}

pub struct StreamHasher<W, H> {
    hash: H,
    inner: W,
}
impl<W, H> StreamHasher<W, H>
    where H: Hasher,
          W: io::Write
{
    pub fn new(inner: W) -> Self
        where H: Default
    {
        StreamHasher {
            hash: H::default(),
            inner: inner,
        }
    }
    pub fn with_hasher(inner: W, hash: H) -> Self {
        StreamHasher {
            hash: hash,
            inner: inner,
        }
    }
    pub fn finish(&self) -> u64 {
        self.hash.finish()
    }
}
impl<W, H> io::Write for StreamHasher<W, H>
    where W: io::Write,
          H: Hasher
{
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        let size = self.inner.write(buf)?;
        self.hash.write(&buf[..size]);
        Ok(size)
    }
    fn flush(&mut self) -> io::Result<()> {
        self.inner.flush()
    }
}

/// Concatinate source paths into an output file.
pub fn concat<W, I>(paths: I, output: &mut W) -> Result<u64, AnnotatedError<io::Error>>
    where W: io::Write,
          I: IntoIterator,
          I::Item: AsRef<Path>
{
    let mut bytes = 0;
    for p in paths {
        let p = p.as_ref();
        bytes += try_annotate!(io::copy(&mut try_annotate!(File::open(p), p), output), p)
    }
    Ok(bytes)
}