summaryrefslogtreecommitdiffstats
path: root/3rdparty/granite/git/repository.php
blob: 30b58a39f5a525bed8ec3741c51d27b3eb315c97 (plain)
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
<?php
/**
 * Repository - provides a 'repository' object with a set of helper methods
 *
 * PHP version 5.3
 *
 * @category Git
 * @package  Granite
 * @author   Craig Roberts <craig0990@googlemail.com>
 * @license  http://www.opensource.org/licenses/mit-license.php MIT Expat License
 * @link     http://craig0990.github.com/Granite/
 */

namespace Granite\Git;
use \InvalidArgumentException as InvalidArgumentException;
use \UnexpectedValueException as UnexpectedValueException;

/**
 * Repository represents a Git repository, providing a variety of methods for
 * fetching objects from SHA-1 ids or the tip of a branch with `head()`
 *
 * @category Git
 * @package  Granite
 * @author   Craig Roberts <craig0990@googlemail.com>
 * @license  http://www.opensource.org/licenses/mit-license.php MIT Expat License
 * @link     http://craig0990.github.com/Granite/
 */
class Repository
{

    /**
     * The path to the repository root
     */
    private $_path;
    /**
     * The indexed version of a commit, ready to write with `commit()`
     */
    private $idx_commit;
    /**
     * The indexed version of a tree, modified to with `add()` and `remove()`
     */
    private $idx_tree;

    /**
     * Sets the repository path
     *
     * @param string $path The path to the repository root (i.e. /repo/.git/)
     */
    public function __construct($path)
    {
        if (!is_dir($path)) {
            throw new InvalidArgumentException("Unable to find directory $path");
        } elseif (!is_readable($path)) {
            throw new InvalidArgumentException("Unable to read directory $path");
        } elseif (!is_dir($path . DIRECTORY_SEPARATOR . 'objects')
            || !is_dir($path . DIRECTORY_SEPARATOR . 'refs')
        ) {
            throw new UnexpectedValueException(
                "Invalid directory, could not find 'objects' or 'refs' in $path"
            );
        }

        $this->_path = $path;
        $this->idx_commit = $this->factory('commit');
        $this->idx_tree = $this->factory('tree');
    }

    /**
     * Returns an object from the Repository of the given type, with the given
     * SHA-1 id, or false if it cannot be found
     *
     * @param string $type The type (blob, commit, tag or tree) of object being
     * requested
     * @param string $sha  The SHA-1 id of the object (or the name of a tag)
     *
     * @return Blob|Commit|Tag|Tree
     */
    public function factory($type, $sha = null)
    {
        if (!in_array($type, array('blob', 'commit', 'tag', 'tree'))) {
            throw new InvalidArgumentException("Invalid type: $type");
        }

        if ($type == 'tag') {
            $sha = $this->_ref('tags' . DIRECTORY_SEPARATOR . $sha);
        }
        $type = 'Granite\\Git\\' . ucwords($type);

        return new $type($this->_path, $sha);
    }

    /**
     * Returns a Commit object representing the HEAD commit
     *
     * @param string $branch The branch name to lookup, defaults to 'master'
     *
     * @return Commit An object representing the HEAD commit
     */
    public function head($branch = 'master', $value = NULL)
    {
        if ($value == NULL)
            return $this->factory(
                'commit', $this->_ref('heads' . DIRECTORY_SEPARATOR . $branch)
            );

        file_put_contents(
            $this->_path . DIRECTORY_SEPARATOR
            . 'refs' . DIRECTORY_SEPARATOR
            . 'heads' . DIRECTORY_SEPARATOR . 'master',
            $value
        );
    }

    /**
     * Returns a string representing the repository's location, which may or may
     * not be initialised
     *
     * @return string A string representing the repository's location
     */
    public function path()
    {
        return $this->_path;
    }

    /**
     * Returns an array of the local branches under `refs/heads`
     *
     * @return array
     */
    public function tags()
    {
      return $this->_refs('tags');
    }

