1212class GitVersionPanel implements IBarPanel
1313{
1414
15+ private $ read = false ;
16+
17+ private $ branch ;
18+ private $ commit ;
19+
1520 public function getPanel ()
1621 {
17- return '' ;
22+ $ this ->parseHead ();
23+ return '<h1>Git Version</h1><p>Revision: ' . $ this ->getCurrentCommitHash () . '</p> ' ;
1824 }
1925
2026 protected function getCurrentBranchName ()
2127 {
22- $ scriptPath = $ _SERVER ['SCRIPT_FILENAME ' ];
23-
24- $ dir = realpath (dirname ($ scriptPath ));
25- while ($ dir !== false && !is_dir ($ dir . '/.git ' )) {
26- flush ();
27- $ currentDir = $ dir ;
28- $ dir .= '/.. ' ;
29- $ dir = realpath ($ dir );
30-
31- // Stop recursion to parent on root directory
32- if ($ dir == $ currentDir ) {
33- break ;
34- }
28+ $ this ->parseHead ();
29+ if ($ this ->branch ) {
30+ return $ this ->branch ;
31+ } elseif ($ this ->commit ) {
32+ return 'detached ' ;
3533 }
34+ return 'not versioned ' ;
35+ }
3636
37- $ head = $ dir . '/.git/HEAD ' ;
38- if ($ dir && is_readable ($ head )) {
39- $ branch = file_get_contents ($ head );
40- if (strpos ($ branch , 'ref: ' ) === 0 ) {
41- $ parts = explode ('/ ' , $ branch );
42- return $ parts [2 ];
43- }
44- return '( ' . substr ($ branch , 0 , 7 ) . '…) ' ;
37+ protected function getCurrentCommitHash ()
38+ {
39+ $ this ->parseHead ();
40+ if ($ this ->commit ) {
41+ return $ this ->commit ;
4542 }
46-
4743 return 'not versioned ' ;
4844 }
4945
@@ -53,4 +49,41 @@ public function getTab()
5349 . $ this ->getCurrentBranchName ();
5450 }
5551
52+ private function parseHead ()
53+ {
54+ if (!$ this ->read ) {
55+ $ scriptPath = $ _SERVER ['SCRIPT_FILENAME ' ];
56+ $ dir = realpath (dirname ($ scriptPath ));
57+ while ($ dir !== false && !is_dir ($ dir . '/.git ' )) {
58+ flush ();
59+ $ currentDir = $ dir ;
60+ $ dir .= '/.. ' ;
61+ $ dir = realpath ($ dir );
62+
63+ // Stop recursion to parent on root directory
64+ if ($ dir == $ currentDir ) {
65+ break ;
66+ }
67+ }
68+
69+ $ head = $ dir . '/.git/HEAD ' ;
70+ if ($ dir && is_readable ($ head )) {
71+ $ branch = file_get_contents ($ head );
72+ if (strpos ($ branch , 'ref: ' ) === 0 ) {
73+ $ parts = explode ('/ ' , $ branch );
74+ $ this ->branch = $ parts [2 ];
75+
76+ $ commitFile = $ dir . '/.git/ ' . trim (substr ($ branch , 5 , strlen ($ branch )));
77+ if (is_readable ($ commitFile )) {
78+ $ this ->commit = file_get_contents ($ commitFile );
79+ }
80+ } else {
81+ $ this ->commit = $ branch ;
82+ }
83+ }
84+ $ this ->read = true ;
85+ }
86+ }
87+
5688}
89+
0 commit comments