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
use std::convert::From;

use anyhow::{anyhow, Context, Result};
use displaydoc::Display;
use git2::Remote;
use log::error;
use rayon::prelude::*;
use serde_derive::{Deserialize, Serialize};
use structopt::StructOpt;
use thiserror::Error;

use self::GitTaskError as E;
use crate::{args::GitOptions, tasks::ResolveEnv};

pub mod branch;
pub mod checkout;
pub mod cherry;
pub mod errors;
pub mod fetch;
pub mod merge;
pub mod prune;
pub mod status;
pub mod update;

pub const DEFAULT_REMOTE_NAME: &str = "origin";

#[derive(Debug, Default, Serialize, Deserialize)]
pub struct GitConfig {
    /// Path to download git repo to.
    pub path: String,
    /// Remote to set/update.
    pub remotes: Vec<GitRemote>,
    /// Branch to checkout when cloning/updating. Defaults to the current branch
    /// when updating, or the default branch of the first remote for
    /// cloning.
    pub branch: Option<String>,
    /// Prune local branches whose changes have already been merged upstream.
    #[serde(default = "prune_default")]
    pub prune: bool,
}

// Serde needs a function to set a default.
const fn prune_default() -> bool {
    false
}

// TODO(gib): Pass by reference instead.
#[allow(clippy::clippy::needless_pass_by_value)]
pub(crate) fn run(configs: Vec<GitConfig>) -> Result<()> {
    // TODO(gib): run them in parallel.
    // TODO(gib): continue even if one errors.
    let errors: Vec<_> = configs
        .par_iter()
        .map(|c| update::update(c))
        .filter_map(Result::err)
        .collect();
    if errors.is_empty() {
        Ok(())
    } else {
        for error in &errors {
            error!("{:?}", error);
        }
        let mut errors_iter = errors.into_iter();
        Err(errors_iter.next().ok_or(E::UnexpectedNone)?)
            .with_context(|| anyhow!("{:?}", errors_iter.collect::<Vec<_>>()))
    }
}

impl From<GitOptions> for GitConfig {
    fn from(item: GitOptions) -> Self {
        Self {
            path: item.git_path,
            remotes: vec![GitRemote {
                name: item.remote,
                push_url: None,
                fetch_url: item.git_url,
            }],
            branch: item.branch,
            prune: item.prune,
        }
    }
}

impl ResolveEnv for Vec<GitConfig> {
    fn resolve_env<F>(&mut self, env_fn: F) -> Result<()>
    where
        F: Fn(&str) -> Result<String>,
    {
        for config in self.iter_mut() {
            if let Some(branch) = config.branch.as_ref() {
                config.branch = Some(env_fn(branch)?);
            }
            config.path = env_fn(&config.path)?;
            for remote in &mut config.remotes {
                remote.name = env_fn(&remote.name)?;
                remote.push_url = if let Some(push_url) = &remote.push_url {
                    Some(env_fn(push_url)?)
                } else {
                    None
                };
                remote.fetch_url = env_fn(&remote.fetch_url)?;
            }
        }
        Ok(())
    }
}

#[derive(Debug, Default, StructOpt, Serialize, Deserialize)]
pub struct GitRemote {
    /// Name of the remote to set in git.
    pub name: String,
    /// URL to fetch from. Also used for pushing if `push_url` unset.
    pub fetch_url: String,
    /// URL to push to, defaults to fetch URL.
    pub push_url: Option<String>,
}

impl GitRemote {
    pub(crate) fn from(remote: &Remote) -> Result<Self> {
        let fetch_url = remote.url().ok_or(E::InvalidRemote)?.to_owned();

        let push_url = match remote.pushurl() {
            Some(url) if url != fetch_url => Some(url.to_owned()),
            _ => None,
        };

        Ok(Self {
            name: remote.name().ok_or(E::InvalidRemote)?.to_owned(),
            fetch_url,
            push_url,
        })
    }
}

#[derive(Error, Debug, Display)]
/// Errors thrown by this file.
pub enum GitTaskError {
    /// Remote un-named, or invalid UTF-8 name.
    InvalidRemote,
    /// Unexpected None in option.
    UnexpectedNone,
}