git-checks 2.2.0

Checks to run against a topic in git to enforce coding standards.
Documentation
// Copyright 2016 Kitware, Inc.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use crates::git_workarea::GitContext;

use context::CheckGitContext;

#[derive(Debug)]
/// A git context for a submodule for use within checks.
///
/// Checks which need to inspect submodules should use this to obtain a `GitContext` for the
/// submodule.
pub struct SubmoduleContext<'a> {
    /// The name of the submodule (usually the same as `path`).
    pub name: &'a str,
    /// The path of the submodule within the repository.
    pub path: &'a str,
    /// The clone URL for the submodule.
    pub url: &'a str,
    /// The branch the submodule tracks.
    pub branch: &'a str,

    /// The context to use to query the submodule.
    pub context: GitContext,
}

impl<'a> SubmoduleContext<'a> {
    /// Create submodule context for the given path.
    ///
    /// Returns `None` if the requisite information is not available within the context being used.
    pub fn new(ctx: &'a CheckGitContext, diff_path: &str) -> Option<Self> {
        ctx.submodule_config()
            .iter()
            // Extract the current path's configuration.
            .filter_map(|(name, config)| {
                config.get("url")
                    .and_then(|url| {
                        config.get("path")
                            .map(|path| (url, path))
                    })
                    .and_then(|(url, path)| {
                        if path == diff_path {
                            let branch = config.get("branch")
                                .map_or("master", |b| b.as_str());

                            Some((name, path, url, branch))
                        } else {
                            None
                        }
                    })
            })
            // We only care about the first instance which matches.
            .next()
            // Turn it into a SubmoduleContext.
            .map(|(name, path, url, branch)| {
                let gitdir = ctx.gitdir().join("modules").join(path);

                SubmoduleContext {
                    name: name,
                    path: path,
                    url: url,
                    branch: branch,

                    context: GitContext::new(gitdir),
                }
            })
    }
}