GitParser.php 1.83 KB
Newer Older
Tomáš Pospíšil's avatar
errors  
Tomáš Pospíšil committed
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
<?php

namespace Praguebest\Tools;

use Nette\Utils\FileSystem;

final class GitParser
{

    public function getLastCommitMessage(): ?string
    {
        $dir = Dumper::getDirectory();

        $fileMessage = $dir . '/.git/COMMIT_EDITMSG';

        if ($dir && is_readable($fileMessage)) {
            return file_get_contents($fileMessage);
        }

        return null;
    }

    public function getBranches(): array
    {
        $dir = Dumper::getDirectory();
26
27
28
29
30
31
        $heads = $dir . '/.git/refs/heads';
        if (!is_dir($heads)) {
            return [];
        }

        $files = scandir($heads);
Tomáš Pospíšil's avatar
errors  
Tomáš Pospíšil committed
32
33
34
35
36

        $branches = [];

        if ($dir && is_array($files)) {
            foreach ($files as $file) {
37
38
                if ('.' !== $file && '..' !== $file && $file !== $this->getBranchName()) {
                    $branches[] = $file;
Tomáš Pospíšil's avatar
errors  
Tomáš Pospíšil committed
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
                }
            }

            sort($branches, SORT_NUMERIC);

            return array_reverse($branches);
        }

        return [];
    }

    public function getBranchName(): string
    {
        $dir = Dumper::getDirectory();

        $head = $dir . '/.git/HEAD';
        if ($dir && is_readable($head)) {
            $branch = FileSystem::read($head);
            if (0 === strpos($branch, 'ref:')) {
                $parts = explode('/', $branch);

                return substr($parts[2], 0, -1);
            }

            return $branch;
        }

        return '';
    }

    public function getTags(): array
    {
        $dir = Dumper::getDirectory();

        $files = scandir($dir . '/.git/refs/tags');
        $tags = [];

        if ($dir && is_array($files)) {
            foreach ($files as $file) {
                if ('.' !== $file && '..' !== $file) {
                    $tags [] = $file;
                }
            }

            return $tags;
        }

        return [];
    }

}