8ctopus/git-hook 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

8ctopus/git-hook

Composer 安装命令:

composer require 8ctopus/git-hook

包简介

Automate deployment for git pushes to GitHub and Gitea

README 文档

README

packagist downloads min php version license tests code coverage badge lines of code

Automate deployment for git pushes to GitHub and Gitea using webhooks.

Automatically push your git repository changes to any website.

demo

  • git clone the repository
  • start a local php development server: php -S localhost:80 demo.php
  • run the curl request which simulates the webhook request
curl \
    --request POST \
    --header "content-type: application/json" \
    --header "X-HUB-SIGNATURE-256: 2d8e4a6f3114e41f09a65195b2d69b5844e7a1a9284cdb2671354568304dd7a6" \
    --data '{"ref":"refs/heads/master", "before":"fc7fc95de2d998e0b41e17cfc3442836bbf1c7c9", "after": "fc7fc95de2d998e0b41e17cfc3442836bbf1c7c9", "total_commits":1, "repository":{"name": "site"}}' \
    http://localhost/

install

composer require 8ctopus/git-hook

GitHub usage

  • 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)
use Apix\Log\Logger\File;
use HttpSoft\ServerRequest\ServerRequestCreator;
use Oct8pus\GitHubHook;

// assuming script is in DOCUMENT_ROOT/public/api/myhook/index.php
$documentRoot = __DIR__ . '/../../..';

require_once $documentRoot . '/vendor/autoload.php';

$commands = [
    // repository name eg. https://github.com/8ctopus/site
    'site' => [
        // directory in which commands will be executed
        'path' => $documentRoot,
        'commands' => [
            // adjust to your flavor
            '/usr/bin/git pull',
            '/usr/local/bin/composer install --no-interaction --no-dev',
        ],
    ],
];

// the logger is optional but provides useful information (any PSR-3 logger will do)
// to use this logger, composer require 8ctopus/apix-log
$logger = new File(sys_get_temp_dir() . '/git-hook-' . date('Y-m-d-His') . '.log');

try {
    $logger->info('Git hook...');

    $request = ServerRequestCreator::createFromGlobals($_SERVER, $_FILES, $_COOKIE, $_GET, $_POST);

    (new GitHubHook($request, $commands, 'SAME_SECRET_KEY_AS_IN_GITHUB_ADMIN', $logger))
        ->run();

    $logger->notice('Git hook - OK');
} catch (Exception $exception) {
    if ($exception->getCode() !== 0) {
        // informs the webhook that the command failed
        http_response_code($exception->getCode());

        // REMOVE ME IN PRODUCTION
        echo $exception->getMessage();
    }
}
  • In the GitHub project, go to Settings > Webhooks > Add webhook.
  • Set Payload URL to https://example.com/api/myhook/
  • Set Content type to application/json
  • Set Secret using a strong password (same as in the script SAME_SECRET_KEY_AS_IN_GITHUB_ADMIN)
  • Set Just the push event
  • Check Active
  • Click Add Webhook
  • 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.

Note: Also read the important notes below.

Gitea usage

  • 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)
declare(strict_types=1);

use Apix\Log\Logger\File;
use HttpSoft\ServerRequest\ServerRequestCreator;
use Oct8pus\GiteaHook;

// assuming script is in DOCUMENT_ROOT/public/api/myhook/index.php
$documentRoot = __DIR__ . '/../../..';

require_once $documentRoot . '/vendor/autoload.php';

$commands = [
    'site' => [
        'path' => $documentRoot,
        'commands' => [
            // adjust to your flavor
            '/usr/bin/git pull',
            '/usr/local/bin/composer install --no-interaction --no-dev',
        ],
    ],
];

// the logger is optional but provides useful information (any PSR-3 logger will do)
// to use this logger, composer require 8ctopus/apix-log
$logger = new File(sys_get_temp_dir() . '/git-hook-' . date('Y-m-d-His') . '.log');

try {
    $logger->info('Git hook...');

    $request = ServerRequestCreator::createFromGlobals($_SERVER, $_FILES, $_COOKIE, $_GET, $_POST);

    (new GiteaHook($request, $commands, 'SAME_SECRET_KEY_AS_IN_GITEA_ADMIN', $logger))
        ->run();

    $logger->notice('Git hook - OK');
} catch (Exception $exception) {
    if ($exception->getCode() !== 0) {
        // informs the webhook that the command failed
        http_response_code($exception->getCode());

        // REMOVE ME IN PRODUCTION
        echo $exception->getMessage();
    }
}
  • update your gitea configuration in order to allow to send webhooks to your domain
[webhook]
SKIP_TLS_VERIFY = false
ALLOWED_HOST_LIST = example.com
  • In the Gitea project, go to Settings, select Gitea from Add webhook.
  • Set Target URL to https://example.com/api/myhook/
  • Set HTTP Method to POST
  • Set Post Content Type to application/json
  • Set Secret using a strong password (same as in the script SAME_SECRET_KEY_AS_IN_GITEA_ADMIN)
  • Set Trigger On to Push Events
  • Set Branch filter to master or any branch you want to trigger the script
  • Check Active
  • Click Add Webhook
  • Once added, click on it and scroll to the bottom and click Test Delivery
  • If the delivery succeeds you are all set. If it fails, go to the server and check the log.

important notes for both github and gitea

Note: for git pulls to work using user www-data (the apache typically runs under that user), you probably will need to:

  • make sure the upstream is set, so git knows where to pull from
git branch --set-upstream-to=origin/master master
  • make sure user www-data is the owner of the git repository. If not, you will get the error message
[2023-05-05 16:23:21] ERROR fatal: detected dubious ownership in repository at '...'

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.

sudo -H -u ubuntu -- /usr/bin/git pull;

Note: for git pulls to work using user www-data (the apache processes typically run under that user), you probably will need to:

- include the user and password (must be url encoded) inside the git remote url

- git remote set-url origin https://user:password@example.com/gitea/site.git

callbacks

Callbacks can be implemented per command or for every command:

$commands = [
    'site' => [
        'path' => $path,
        'commands' => [
            'git status' => commandCallback(...),
            'composer install --no-interaction',
        ],
        'afterExec' => globalCallback(...),
    ],
];

Both callbacks have the same signature

function callback(?LoggerInterface $logger, string $command, string $stdout, string $stderr, string $status) : bool

Returning false aborts the deployment

debugging

The deployment script can be easily debugged locally using ngrok.

  • run ngrok ngrok http 80
  • 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
  • run the php local server php -S localhost:80 demo.php
  • start visual studio code debugging and set a breakpoint in demo.php
  • resend the webhook request

clean code

composer fix(-risky)

phpstan

composer phpstan

phpmd

composer phpmd

8ctopus/git-hook 适用场景与选型建议

8ctopus/git-hook 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 148 次下载、GitHub Stars 达 3, 最近一次更新时间为 2023 年 05 月 09 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「git」 「github」 「HOOK」 「deployment」 「webhook」 「gitea」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 8ctopus/git-hook 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 8ctopus/git-hook 我们能提供哪些服务?
定制开发 / 二次开发

基于 8ctopus/git-hook 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 148
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 3
  • 点击次数: 23
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 3
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2023-05-09