git-checks 3.5.2

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 impl_prelude::*;

#[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 considered to indicate an executable file.
    ///
    /// Really only intended for Windows where executable permissions do not exist.
    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<I>(extensions: I) -> Self
        where I: IntoIterator,
              I::Item: ToString,
    {
        Self {
            extensions: extensions.into_iter()
                .map(|e| e.to_string())
                .collect(),
        }
    }
}

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

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

        for diff in content.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 = 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!("{}adds `{}` {}.",
                                         commit_prefix(content),
                                         diff.name,
                                         msg));
            }
        }

        Ok(result)
    }
}

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

    const BAD_TOPIC: &str = "6ad8d4932466efc57ecccd3c80def3737b5d7e9a";
    const FIX_TOPIC: &str = "bea46a67f75380f1c17c25c7f89ffa9f47b27c06";

    #[test]
    fn test_check_executable_permissions() {
        let check = CheckExecutablePermissions::new(&[".exe"]);
        let result = run_check("test_check_executable_permissions", BAD_TOPIC, check);
        test_result_errors(result, &[
            "commit 6ad8d4932466efc57ecccd3c80def3737b5d7e9a adds `is-exec` with executable \
             permissions, but the file does not look executable.",
            "commit 6ad8d4932466efc57ecccd3c80def3737b5d7e9a adds `not-exec-shebang` without \
             executable permissions, but the file looks executable.",
            "commit 6ad8d4932466efc57ecccd3c80def3737b5d7e9a adds `not-exec.exe` without \
             executable permissions, but the file looks executable.",
        ]);
    }

    #[test]
    fn test_check_executable_permissions_topic() {
        let check = CheckExecutablePermissions::new(&[".exe"]);
        let result = run_topic_check("test_check_executable_permissions_topic", BAD_TOPIC, check);
        test_result_errors(result, &[
            "adds `is-exec` with executable permissions, but the file does not look \
             executable.",
            "adds `not-exec-shebang` without executable permissions, but the file looks \
             executable.",
            "adds `not-exec.exe` without executable permissions, but the file looks \
             executable.",
        ]);
    }

    #[test]
    fn test_check_executable_permissions_topic_fixed() {
        let check = CheckExecutablePermissions::new(&[".exe"]);
        run_topic_check_ok("test_check_executable_permissions_topic_fixed", FIX_TOPIC, check);
    }
}