Initial commit

This commit is contained in:
Pavel Shevaev 2023-10-23 15:13:23 +03:00
commit e8c9f95156
3 changed files with 130 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
tags

11
composer.json Normal file
View File

@ -0,0 +1,11 @@
{
"name": "bit/taskman_git",
"description": "taskman git utils",
"homepage": "https://git.bit5.ru/composer/taskman_git",
"require": {
"php": ">=7.4"
},
"autoload": {
"classmap": ["git.inc.php"]
}
}

118
git.inc.php Normal file
View File

@ -0,0 +1,118 @@
<?php
namespace taskman;
use Exception;
task('git_info', function()
{
list($rev_hash, $branch, $revision_number) = git_get_info();
$info = "==============GIT INFO==============\n"
. "$rev_hash - hash\n"
. "$branch - branch\n"
. "$revision_number - revision\n";
echo $info;
});
function git_do($repo, $action, &$out = NULL, $verbose = true)
{
$cli = "cd $repo && git $action";
if($verbose)
echo "Git CLI: $cli\n";
exec($cli, $out, $result);
if($verbose || $result !== 0)
echo implode("\n", $out)."\n";
if($result !== 0)
throw new Exception("Error executing command: $cli ($result)");
}
function git_is_repo($directory)
{
$output = [];
git_do($directory, "rev-parse --is-inside-work-tree", $output, false);
return !empty($output) && $output[0] === 'true';
}
function git_rev_from_commit_message($message)
{
// Regular expression pattern to extract the commit hash
$pattern = '/\b[0-9a-f]{7,40}\b/';
// Extract the commit hash from the message
preg_match($pattern, $message, $matches);
$commit_hash = $matches[0] ?? '';
return $commit_hash;
}
function get_git_last_remote_tag($repo)
{
$remote_tags = [];
git_do($repo, 'ls-remote --tags origin', $output, false);
foreach($output as $line)
{
$items = explode("\t", trim($line));
if(sizeof($items) < 2)
continue;
$tag_spec = $items[1];
if(str_ends_with($tag_spec, '^{}'))
continue;
$tag = str_replace('refs/tags/', '', $tag_spec);
$remote_tags[] = $tag;
}
return _get_last_version_tag($remote_tags);
}
function _get_last_version_tag(array $tags)
{
if(!$tags)
return false;
usort($tags, function ($tag1, $tag2) {
$version1 = str_replace('v', '', $tag1);
$version2 = str_replace('v', '', $tag2);
return version_compare($version1, $version2);
});
return end($tags);
}
class GitVersion
{
public $major;
public $minor;
public $patch;
static function parse($version_str)
{
$parts = explode('.', $version_str);
if(sizeof($parts) != 3)
throw new Exception("Invalid version string: $version_str");
$v = new GitVersion();
if($parts[0][0] === 'v')
$parts[0] = substr($parts[0], 1);
$v->major = (int)$parts[0];
$v->minor = (int)$parts[1];
$v->patch = (int)$parts[2];
return $v;
}
function bump($up_mode)
{
if($up_mode == 1)
++$this->patch;
else if($up_mode == 2)
{
++$this->minor;
$this->patch = 0;
}
else if($up_mode == 3)
{
++$this->major;
$this->minor = 0;
$this->patch = 0;
}
else
throw new Exception("Unsupported up mode: $up_mode");
}
function encode()
{
return 'v'.$this->major.'.'.$this->minor.'.'.$this->patch;
}
}