git-checks 1.0.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 super::super::*;

#[derive(Debug)]
/// Checks whether a file's executable permissions matches its contents.
///
/// Files which look executable but are not marked as such or vice versa are rejected.
pub struct CheckExecutablePermissions {
    extensions: Vec<String>,
}

impl CheckExecutablePermissions {
    /// Create a new check which checks for executable permissions.
    ///
    /// Files which end in the given extension are assumed to be executable.
    pub fn new<E: ToString>(extensions: &[E]) -> Self {
        CheckExecutablePermissions {
            extensions: extensions.iter().map(ToString::to_string).collect(),
        }
    }
}

impl Check for CheckExecutablePermissions {
    fn name(&self) -> &str {
        "check-executable-permissions"
    }

    fn check(&self, ctx: &CheckGitContext, commit: &Commit) -> Result<CheckResult> {
        let mut result = CheckResult::new();

        for diff in &commit.diffs {
            match diff.status {
                StatusChange::Added |
                StatusChange::Modified(_) => (),
                _ => continue,
            }

            // Ignore files which haven't changed their modes.
            if diff.old_mode == diff.new_mode {
                continue;
            }

            let is_executable = match diff.new_mode.as_str() {
                "100755" => true,
                "100644" => false,
                _ => continue,
            };

            let executable_ext =
                self.extensions.iter().any(|ext| diff.name.as_str().ends_with(ext));
            let looks_executable = if executable_ext {
                true
            } else {
                let cat_file = try!(ctx.git()
                    .arg("cat-file")
                    .arg("blob")
                    .arg(diff.new_blob.as_str())
                    .output()
                    .chain_err(|| "failed to contruct cat-file command"));
                let content = String::from_utf8_lossy(&cat_file.stdout);
                content.starts_with("#!/") || content.starts_with("#! /")
            };

            let err = match (is_executable, looks_executable) {
                (true, false) => {
                    Some("with executable permissions, but the file does not look executable")
                },
                (false, true) => {
                    Some("without executable permissions, but the file looks executable")
                },
                _ => None,
            };

            if let Some(msg) = err {
                result.add_error(format!("commit {} adds `{}` {}.",
                                         commit.sha1_short,
                                         diff.name,
                                         msg));
            }
        }

        Ok(result)
    }
}

#[cfg(test)]
mod tests {
    use super::CheckExecutablePermissions;
    use super::super::test::*;

    static BAD_TOPIC: &'static str = "6ad8d4932466efc57ecccd3c80def3737b5d7e9a";

    #[test]
    fn test_check_executable_permissions() {
        let check = CheckExecutablePermissions::new(&[".exe"]);
        let mut conf = GitCheckConfiguration::new();

        conf.add_check(&check);

        let result = test_check("test_check_executable_permissions", BAD_TOPIC, &conf);

        assert_eq!(result.warnings().len(), 0);
        assert_eq!(result.alerts().len(), 0);
        assert_eq!(result.errors().len(), 3);
        assert_eq!(result.errors()[0],
                   "commit 6ad8d49 adds `is-exec` with executable permissions, but the file does \
                    not look executable.");
        assert_eq!(result.errors()[1],
                   "commit 6ad8d49 adds `not-exec-shebang` without executable permissions, but \
                    the file looks executable.");
        assert_eq!(result.errors()[2],
                   "commit 6ad8d49 adds `not-exec.exe` without executable permissions, but the \
                    file looks executable.");
        assert_eq!(result.allowed(), false);
        assert_eq!(result.pass(), false);
    }
}