{"id":19217072,"url":"https://github.com/8ctopus/git-hook","last_synced_at":"2025-05-12T23:48:18.925Z","repository":{"id":109058335,"uuid":"257314084","full_name":"8ctopus/git-hook","owner":"8ctopus","description":"Automatically deploy your git pushes to any server","archived":false,"fork":false,"pushed_at":"2024-07-26T14:31:01.000Z","size":130,"stargazers_count":4,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"master","last_synced_at":"2024-11-05T12:27:45.624Z","etag":null,"topics":["deployment","git","gitea","github","php","webhook"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/8ctopus.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2020-04-20T14:54:13.000Z","updated_at":"2024-08-28T14:49:03.000Z","dependencies_parsed_at":"2023-07-07T10:33:20.577Z","dependency_job_id":null,"html_url":"https://github.com/8ctopus/git-hook","commit_stats":null,"previous_names":["8ctopus/gitea-hook"],"tags_count":18,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/8ctopus%2Fgit-hook","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/8ctopus%2Fgit-hook/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/8ctopus%2Fgit-hook/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/8ctopus%2Fgit-hook/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/8ctopus","download_url":"https://codeload.github.com/8ctopus/git-hook/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":223836285,"owners_count":17211326,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["deployment","git","gitea","github","php","webhook"],"created_at":"2024-11-09T14:20:00.747Z","updated_at":"2024-11-09T14:20:01.440Z","avatar_url":"https://github.com/8ctopus.png","language":"PHP","readme":"# git hook\n\n[![packagist](https://poser.pugx.org/8ctopus/git-hook/v)](https://packagist.org/packages/8ctopus/git-hook)\n[![downloads](https://poser.pugx.org/8ctopus/git-hook/downloads)](https://packagist.org/packages/8ctopus/git-hook)\n[![min php version](https://poser.pugx.org/8ctopus/git-hook/require/php)](https://packagist.org/packages/8ctopus/git-hook)\n[![license](https://poser.pugx.org/8ctopus/git-hook/license)](https://packagist.org/packages/8ctopus/git-hook)\n[![tests](https://github.com/8ctopus/git-hook/actions/workflows/tests.yml/badge.svg)](https://github.com/8ctopus/git-hook/actions/workflows/tests.yml)\n![code coverage badge](https://raw.githubusercontent.com/8ctopus/git-hook/image-data/coverage.svg)\n![lines of code](https://raw.githubusercontent.com/8ctopus/git-hook/image-data/lines.svg)\n\nAutomate deployment for git pushes to [GitHub](https://github.com) and [Gitea](https://gitea.io) using webhooks.\n\nAutomatically push your git repository changes to any website.\n\n## demo\n\n- git clone the repository\n- start a local php development server: `php -S localhost:80 demo.php`\n- run the curl request which simulates the webhook request\n\n```sh\ncurl \\\n    --request POST \\\n    --header \"content-type: application/json\" \\\n    --header \"X-HUB-SIGNATURE-256: 2d8e4a6f3114e41f09a65195b2d69b5844e7a1a9284cdb2671354568304dd7a6\" \\\n    --data '{\"ref\":\"refs/heads/master\", \"before\":\"fc7fc95de2d998e0b41e17cfc3442836bbf1c7c9\", \"after\": \"fc7fc95de2d998e0b41e17cfc3442836bbf1c7c9\", \"total_commits\":1, \"repository\":{\"name\": \"site\"}}' \\\n    http://localhost/\n```\n\n## install\n\n    composer require 8ctopus/git-hook\n\n## GitHub usage\n\n- Create a new page such as this one in a public part of your website (in this example `https://example.com/api/myhook/index.php`)\n\n```php\nuse Apix\\Log\\Logger\\File;\nuse HttpSoft\\ServerRequest\\ServerRequestCreator;\nuse Oct8pus\\GitHubHook;\n\n// assuming script is in DOCUMENT_ROOT/public/api/myhook/index.php\n$documentRoot = __DIR__ . '/../../..';\n\nrequire_once $documentRoot . '/vendor/autoload.php';\n\n$commands = [\n    // repository name eg. https://github.com/8ctopus/site\n    'site' =\u003e [\n        // directory in which commands will be executed\n        'path' =\u003e $documentRoot,\n        'commands' =\u003e [\n            // adjust to your flavor\n            '/usr/bin/git pull',\n            '/usr/local/bin/composer install --no-interaction --no-dev',\n        ],\n    ],\n];\n\n// the logger is optional but provides useful information (any PSR-3 logger will do)\n// to use this logger, composer require 8ctopus/apix-log\n$logger = new File(sys_get_temp_dir() . '/git-hook-' . date('Y-m-d-His') . '.log');\n\ntry {\n    $logger-\u003einfo('Git hook...');\n\n    $request = ServerRequestCreator::createFromGlobals($_SERVER, $_FILES, $_COOKIE, $_GET, $_POST);\n\n    (new GitHubHook($request, $commands, 'SAME_SECRET_KEY_AS_IN_GITHUB_ADMIN', $logger))\n        -\u003erun();\n\n    $logger-\u003enotice('Git hook - OK');\n} catch (Exception $exception) {\n    if ($exception-\u003egetCode() !== 0) {\n        // informs the webhook that the command failed\n        http_response_code($exception-\u003egetCode());\n\n        // REMOVE ME IN PRODUCTION\n        echo $exception-\u003egetMessage();\n    }\n}\n```\n\n- In the GitHub project, go to `Settings` \u003e `Webhooks` \u003e `Add webhook`.\n- Set `Payload URL` to `https://example.com/api/myhook/`\n- Set `Content type` to `application/json`\n- Set `Secret` using a strong password (same as in the script `SAME_SECRET_KEY_AS_IN_GITHUB_ADMIN`)\n- Set `Just the push event`\n- Check `Active`\n- Click `Add Webhook`\n- Once added, click on it and scroll to the bottom to check the first delivery. If the first delivery succeeded you are all set. If it failed, review the response error and click `Redeliver` once you think you fixed it.\n\n_Note_: Also read the important notes below.\n\n## Gitea usage\n\n- Create a new page such as this one in a public part of your website (in this example `https://example.com/api/myhook/index.php`)\n\n```php\ndeclare(strict_types=1);\n\nuse Apix\\Log\\Logger\\File;\nuse HttpSoft\\ServerRequest\\ServerRequestCreator;\nuse Oct8pus\\GiteaHook;\n\n// assuming script is in DOCUMENT_ROOT/public/api/myhook/index.php\n$documentRoot = __DIR__ . '/../../..';\n\nrequire_once $documentRoot . '/vendor/autoload.php';\n\n$commands = [\n    'site' =\u003e [\n        'path' =\u003e $documentRoot,\n        'commands' =\u003e [\n            // adjust to your flavor\n            '/usr/bin/git pull',\n            '/usr/local/bin/composer install --no-interaction --no-dev',\n        ],\n    ],\n];\n\n// the logger is optional but provides useful information (any PSR-3 logger will do)\n// to use this logger, composer require 8ctopus/apix-log\n$logger = new File(sys_get_temp_dir() . '/git-hook-' . date('Y-m-d-His') . '.log');\n\ntry {\n    $logger-\u003einfo('Git hook...');\n\n    $request = ServerRequestCreator::createFromGlobals($_SERVER, $_FILES, $_COOKIE, $_GET, $_POST);\n\n    (new GiteaHook($request, $commands, 'SAME_SECRET_KEY_AS_IN_GITEA_ADMIN', $logger))\n        -\u003erun();\n\n    $logger-\u003enotice('Git hook - OK');\n} catch (Exception $exception) {\n    if ($exception-\u003egetCode() !== 0) {\n        // informs the webhook that the command failed\n        http_response_code($exception-\u003egetCode());\n\n        // REMOVE ME IN PRODUCTION\n        echo $exception-\u003egetMessage();\n    }\n}\n```\n\n- update your gitea configuration in order to allow to send webhooks to your domain\n\n```ini\n[webhook]\nSKIP_TLS_VERIFY = false\nALLOWED_HOST_LIST = example.com\n```\n\n- In the Gitea project, go to `Settings`, select `Gitea` from `Add webhook`.\n- Set `Target URL` to `https://example.com/api/myhook/`\n- Set `HTTP Method` to `POST`\n- Set `Post Content Type` to `application/json`\n- Set `Secret` using a strong password (same as in the script `SAME_SECRET_KEY_AS_IN_GITEA_ADMIN`)\n- Set `Trigger On` to `Push Events`\n- Set `Branch filter` to `master` or any branch you want to trigger the script\n- Check `Active`\n- Click `Add Webhook`\n- Once added, click on it and scroll to the bottom and click `Test Delivery`\n- If the delivery succeeds you are all set. If it fails, go to the server and check the log.\n\n## important notes for both github and gitea\n\n_Note_: for git pulls to work using user `www-data` (the apache typically runs under that user), you probably will need to:\n\n- make sure the upstream is set, so git knows where to pull from\n\n```\ngit branch --set-upstream-to=origin/master master\n```\n\n- make sure user `www-data` is the owner of the git repository. If not, you will get the error message\n\n```\n[2023-05-05 16:23:21] ERROR fatal: detected dubious ownership in repository at '...'\n```\n\n_Note_: If you are concerned about weaker security, you can consider giving user `www-data` permissions to run git as another user such as `ubuntu`. This way, your webserver files can be owned by `ubuntu` and `www-data` can only read them. I'm not security specialist, so be warned.\n\n```\nsudo -H -u ubuntu -- /usr/bin/git pull;\n```\n\n~~_Note_: for git pulls to work using user `www-data` (the apache processes typically run under that user), you probably will need to:~~\n\n~~- include the user and password (must be url encoded) inside the git remote url~~\n\n```diff\n- git remote set-url origin https://user:password@example.com/gitea/site.git\n```\n\n## callbacks\n\nCallbacks can be implemented per command or for every command:\n\n```php\n$commands = [\n    'site' =\u003e [\n        'path' =\u003e $path,\n        'commands' =\u003e [\n            'git status' =\u003e commandCallback(...),\n            'composer install --no-interaction',\n        ],\n        'afterExec' =\u003e globalCallback(...),\n    ],\n];\n```\n\nBoth callbacks have the same signature\n\n```php\nfunction callback(?LoggerInterface $logger, string $command, string $stdout, string $stderr, string $status) : bool\n```\n\nReturning false aborts the deployment\n\n## debugging\n\nThe deployment script can be easily debugged locally using [ngrok](https://ngrok.com/).\n\n- run ngrok `ngrok http 80`\n- update the `Payload URL` for Github or `Target URL` for Gitea to the ngrok address, similar to this one `https://6daf-31-218-13-51.ngrok-free.app`\n- run the php local server `php -S localhost:80 demo.php`\n- start visual studio code debugging and set a breakpoint in `demo.php`\n- resend the webhook request\n\n## clean code\n\n    composer fix(-risky)\n\n## phpstan\n\n    composer phpstan\n\n## phpmd\n\n    composer phpmd\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2F8ctopus%2Fgit-hook","html_url":"https://awesome.ecosyste.ms/projects/github.com%2F8ctopus%2Fgit-hook","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2F8ctopus%2Fgit-hook/lists"}