wgx731's Technical Blog

Programmer @ National University Of Singapore.

Playing With HOOK

| Comments

What is git hook?

According to git documentation:

A feature that fire off custom scripts when certain important actions occur, including client side and server side.

Learning from master omer on Saturday’s workshop, we can use hook to do automated deployment, his approach is to create a separate bare repository in the hosting server and when push received trigger the script to do deployment. Whereas in my opinion, if you host your repository on github or Bitbucket, you can also use the POST hook service from them to do automatic deployment.

If you are using Bitbucket, and here is the documentation on Bitbucket POST hook, it’s quite useful. But I think it lacks of some example. We are using PHP to receive the POST data, it took us quite some time to figure out that the POST json data is actually in $_POST['payload'], which is not pointed out in the documentation.

Below is an skeleton file that you can use for your auto-deployment as well:

[deploy.php]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?php
if (isset($_POST["payload"])) {
    $payload = json_decode($_POST["payload"], true);
    // only deploy for master branch
    if ($payload["commits"][0]["branch"] == "master") {
        try {
            // only deploy when you see deploy command - store in $deployCommand
            $deploy = strpos($payload["commits"][0]["message"], $deployCommand);
            if ($deploy !== false) {
                // finish what you need to do for deployment
                echo "Deployed. :D \n";
            }
        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }
    else {
        echo "Latest commit not from master branch, not deploying. \n";
    }
}
else {
    echo"Missing payload.\n";
}
?>

Sadly at last we need to switch back to Github with no administrator access for the repository, besides that we need to focus on the assignment itself, so I don’t think we will continue on this auto-deployment tool as it’s just a tool, anyway it’s a good practice for us at least.

Wish it helps you as well. Thank you very much.

Comments