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
use std::io::Write;
use std::path::Path;
use failure::{Error, ResultExt};
use git2::{AutotagOption, FetchOptions, FetchPrune, RemoteCallbacks, Repository};
use git2::build::RepoBuilder;

use config::Config;
use github::GitHub;
use {Provider, Repo};

/// A driver for orchestrating the process of fetching a list of repositories
/// and then downloading each of them.
#[derive(Debug, Clone, PartialEq)]
pub struct Driver {
    config: Config,
}

impl Driver {
    /// Create a new `Driver` with the provided config.
    pub fn with_config(config: Config) -> Driver {
        Driver { config }
    }

    /// Download a list of all repositories from the `Provider`s found in the
    /// configuration file, then fetch any recent changes (running `git clone`
    /// if necessary).
    pub fn run(&self) -> Result<(), Error> {
        info!("Starting repository backup");

        let providers = get_providers(&self.config)?;
        let repos = self.get_repos_from_providers(&providers)?;
        self.update_repos(&repos)?;

        info!("Finished repository backup");
        Ok(())
    }

    /// Update the provided repositories.
    pub fn update_repos(&self, repos: &[Repo]) -> Result<(), UpdateFailure> {
        info!("Updating repositories");
        let mut errors = Vec::new();

        for repo in repos {
            if let Err(e) = self.update_repo(repo) {
                warn!("Updating {} failed, {}", repo.name, e);
                errors.push((repo.clone(), e));
            }
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(UpdateFailure { errors })
        }
    }

    fn update_repo(&self, repo: &Repo) -> Result<(), Error> {
        debug!("Updating {}", repo.full_name());
        let dest_dir = self.config.general.dest_dir.join(repo.full_name());

        if dest_dir.exists() {
            fetch_updates(&dest_dir, repo).context("`git fetch` failed")?;
        } else {
            clone_repo(&dest_dir, repo).context("`git clone` failed")?;
        }

        Ok(())
    }

    /// Iterate over the `Provider`s and collect all the repositories they've
    /// found into one big list.
    pub fn get_repos_from_providers(
        &self,
        providers: &[Box<Provider>],
    ) -> Result<Vec<Repo>, Error> {
        let mut repos = Vec::new();

        for provider in providers {
            info!("Fetching repositories from {}", provider.name());
            let found = provider
                .repositories()
                .context("Unable to fetch repositories")?;

            info!("Found {} repos from {}", found.len(), provider.name());
            repos.extend(found);
        }

        Ok(repos)
    }
}

fn clone_repo(dest_dir: &Path, repo: &Repo) -> Result<(), Error> {
    debug!("Cloning into {}", dest_dir.display());

    let mut builder = RepoBuilder::new();

    let mut fetch_opts = FetchOptions::new();
    fetch_opts
        .prune(FetchPrune::On)
        .download_tags(AutotagOption::All);

    if let Some(cb) = logging_cb(repo) {
        fetch_opts.remote_callbacks(cb);
    }

    builder
        .fetch_options(fetch_opts)
        .clone(&repo.url, dest_dir)?;
    Ok(())
}

/// If we are logging at `trace` level, get a `RemoteCallbacks` which will print
/// a progress message.
fn logging_cb<'a>(repo: &'a Repo) -> Option<RemoteCallbacks<'a>> {
    if log_enabled!(::log::Level::Trace) {
        let mut cb = RemoteCallbacks::new();
        let repo_name = repo.full_name();

        cb.transfer_progress(move |progress| {
            trace!(
                "{} downloaded {}/{} objects ({} bytes)",
                repo_name,
                progress.received_objects(),
                progress.total_objects(),
                progress.received_bytes()
            );
            true
        });
        Some(cb)
    } else {
        None
    }
}

fn fetch_updates(dest_dir: &Path, repo: &Repo) -> Result<(), Error> {
    let git_repo = Repository::open(dest_dir).context("Not a git repository")?;
    let mut remote = git_repo
        .find_remote("origin")
        .or_else(|_| git_repo.remote_anonymous("origin"))
        .context("The repo has no `origin` remote")?;

    let mut fetch_opts = FetchOptions::default();
    fetch_opts
        .prune(FetchPrune::On)
        .download_tags(AutotagOption::All);

    if let Some(cb) = logging_cb(repo) {
        fetch_opts.remote_callbacks(cb);
    }

    remote
        .download(&[], Some(&mut fetch_opts))
        .context("Download failed")?;

    if remote.stats().received_bytes() != 0 {
        let stats = remote.stats();
        if stats.local_objects() > 0 {
            debug!(
                "Received {} objects in {} bytes for {} (used {} local \
                 objects)",
                stats.indexed_objects(),
                stats.received_bytes(),
                repo.full_name(),
                stats.local_objects()
            );
        } else {
            debug!(
                "Received {} objects in {} bytes for {}",
                stats.indexed_objects(),
                stats.received_bytes(),
                repo.full_name()
            );
        }
    }

    remote.disconnect();

    // Update the references in the remote's namespace to point to the right
    // commits. This may be needed even if there was no packfile to download,
    // which can happen e.g. when the branches have been changed but all the
    // needed objects are available locally.
    remote.update_tips(None, true, AutotagOption::Unspecified, None)?;

    Ok(())
}

/// A wrapper around one or more failures during the updating process.
#[derive(Debug, Fail)]
#[fail(display = "One or more errors ecountered while updating repos")]
pub struct UpdateFailure {
    errors: Vec<(Repo, Error)>,
}

impl UpdateFailure {
    /// Print a "backtrace" for each error encountered.
    pub fn display<W: Write>(&self, writer: &mut W) -> Result<(), Error> {
        writeln!(
            writer,
            "There were {} errors updating repositories",
            self.errors.len()
        )?;

        for &(ref repo, ref err) in &self.errors {
            writeln!(writer, "Error: {} failed with {}", repo.full_name(), err)?;
            for cause in err.causes().skip(1) {
                writeln!(writer, "\tCaused By: {}", cause)?;
            }
        }

        Ok(())
    }
}

fn get_providers(cfg: &Config) -> Result<Vec<Box<Provider>>, Error> {
    let mut providers: Vec<Box<Provider>> = Vec::new();

    if let Some(gh_config) = cfg.github.as_ref() {
        let gh = GitHub::with_config(gh_config.clone());
        providers.push(Box::new(gh));
    }

    if providers.is_empty() {
        warn!("No providers found");
    }

    Ok(providers)
}