Modernize Git to upstream GitRepos, mainly command handling.
[phpgit.git] / library / Git / Tree.php
blob483bde910240332e7cd7614935dcb247acc8e0ab
1 <?php
3 /**
4 * Represents a tree file structure in Git.
5 */
6 class Git_Tree extends Git_Lazy {
7 /**
8 * Instance of Git_Repo.
9 */
10 public $repo;
11 /**
12 * Treeish identifier of the tree. Can be a SHA-1 sum.
14 protected $id;
15 protected $mode;
16 protected $name;
17 protected $contents;
18 public function __construct($repo, $kwargs = array()) {
19 $this->repo = $repo;
20 foreach ($kwargs as $k => $v) {
21 $this->$k = $v;
24 /**
25 * Lazy loads the tree's contents.
27 protected function bake() {
28 $tmp = Git_Tree::construct($this->repo, $this->id);
29 $this->contents = $tmp->contents;
31 /**
32 * Constructs and fully initializes a tree.
34 public static function construct($repo, $treeish, $paths = array()) {
35 // suspect:
36 $output = $repo->git->lsTree($treeish, $paths);
37 $tree = new Git_Tree($repo, array('id' => $treeish));
38 $tree->constructInitialize($repo, $treeish, $output);
39 return $tree;
41 /**
42 * Initializes a tree object based on the output of the ls-tree command.
44 public function constructInitialize($repo, $id, $text) {
45 $this->repo = $repo;
46 $this->id = $id;
47 $this->contents = array();
48 foreach (explode("\n", $text) as $line) {
49 $out = self::contentFromString($repo, $line);
50 if (!$out) continue;
51 $this->contents[] = $out;
53 $this->markBaked();
55 /**
56 * Creates a content object (blob or tree) based on the ls-tree command.
58 public function contentFromString($repo, $text) {
59 $text = str_replace("\t", ' ', $text);
60 $bits = explode(' ', $text);
61 if (count($bits) != 4) return;
62 list($mode, $type, $id, $name) = $bits;
63 switch ($type) {
64 case 'tree':
65 return new Git_Tree($repo, compact('id', 'mode', 'name'));
66 case 'blob':
67 return new Git_Blob($repo, compact('id', 'mode', 'name'));
68 case 'commit':
69 return;
70 default:
71 throw new Git_Exception('Invalid type: ' . $type);
74 /**
75 * Retrieves a named object in this tree's contents.
76 * @param Filename of object to return. This function does NOT search
77 * recursively.
78 * @return Null if file not found, otherwise Git_Tree or Git_Commit file.
80 public function get($file) {
81 foreach ($this->contents as $c) {
82 if ($c->name == $file) return $c;
85 /**
86 * Retrieves the basename of this tree.
88 public function basename() {
89 return basename($this->__get('name'));
91 public function __toString() {
92 return '(Git_Tree "'.$this->id.'")';