forked from ArtSkills/common
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathGitBranchTrimShell.php
189 lines (164 loc) · 5.49 KB
/
GitBranchTrimShell.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
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
<?php
declare(strict_types=1);
namespace ArtSkills\Shell;
use ArtSkills\Error\InternalException;
use ArtSkills\Lib\Env;
use ArtSkills\Lib\Git;
use Cake\Console\Shell;
use Cake\Core\Configure;
use Cake\I18n\Time;
use Exception;
/**
* Чистилка старых (смерженных с мастером) веток.
* Запускается из шелла посредством наследования данного класса.
* Конфигурация:
* в app.php прописываем следующее:
* ```
* 'Git' => [
* 'dir' => 'Корневая попка с Git',
* 'branchDeleteInterval' => '-7 days', // через сколько удалять смерженную с мастером ветку
* ],
* ```
*/
class GitBranchTrimShell extends Shell
{
public const CONFIGURATION_NAME = 'Git';
public const DEFAULT_CONFIGURATION = [
'dir' => '',
'branchDeleteInterval' => '-7 days',
];
/**
* Из какой директории запускать
*
* @var string
*/
protected string $_fromDir = '';
/**
* Возраст удаляемых веток
*
* @var string
*/
protected string $_branchDeleteInterval = '-7 days';
/**
* Чистка старых веток
*
* @return void
* @throws Exception
*/
public function main()
{
$this->out("Start: " . date('Y-m-d H:i:s'));
$log = $this->_run();
$this->out(implode("\n", $log));
$this->out("Finish!");
}
/**
* Удаление старых неиспользуемых веток
*
* @return string[]
* @throws Exception
*/
private function _run(): array
{
$gitConfig = Configure::read(static::CONFIGURATION_NAME);
if (empty($gitConfig)) {
throw new InternalException('Не сконфигурирован Git');
}
$gitConfig += static::DEFAULT_CONFIGURATION;
if (empty($gitConfig['dir']) || !is_dir($gitConfig['dir'])) {
throw new InternalException('Не сконфигурирована Git рабочая папка');
}
$this->_fromDir = $gitConfig['dir'];
$this->_branchDeleteInterval = $gitConfig['branchDeleteInterval'];
$currentDir = getcwd();
$fromDir = $this->_fromDir();
if (!empty($fromDir)) {
// возможность запускать из любого места
// чтобы можно было работать с гитом, нужно переключиться в правильную папку
chdir($fromDir);
}
$git = $this->_git();
$currentBranch = $git->getCurrentBranchName();
if (empty($currentBranch)) {
throw new InternalException('Гит не инициализирован');
}
if ($currentBranch != Git::BRANCH_NAME_MASTER) {
if (!$git->checkout(Git::BRANCH_NAME_MASTER)) {
throw new InternalException('Не удалось переключиться на мастера');
}
}
$git->updateRefs();
$toDeleteTypes = [Git::BRANCH_TYPE_LOCAL];
if ($this->_canDeleteRemote()) {
array_unshift($toDeleteTypes, Git::BRANCH_TYPE_REMOTE);
}
$log = [];
foreach ($toDeleteTypes as $type) {
$log = array_merge($log, $this->_deleteMergedOldBranches($type, [$currentBranch]));
}
if ($currentBranch != Git::BRANCH_NAME_MASTER) {
$git->checkout($currentBranch);
}
if (!empty($fromDir)) {
chdir($currentDir);
}
return $log;
}
/**
* Где можно удалять удалённые(не локальные) ветки
*
* @return bool
*/
protected function _canDeleteRemote(): bool
{
return Env::isProduction();
}
/**
* Объект гита
*
* @return Git
*/
protected function _git(): Git
{
return Git::getInstance();
}
/**
* Из какой директории запускать
*
* @return string
*/
protected function _fromDir(): string
{
if (Env::isLocal() || Env::isUnitTest()) {
return '';
}
return $this->_fromDir;
}
/**
* подчищает старые неиспользуемые ветки
*
* @param string $type
* @param string[] $skipBranches
* @return string[] log
*/
protected function _deleteMergedOldBranches(string $type, array $skipBranches = []): array
{
$git = $this->_git();
$skipBranches = array_merge($skipBranches, [Git::BRANCH_NAME_MASTER, Git::BRANCH_NAME_HEAD]);
$mergedBranches = $git->getMergedBranches($type);
$deleteDateFrom = Time::parse($this->_branchDeleteInterval)->toDateString();
$log = [];
foreach ($mergedBranches as $branchName => $lastCommitDate) {
if ($lastCommitDate > $deleteDateFrom) {
continue;
}
if (in_array($branchName, $skipBranches)) {
$log[] = 'Skipped ' . $type . ' branch ' . $branchName . ' (is current or master)!';
} else {
$git->deleteBranch($branchName, $type);
$log[] = 'Deleted old merged ' . $type . ' branch ' . $branchName . ' (last commit date: ' . $lastCommitDate . ')!';
}
}
return $log;
}
}