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
use std::{
    fs,
    path::{Path, PathBuf},
};

use anyhow::{Context, Result};
use displaydoc::Display;
use git2::Repository;
use log::{debug, error, info, trace};
use rayon::prelude::*;
use thiserror::Error;
use walkdir::WalkDir;

use self::GenerateGitError as E;
use super::GENERATED_PRELUDE_COMMENT;
use crate::{
    args::GenerateGitConfig,
    tasks::{
        git::{GitConfig, GitRemote},
        task::Task,
        ResolveEnv,
    },
};

pub fn run(generate_git_configs: &[GenerateGitConfig]) -> Result<()> {
    let errors: Vec<_> = generate_git_configs
        .par_iter()
        .map(|config| run_single(config))
        .filter_map(Result::err)
        .collect();
    if errors.is_empty() {
        Ok(())
    } else {
        for error in &errors {
            error!("{:?}", error);
        }
        let first_error = errors.into_iter().next().ok_or(E::UnexpectedNone)?;
        Err(first_error)
    }
}

pub fn run_single(generate_git_config: &GenerateGitConfig) -> Result<()> {
    debug!(
        "Generating git config for: {path}",
        path = generate_git_config.path.display()
    );
    let mut git_task = Task::from(&generate_git_config.path)?;
    debug!("Existing git config: {:?}", git_task);
    let mut git_configs = Vec::new();
    for path in find_repos(
        &generate_git_config.search_paths,
        generate_git_config.excludes.as_ref(),
    ) {
        git_configs.push(parse_git_config(
            &path,
            generate_git_config.prune,
            &generate_git_config.remote_order,
        )?);
    }
    // TODO(gib): keep old branch names.
    git_configs.sort_unstable_by(|c1, c2| c1.path.cmp(&c2.path));
    let toml_configs = git_configs
        .into_iter()
        .map(toml::Value::try_from)
        .collect::<Result<Vec<_>, _>>()?;
    git_task.config.data = Some(toml_configs.into());
    debug!("New git config: {:?}", git_task);
    let mut serialized_task = GENERATED_PRELUDE_COMMENT.to_owned();
    serialized_task.push_str(&toml::to_string_pretty(&git_task.config)?);
    trace!("New toml file: <<<{}>>>", serialized_task);
    fs::write(&generate_git_config.path, serialized_task)?;
    info!(
        "Git repo layout generated for task '{}' and written to '{:?}'",
        git_task.name, generate_git_config.path
    );
    Ok(())
}

// False-positives on Vec::new(), see https://github.com/rust-lang/rust-clippy/issues/3410
#[allow(clippy::use_self)]
impl ResolveEnv for Vec<GenerateGitConfig> {
    fn resolve_env<F>(&mut self, env_fn: F) -> Result<()>
    where
        F: Fn(&str) -> Result<String>,
    {
        for config in self.iter_mut() {
            config.path = PathBuf::from(env_fn(&config.path.to_string_lossy())?);

            let mut new_search_paths = Vec::new();
            for search_path in &config.search_paths {
                new_search_paths.push(PathBuf::from(env_fn(&search_path.to_string_lossy())?));
            }
            config.search_paths = new_search_paths;

            if let Some(excludes) = config.excludes.as_ref() {
                let mut new_excludes = Vec::new();
                for exclude in excludes {
                    new_excludes.push(env_fn(exclude)?);
                }
                config.excludes = Some(new_excludes);
            }
        }
        Ok(())
    }
}

fn find_repos(search_paths: &[PathBuf], excludes: Option<&Vec<String>>) -> Vec<PathBuf> {
    let mut repo_paths = Vec::new();
    for path in search_paths {
        trace!("Searching in '{}'", &path.display());
        for entry in WalkDir::new(path)
            .into_iter()
            .filter_entry(|e| {
                if let Some(ex) = excludes {
                    let s = e.path().to_str().unwrap_or("");
                    for exclude in ex {
                        if s.contains(exclude) {
                            return false;
                        }
                    }
                    true
                } else {
                    true
                }
            })
            .filter_map(Result::ok)
            .filter(|e| e.file_type().is_dir() && e.file_name() == ".git")
        {
            trace!("Entry: {:?}", &entry);
            let mut repo_path = entry.into_path();
            repo_path.pop();
            repo_paths.push(repo_path);
        }
    }
    debug!("Found repo paths: {:?}", repo_paths);
    repo_paths
}

fn parse_git_config(path: &Path, prune: bool, remote_order: &[String]) -> Result<GitConfig> {
    let repo = Repository::open(&path)?;

    let mut sorted_remote_names = Vec::new();
    {
        let mut remote_names: Vec<String> = Vec::new();
        for opt_name in &repo.remotes()? {
            remote_names.push(opt_name.ok_or(E::InvalidUtf8)?.to_owned());
        }
        for order in remote_order {
            if let Some(pos) = remote_names.iter().position(|el| el == order) {
                sorted_remote_names.push(remote_names.remove(pos));
            }
        }
        sorted_remote_names.extend(remote_names.into_iter());
    }

    let mut remotes = Vec::new();
    for name in sorted_remote_names {
        remotes.push(GitRemote::from(
            &repo
                .find_remote(&name)
                .with_context(|| E::InvalidRemote { name })?,
        )?);
    }

    let config = GitConfig {
        path: path.to_string_lossy().to_string(),
        branch: None,
        remotes,
        prune,
    };
    trace!("Parsed GitConfig: {:?}", &config);
    Ok(config)
}

#[derive(Error, Debug, Display)]
/// Errors thrown by this file.
pub enum GenerateGitError {
    /// Invalid UTF-8.
    InvalidUtf8,
    /// Invalid remote '{name}'.
    InvalidRemote { name: String },
    /// Unexpected None in option.
    UnexpectedNone,
}