00001 <?php
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021 class GitObject
00022 {
00026 public $repo;
00027 protected $type;
00028 protected $name = NULL;
00029
00035 public function getName() { return $this->name; }
00036
00043 public function getType() { return $this->type; }
00044
00053 static public function create($repo, $type)
00054 {
00055 if ($type == Git::OBJ_COMMIT)
00056 return new GitCommit($repo);
00057 if ($type == Git::OBJ_TREE)
00058 return new GitTree($repo);
00059 if ($type == Git::OBJ_BLOB)
00060 return new GitBlob($repo);
00061 throw new Exception(sprintf('unhandled object type %d', $type));
00062 }
00063
00071 protected function hash($data)
00072 {
00073 $hash = hash_init('sha1');
00074 hash_update($hash, Git::getTypeName($this->type));
00075 hash_update($hash, ' ');
00076 hash_update($hash, strlen($data));
00077 hash_update($hash, "\0");
00078 hash_update($hash, $data);
00079 return hash_final($hash, TRUE);
00080 }
00081
00088 public function __construct($repo, $type)
00089 {
00090 $this->repo = $repo;
00091 $this->type = $type;
00092 }
00093
00103 public function unserialize($data)
00104 {
00105 $this->name = $this->hash($data);
00106 $this->_unserialize($data);
00107 }
00108
00115 public function serialize()
00116 {
00117 return $this->_serialize();
00118 }
00119
00126 public function rehash()
00127 {
00128 $this->name = $this->hash($this->serialize());
00129 }
00130
00135 public function write()
00136 {
00137 $sha1 = sha1_hex($this->name);
00138 $path = sprintf('%s/objects/%s/%s', $this->repo->dir, substr($sha1, 0, 2), substr($sha1, 2));
00139 if (file_exists($path))
00140 return FALSE;
00141 $dir = dirname($path);
00142 if (!is_dir($dir))
00143 mkdir(dirname($path), 0770);
00144 $f = fopen($path, 'ab');
00145 flock($f, LOCK_EX);
00146 ftruncate($f, 0);
00147 $data = $this->serialize();
00148 $data = Git::getTypeName($this->type).' '.strlen($data)."\0".$data;
00149 fwrite($f, gzcompress($data));
00150 fclose($f);
00151 return TRUE;
00152 }
00153 };
00154 ?>