    /**
     * Returns an array of the local tags under `refs/tags`
     *
     * @return array
     */
    public function branches()
    {
      return $this->_refs('heads');
    }

    private function _refs($type)
    {
      $dir = $this->_path . 'refs' . DIRECTORY_SEPARATOR . $type;
      $refs = glob($dir . DIRECTORY_SEPARATOR . '*');
      foreach ($refs as &$ref) {
        $ref = basename($ref);
      }
      return $refs;
    }

    /**
     * Initialises a Git repository
     *
     * @return boolean Returns true on success, false on error
     */
    public static function init($path)
    {
      $path .= '/';
      if (!is_dir($path)) {
        mkdir($path);
      } elseif (is_dir($path . 'objects')) {
        return false;
      }

      mkdir($path . 'objects');
      mkdir($path . 'objects/info');
      mkdir($path . 'objects/pack');
      mkdir($path . 'refs');
      mkdir($path . 'refs/heads');
      mkdir($path . 'refs/tags');

      file_put_contents($path . 'HEAD', 'ref: refs/heads/master');

      return true;
    }

    /**
     * Writes the indexed commit to disk, with blobs added/removed via `add()` and
     * `rm()`
     *
     * @param string $message The commit message
     * @param string $author  The author name
     *
     * @return boolean True on success, or false on failure
     */
    public function commit($message, $author)
    {
        $user_string = $username . ' ' . time() . ' +0000';

        try {
            $parents = array($this->repo->head()->sha());
        } catch (InvalidArgumentException $e) {
            $parents = array();
        }

        $this->idx_commit->message($message);
        $this->idx_commit->author($user_string);
        $this->idx_commit->committer($user_string);
        $this->idx_commit->tree($this->idx_tree);
        $commit->parents($parents);

        $this->idx_tree->write();
        $this->idx_commit->write();

        $this->repo->head('master', $this->idx_commit->sha());

        $this->idx_commit = $this->factory('commit');
        $this->idx_tree = $this->factory('tree');
    }

    /**
     * Adds a file to the indexed commit, to be written to disk with `commit()`
     *
     * @param string           $filename The filename to save it under
     * @param Granite\Git\Blob $blob     The raw blob object to add to the tree
     */
    public function add($filename, Granite\Git\Blob $blob)
    {
        $blob->write();
        $nodes = $this->idx_tree->nodes();
        $nodes[$filename] = new Granite\Git\Tree\Node($filename, '100644', $blob->sha());
        $this->idx_tree->nodes($nodes);
    }

    /**
     * Removes a file from the indexed commit
     */
    public function rm($filename)
    {
        $nodes = $this->idx_tree->nodes();
        unset($nodes[$filename]);
        $this->idx_tree->nodes($nodes);
    }

    /**
     * Returns an SHA-1 id of the ref resource
     *
     * @param string $ref The ref name to lookup
     *
     * @return string An SHA-1 id of the ref resource
     */
    private function _ref($ref)
    {
        // All refs are stored in `.git/refs`
        $file = $this->_path . 'refs' . DIRECTORY_SEPARATOR . $ref;

        if (file_exists($file)) {
            return trim(file_get_contents($file));
        }

        $sha = $this->_packedRef($ref);

        if ($sha == false) {
            throw new InvalidArgumentException("The ref $ref could not be found");
        }

        return $sha;
    }

    /**
     * Returns an SHA-1 id of the ref resource, or false if it cannot be found
     *
     * @param string $ref The ref name to lookup
     *
     * @return string An SHA-1 id of the ref resource
     */
    private function _packedRef($ref)
    {
        $sha = false;
        if (file_exists($this->_path . 'packed-refs')) {
            $file = fopen($this->_path . 'packed-refs', 'r');

            while (($line = fgets($file)) !== false) {
                $info = explode(' ', $line);
                if (count($info) == 2
                    && trim($info[1]) == 'refs' . DIRECTORY_SEPARATOR . $ref
                ) {
                    $sha = trim($info[0]);
                    break;
                }
            }

            fclose($file);
        }

        return $sha;
    }

}