Require Specific Commit Message AWS Lambda on Push to Codecommit

1.2k views Asked by At

I am trying to enforce a commit to start with "BPSD-XXXXX" and can't figure out how to enforce this lambda function once pushed, but before the code is actually pushed to AWS Codecommit.

The lambda function below enforces the commit string but not until after the code is actually pushed. I have a trigger set up to Codecommit when code is pushed.

I realize the trigger is the issue, but is there a trigger I can put in that somehow checks the commit message before the full push actually happens? Or while the push is happening?

var aws = require('aws-sdk');
//aws.config.update({region:'us-east-2'});
var codecommit = new aws.CodeCommit({ apiVersion: '2015-04-13' });

exports.handler = function (event, context) {
    //console.log(JSON.stringify(event));
    for (var reference of event.Records[0].codecommit.references) {
        let commitId = reference.commit;
        let repo = event.Records[0].eventSourceARN.split(':').pop();
        console.log('commitId', commitId);
        console.log('repo', repo);
        codecommit.getCommit({ repositoryName: repo, commitId: commitId }, function (error, data) {
            if (error)
                throw error;

            console.log('message:', data.commit.message);
            if (!/^(BPSD-[0-9]+|Merge)/.test(data.commit.message))
                throw new Error("Your commit message is missing either a JIRA Issue ('BPSD-XXXX') or 'Merge'");
        });
    }
};

I want the code to not be pushed if the commit message doesn't contain "BPSD-XXXXX"

1

There are 1 answers

2
JohnB On BEST ANSWER

At the point of your lambda its already been uploaded. What you'll need to do is enforce commit hook at the point of committing which checks the commit message.This will likley be controlled in .git/hooks/commit-msg

These can be controlled either in each repo, or can be set as a Server-side commit hook.

Some links which should help:

https://git-scm.com/book/uz/v2/Customizing-Git-An-Example-Git-Enforced-Policy

https://gist.github.com/pgilad/5d7e4db725a906bd7aa7

A quick script that I found which could go in .git/hooks/commit-msg

#!/usr/bin/env bash
INPUT_FILE=$1
START_LINE=`head -n1 $INPUT_FILE`
PATTERN="^(MYPROJ)-[[:digit:]]+: "
if ! [[ "$START_LINE" =~ $PATTERN ]]; then
  echo "Bad commit message, see example: MYPROJ-123: commit message"
  exit 1
fi