Dave Jarvis' Repositories

git clone https://repo.autonoma.ca/repo/treetrek.git

Simplifies code, performs more optimizations

AuthorDave Jarvis <email>
Date2026-02-22 13:09:40 GMT-0800
Commitc37a67980ae82ad3c3d302a7bae4777ac3b0c2d9
Parent6ccb6b9
git/BufferedReader.php
private int $bufferLen = 0;
+ private string $wBuffer = '';
+ private int $wBufferLen = 0;
+
private readonly bool $writable;
public function __construct( string $path, string $mode = 'rb' ) {
$this->handle = @\fopen( $path, $mode );
$this->writable = $mode !== 'rb';
}
public function __destruct() {
if( $this->handle !== false ) {
+ $this->flushWrites();
\fclose( $this->handle );
$available = $this->bufferLen - $this->bufferPos;
- if( $available < $length
- && $this->handle !== false
- && !\feof( $this->handle )
- ) {
+ if( $available >= $length ) {
+ $result = \substr(
+ $this->buffer, $this->bufferPos, $length
+ );
+ $this->bufferPos += $length;
+
+ if( $this->bufferPos >= $this->bufferLen ) {
+ $this->clearReadBuffer();
+ }
+
+ return $result;
+ }
+
+ if( $this->bufferPos > 0 ) {
+ $this->buffer = $available > 0
+ ? \substr( $this->buffer, $this->bufferPos )
+ : '';
+ $this->bufferLen = $available;
+ $this->bufferPos = 0;
+ }
+
+ if( $this->handle !== false && !\feof( $this->handle ) ) {
$chunk = \fread(
$this->handle,
\max( $length - $available, self::CHUNK_SIZE )
);
if( $chunk !== false && $chunk !== '' ) {
$this->buffer .= $chunk;
$this->bufferLen += \strlen( $chunk );
- $available = $this->bufferLen - $this->bufferPos;
+ $available = $this->bufferLen;
}
}
if( $this->bufferPos >= $this->bufferLen ) {
- $this->buffer = '';
- $this->bufferPos = 0;
- $this->bufferLen = 0;
- } elseif( $this->bufferPos >= self::CHUNK_SIZE ) {
- $this->buffer = \substr( $this->buffer, $this->bufferPos );
- $this->bufferLen -= $this->bufferPos;
- $this->bufferPos = 0;
+ $this->clearReadBuffer();
}
}
return $result;
}
public function write( string $data ): bool {
- $canWrite = $this->writable && $this->handle !== false;
+ if( !$this->writable || $this->handle === false ) {
+ return false;
+ }
- if( $canWrite ) {
- $this->buffer = '';
- $this->bufferPos = 0;
- $this->bufferLen = 0;
+ $this->clearReadBuffer();
+
+ $this->wBuffer .= $data;
+ $this->wBufferLen += \strlen( $data );
+
+ if( $this->wBufferLen < self::CHUNK_SIZE ) {
+ return true;
}
- return $canWrite ? \fwrite( $this->handle, $data ) !== false : false;
+ return $this->flushWrites();
}
if( $success ) {
- $this->buffer = '';
- $this->bufferPos = 0;
- $this->bufferLen = 0;
+ $this->clearReadBuffer();
}
}
public function rewind(): void {
if( $this->handle !== false ) {
+ $this->flushWrites();
\rewind( $this->handle );
- $this->buffer = '';
- $this->bufferPos = 0;
- $this->bufferLen = 0;
+ $this->clearReadBuffer();
+ }
+ }
+
+ private function clearReadBuffer(): void {
+ $this->buffer = '';
+ $this->bufferPos = 0;
+ $this->bufferLen = 0;
+ }
+
+ private function flushWrites(): bool {
+ if( $this->wBufferLen === 0 ) {
+ return true;
}
+
+ $ok = \fwrite( $this->handle, $this->wBuffer ) !== false;
+ $this->wBuffer = '';
+ $this->wBufferLen = 0;
+
+ return $ok;
}
}
git/DeltaDecoder.php
$len = strlen( $delta );
$outLen = 0;
- $done = false;
- $result = '';
- while( !$done && $pos < $len ) {
- if( $cap > 0 && $outLen >= $cap ) {
- $done = true;
- }
+ while( $pos < $len ) {
+ if( $cap > 0 && $outLen >= $cap ) break;
- if( !$done ) {
- $op = ord( $delta[$pos++] );
+ $op = ord( $delta[$pos++] );
- if( $op & 128 ) {
- $off = 0;
- $ln = 0;
+ if( $op & 128 ) {
+ $off = $ln = 0;
- $this->parseCopyInstruction( $op, $delta, $pos, $off, $ln );
+ $this->parseCopyInstruction( $op, $delta, $pos, $off, $ln );
- $extracted = substr( $base, $off, $ln );
- $chunks[] = $extracted;
- $outLen += $ln;
- } else {
- $ln = $op & 127;
- $extracted = substr( $delta, $pos, $ln );
- $chunks[] = $extracted;
- $outLen += $ln;
- $pos += $ln;
- }
+ $chunks[] = substr( $base, $off, $ln );
+ $outLen += $ln;
+ } else {
+ $ln = $op & 127;
+ $chunks[] = substr( $delta, $pos, $ln );
+ $outLen += $ln;
+ $pos += $ln;
}
}
$result = implode( '', $chunks );
-
- if( $cap > 0 && strlen( $result ) > $cap ) {
- $result = substr( $result, 0, $cap );
- }
- return $result;
+ return $cap > 0 && strlen( $result ) > $cap
+ ? substr( $result, 0, $cap )
+ : $result;
}
foreach( $stream->stream( $handle ) as $data ) {
- if( $offset > 0 ) {
- $buffer = substr( $buffer, $offset );
- $offset = 0;
- }
-
$buffer .= $data;
- $bufLen = strlen( $buffer ); // loop invariant: buffer unchanged inside while
+ $bufLen = \strlen( $buffer );
while( $offset < $bufLen ) {
$len = $bufLen - $offset;
if( $state < 2 ) {
- // Inline advanceToInstructions: scan past the variable-length source
- // or target size integer (high-bit continuation bytes, then one
- // terminating byte with bit-7 clear).
$pos = $offset;
$found = false;
}
- $off = 0;
- $ln = 0;
+ $off = $ln = 0;
$ptr = $offset + 1;
-
- ($op & 0x01) ? $off |= ord( $buffer[$ptr++] ) : null;
- ($op & 0x02) ? $off |= ord( $buffer[$ptr++] ) << 8 : null;
- ($op & 0x04) ? $off |= ord( $buffer[$ptr++] ) << 16 : null;
- ($op & 0x08) ? $off |= ord( $buffer[$ptr++] ) << 24 : null;
- ($op & 0x10) ? $ln |= ord( $buffer[$ptr++] ) : null;
- ($op & 0x20) ? $ln |= ord( $buffer[$ptr++] ) << 8 : null;
- ($op & 0x40) ? $ln |= ord( $buffer[$ptr++] ) << 16 : null;
- $ln = $ln === 0 ? 0x10000 : $ln;
+ $this->parseCopyInstruction( $op, $buffer, $ptr, $off, $ln );
if( $isStream ) {
}
} else {
- $slc = substr( $base, $off, $ln );
- $slcLen = strlen( $slc );
+ $slc = \substr( $base, $off, $ln );
$yieldBuffer .= $slc;
- $yieldBufLen += $slcLen;
+ $yieldBufLen += \strlen( $slc );
if( $yieldBufLen >= self::CHUNK_SIZE ) {
yield $yieldBuffer;
$yieldBuffer = '';
$yieldBufLen = 0;
}
}
- $offset += 1 + $need;
+ $offset = $ptr;
} else {
$ln = $op & 127;
}
}
+ }
+
+ if( $offset >= self::CHUNK_SIZE ) {
+ $buffer = \substr( $buffer, $offset );
+ $offset = 0;
}
}
if( $yieldBuffer !== '' ) {
yield $yieldBuffer;
}
}
public function readDeltaTargetSize( StreamReader $handle, int $type ): int {
- $result = 0;
-
if( $type === 6 ) {
$byte = ord( $handle->read( 1 ) );
}
- $stream = CompressionStream::createInflater();
- $head = '';
- $try = 0;
+ $head = $this->readInflatedHead( $handle );
- foreach( $stream->stream( $handle, 512 ) as $out ) {
- $head .= $out;
- $try++;
+ if( strlen( $head ) === 0 ) return 0;
- if( strlen( $head ) >= 32 || $try >= 64 ) {
- break;
- }
- }
+ $pos = 0;
+ $this->readDeltaSize( $head, $pos );
- if( strlen( $head ) > 0 ) {
- $pos = 0;
- $this->readDeltaSize( $head, $pos );
+ return $this->readDeltaSize( $head, $pos );
+ }
- $result = $this->readDeltaSize( $head, $pos );
- }
+ public function readDeltaBaseSize( StreamReader $handle ): int {
+ $head = $this->readInflatedHead( $handle );
- return $result;
+ if( strlen( $head ) === 0 ) return 0;
+
+ $pos = 0;
+
+ return $this->readDeltaSize( $head, $pos );
}
- public function readDeltaBaseSize( StreamReader $handle ): int {
+ private function readInflatedHead( StreamReader $handle ): string {
$stream = CompressionStream::createInflater();
$head = '';
$try = 0;
- $result = 0;
foreach( $stream->stream( $handle, 512 ) as $out ) {
$head .= $out;
$try++;
if( strlen( $head ) >= 32 || $try >= 64 ) {
break;
}
- }
-
- if( strlen( $head ) > 0 ) {
- $pos = 0;
- $result = $this->readDeltaSize( $head, $pos );
}
- return $result;
+ return $head;
}
$len = $len === 0 ? 0x10000 : $len;
- }
-
- private function calculateCopyInstructionSize( int $op ): int {
- $calc = $op & 0x7F;
- $calc = $calc - ($calc >> 1 & 0x55);
- $calc = ($calc >> 2 & 0x33) + ($calc & 0x33);
- $calc = (($calc >> 4) + $calc) & 0x0F;
-
- return $calc;
}
git/Git.php
public function eachTag( callable $callback ): void {
- $this->refs->scanRefs( 'refs/tags', function( $name, $sha ) use (
- $callback
- ) {
- $data = $this->read( $sha );
- $tag = $this->parseTagData( $name, $sha, $data );
-
- $callback( $tag );
- } );
- }
-
- public function walk(
- string $refOrSha,
- callable $callback,
- string $path = ''
- ): void {
- $sha = $this->resolve( $refOrSha );
- $treeSha = '';
-
- if( $sha !== '' ) {
- $treeSha = $this->getTreeSha( $sha );
- }
-
- if( $path !== '' && $treeSha !== '' ) {
- $info = $this->resolvePath( $treeSha, $path );
- $treeSha = $info['isDir'] ? $info['sha'] : '';
- }
-
- if( $treeSha !== '' ) {
- $this->walkTree( $treeSha, $callback );
- }
- }
-
- public function readFile( string $ref, string $path ): File {
- $sha = $this->resolve( $ref );
- $tree = $sha !== '' ? $this->getTreeSha( $sha ) : '';
- $info = $tree !== '' ? $this->resolvePath( $tree, $path ) : [];
-
- return isset( $info['sha'] ) && !$info['isDir'] && $info['sha'] !== ''
- ? new File(
- \basename( $path ),
- $info['sha'],
- $info['mode'],
- 0,
- $this->getObjectSize( $info['sha'] ),
- $this->peek( $info['sha'] )
- )
- : new MissingFile();
- }
-
- public function getObjectSize( string $sha, string $path = '' ): int {
- $target = $sha;
- $result = 0;
-
- if( $path !== '' ) {
- $info = $this->resolvePath(
- $this->getTreeSha( $this->resolve( $sha ) ),
- $path
- );
- $target = $info['sha'] ?? '';
- }
-
- if( $target !== '' ) {
- $result = $this->packs->getSize( $target );
-
- if( $result === 0 ) {
- $result = $this->getLooseObjectSize( $target );
- }
- }
-
- return $result;
- }
-
- public function stream(
- string $sha,
- callable $callback,
- string $path = ''
- ): void {
- $target = $sha;
-
- if( $path !== '' ) {
- $info = $this->resolvePath(
- $this->getTreeSha( $this->resolve( $sha ) ),
- $path
- );
- $target = isset( $info['isDir'] ) && !$info['isDir']
- ? $info['sha']
- : '';
- }
-
- if( $target !== '' ) {
- $this->slurp( $target, $callback );
- }
- }
-
- public function peek( string $sha, int $length = 255 ): string {
- $size = $this->packs->getSize( $sha );
-
- return $size === 0
- ? $this->peekLooseObject( $sha, $length )
- : $this->packs->peek( $sha, $length );
- }
-
- public function read( string $sha ): string {
- $size = $this->getObjectSize( $sha );
- $content = '';
-
- if( $size > 0 && $size <= self::MAX_READ ) {
- $this->slurp( $sha, function( $chunk ) use ( &$content ) {
- $content .= $chunk;
- } );
- }
-
- return $content;
- }
-
- public function history(
- string $ref,
- int $limit,
- callable $callback
- ): void {
- $sha = $this->resolve( $ref );
- $count = 0;
- $done = false;
-
- while( !$done && $sha !== '' && $count < $limit ) {
- $commit = $this->parseCommit( $sha );
-
- if( $commit->sha === '' ) {
- $sha = '';
- $done = true;
- }
-
- if( !$done && $sha !== '' ) {
- if( $callback( $commit ) === false ) {
- $done = true;
- }
-
- if( !$done ) {
- $sha = $commit->parentSha;
- $count++;
- }
- }
- }
- }
-
- public function streamRaw( string $subPath ): bool {
- $result = false;
-
- if( \strpos( $subPath, '..' ) === false ) {
- $path = "{$this->repoPath}/$subPath";
-
- if( \is_file( $path ) ) {
- $real = \realpath( $path );
- $repo = \realpath( $this->repoPath );
-
- if( $real !== false && \strpos( $real, $repo ) === 0 ) {
- \header( 'X-Accel-Redirect: ' . $path );
- \header( 'Content-Type: application/octet-stream' );
- $result = true;
- }
- }
- }
-
- return $result;
- }
-
- public function eachRef( callable $callback ): void {
- $head = $this->resolve( 'HEAD' );
-
- if( $head !== '' ) {
- $callback( 'HEAD', $head );
- }
-
- $this->refs->scanRefs( 'refs/heads', function( $n, $s ) use ( $callback ) {
- $callback( "refs/heads/$n", $s );
- } );
-
- $this->refs->scanRefs( 'refs/tags', function( $n, $s ) use ( $callback ) {
- $callback( "refs/tags/$n", $s );
- } );
- }
-
- public function generatePackfile( array $objs ): Generator {
- $ctx = \hash_init( 'sha1' );
- $head = "PACK" . \pack( 'N', 2 ) . \pack( 'N', \count( $objs ) );
-
- \hash_update( $ctx, $head );
- yield $head;
-
- foreach( $objs as $sha => $type ) {
- $size = $this->getObjectSize( $sha );
- $byte = $type << 4 | $size & 0x0f;
- $sz = $size >> 4;
- $hdr = '';
-
- while( $sz > 0 ) {
- $hdr .= \chr( $byte | 0x80 );
- $byte = $sz & 0x7f;
- $sz >>= 7;
- }
-
- $hdr .= \chr( $byte );
- \hash_update( $ctx, $hdr );
- yield $hdr;
-
- foreach( $this->streamCompressed( $sha ) as $compressed ) {
- \hash_update( $ctx, $compressed );
- yield $compressed;
- }
- }
-
- yield \hash_final( $ctx, true );
- }
-
- private function streamCompressed( string $sha ): Generator {
- $yielded = false;
-
- foreach( $this->packs->streamRawCompressed( $sha ) as $chunk ) {
- $yielded = true;
- yield $chunk;
- }
-
- if( !$yielded ) {
- $deflate = \deflate_init( \ZLIB_ENCODING_DEFLATE );
-
- foreach( $this->slurpChunks( $sha ) as $raw ) {
- $compressed = \deflate_add( $deflate, $raw, \ZLIB_NO_FLUSH );
-
- if( $compressed !== '' ) {
- yield $compressed;
- }
- }
-
- $final = \deflate_add( $deflate, '', \ZLIB_FINISH );
-
- if( $final !== '' ) {
- yield $final;
- }
- }
- }
-
- private function slurpChunks( string $sha ): Generator {
- $path = $this->getLoosePath( $sha );
-
- if( \is_file( $path ) ) {
- yield from $this->looseObjectChunks( $path );
- } else {
- $any = false;
-
- foreach( $this->packs->streamGenerator( $sha ) as $chunk ) {
- $any = true;
- yield $chunk;
- }
-
- if( !$any ) {
- $data = $this->packs->read( $sha );
-
- if( $data !== '' ) {
- yield $data;
- }
- }
- }
- }
-
- private function looseObjectChunks( string $path ): Generator {
- $reader = new BufferedReader( $path );
- $infl = $reader->isOpen()
- ? \inflate_init( \ZLIB_ENCODING_DEFLATE )
- : false;
-
- if( $reader->isOpen() && $infl !== false ) {
- $found = false;
- $buffer = '';
-
- while( !$reader->eof() ) {
- $chunk = $reader->read( 16384 );
- $inflated = \inflate_add( $infl, $chunk );
-
- if( $inflated === false ) {
- break;
- }
-
- if( !$found ) {
- $buffer .= $inflated;
- $eos = \strpos( $buffer, "\0" );
-
- if( $eos !== false ) {
- $found = true;
- $body = \substr( $buffer, $eos + 1 );
-
- if( $body !== '' ) {
- yield $body;
- }
-
- $buffer = '';
- }
- } elseif( $inflated !== '' ) {
- yield $inflated;
- }
- }
- }
- }
-
- private function getTreeSha( string $commitOrTreeSha ): string {
- $data = $this->read( $commitOrTreeSha );
- $sha = $commitOrTreeSha;
-
- if( \preg_match( '/^object ([0-9a-f]{40})/m', $data, $matches ) ) {
- $sha = $this->getTreeSha( $matches[1] );
- }
-
- if( $sha === $commitOrTreeSha &&
- \preg_match( '/^tree ([0-9a-f]{40})/m', $data, $matches ) ) {
- $sha = $matches[1];
- }
-
- return $sha;
- }
-
- private function resolvePath( string $treeSha, string $path ): array {
- $parts = \explode( '/', \trim( $path, '/' ) );
- $sha = $treeSha;
- $mode = '40000';
-
- foreach( $parts as $part ) {
- $entry = [ 'sha' => '', 'mode' => '' ];
-
- if( $part !== '' && $sha !== '' ) {
- $entry = $this->findTreeEntry( $sha, $part );
- }
-
- $sha = $entry['sha'];
- $mode = $entry['mode'];
- }
-
- return [
- 'sha' => $sha,
- 'mode' => $mode,
- 'isDir' => $mode === '40000' || $mode === '040000'
- ];
- }
-
- private function findTreeEntry( string $treeSha, string $name ): array {
- $data = $this->read( $treeSha );
- $entry = [ 'sha' => '', 'mode' => '' ];
-
- $this->parseTreeData(
- $data,
- function( $n, $s, $m ) use ( $name, &$entry ) {
- if( $n === $name ) {
- $entry = [ 'sha' => $s, 'mode' => $m ];
-
- return false;
- }
- }
- );
-
- return $entry;
- }
-
- private function parseTagData(
- string $name,
- string $sha,
- string $data
- ): Tag {
- $isAnn = \strncmp( $data, 'object ', 7 ) === 0;
- $pattern = $isAnn
- ? '/^tagger (.*) <(.*)> (\d+) [+\-]\d{4}$/m'
- : '/^author (.*) <(.*)> (\d+) [+\-]\d{4}$/m';
- $id = $this->parseIdentity( $data, $pattern );
- $target = $isAnn
- ? $this->extractPattern( $data, '/^object (.*)$/m', 1, $sha )
- : $sha;
-
- return new Tag(
- $name,
- $sha,
- $target,
- $id['timestamp'],
- $this->extractMessage( $data ),
- $id['name']
- );
- }
-
- private function extractPattern(
- string $data,
- string $pattern,
- int $group,
- string $default = ''
- ): string {
- return \preg_match( $pattern, $data, $matches )
- ? $matches[$group]
- : $default;
- }
-
- private function parseIdentity( string $data, string $pattern ): array {
- $found = \preg_match( $pattern, $data, $matches );
-
- return [
- 'name' => $found ? \trim( $matches[1] ) : 'Unknown',
- 'email' => $found ? $matches[2] : '',
- 'timestamp' => $found ? (int)$matches[3] : 0
- ];
- }
-
- private function extractMessage( string $data ): string {
- $pos = \strpos( $data, "\n\n" );
-
- return $pos !== false ? \trim( \substr( $data, $pos + 2 ) ) : '';
- }
-
- private function slurp( string $sha, callable $callback ): void {
- $path = $this->getLoosePath( $sha );
-
- if( \is_file( $path ) ) {
- $this->slurpLooseObject( $path, $callback );
- } else {
- $this->slurpPackedObject( $sha, $callback );
- }
- }
-
- private function slurpLooseObject( string $path, callable $callback ): void {
- $this->iterateInflated(
- $path,
- function( $chunk ) use ( $callback ) {
- if( $chunk !== '' ) {
- $callback( $chunk );
- }
-
- return true;
- }
- );
- }
-
- private function slurpPackedObject( string $sha, callable $callback ): void {
- $streamed = $this->packs->stream( $sha, $callback );
-
- if( !$streamed ) {
- $data = $this->packs->read( $sha );
-
- if( $data !== '' ) {
- $callback( $data );
- }
- }
- }
-
- private function iterateInflated(
- string $path,
- callable $processor,
- int $bufferSize = 16384
- ): void {
- $reader = new BufferedReader( $path );
- $infl = $reader->isOpen()
- ? \inflate_init( \ZLIB_ENCODING_DEFLATE )
- : false;
- $found = false;
- $buffer = '';
-
- if( $reader->isOpen() && $infl !== false ) {
- while( !$reader->eof() ) {
- $chunk = $reader->read( $bufferSize );
- $inflated = \inflate_add( $infl, $chunk );
-
- if( $inflated === false ) {
- break;
- }
-
- if( !$found ) {
- $buffer .= $inflated;
- $eos = \strpos( $buffer, "\0" );
-
- if( $eos !== false ) {
- $found = true;
- $body = \substr( $buffer, $eos + 1 );
- $head = \substr( $buffer, 0, $eos );
-
- if( $processor( $body, $head ) === false ) {
- break;
- }
- }
- } elseif( $processor( $inflated, '' ) === false ) {
- break;
- }
- }
- }
- }
-
- private function peekLooseObject( string $sha, int $length ): string {
- $path = $this->getLoosePath( $sha );
- $buf = '';
-
- if( \is_file( $path ) ) {
- $this->iterateInflated(
- $path,
- function( $chunk ) use ( $length, &$buf ) {
- $buf .= $chunk;
-
- return \strlen( $buf ) < $length;
- },
- 8192
- );
- }
-
- return \substr( $buf, 0, $length );
- }
-
- private function parseCommit( string $sha ): object {
- $data = $this->read( $sha );
- $result = (object)[ 'sha' => '' ];
-
- if( $data !== '' ) {
- $id = $this->parseIdentity(
- $data,
- '/^author (.*) <(.*)> (\d+)/m'
- );
-
- $result = (object)[
- 'sha' => $sha,
- 'message' => $this->extractMessage( $data ),
- 'author' => $id['name'],
- 'email' => $id['email'],
- 'date' => $id['timestamp'],
- 'parentSha' => $this->extractPattern( $data, '/^parent (.*)$/m', 1 )
- ];
- }
-
- return $result;
- }
-
- private function walkTree( string $sha, callable $callback ): void {
- $data = $this->read( $sha );
- $tree = $data;
-
- if( $data !== '' && \preg_match( '/^tree (.*)$/m', $data, $m ) ) {
- $tree = $this->read( $m[1] );
- }
-
- if( $tree !== '' && $this->isTreeData( $tree ) ) {
- $this->processTree( $tree, $callback );
- }
- }
-
- private function processTree( string $data, callable $callback ): void {
- $this->parseTreeData(
- $data,
- function( $n, $s, $m ) use ( $callback ) {
- $dir = $m === '40000' || $m === '040000';
- $isSub = $m === '160000';
-
- $callback( new File(
- $n,
- $s,
- $m,
- 0,
- $dir || $isSub ? 0 : $this->getObjectSize( $s ),
- $dir || $isSub ? '' : $this->peek( $s )
- ) );
- }
- );
- }
-
- public function parseTreeData( string $data, callable $callback ): void {
- $pos = 0;
- $len = \strlen( $data );
-
- while( $pos < $len ) {
- $space = \strpos( $data, ' ', $pos );
- $eos = \strpos( $data, "\0", $space );
-
- if( $space === false || $eos === false || $eos + 21 > $len ) {
- break;
- }
-
- $mode = \substr( $data, $pos, $space - $pos );
- $name = \substr( $data, $space + 1, $eos - $space - 1 );
- $sha = \bin2hex( \substr( $data, $eos + 1, 20 ) );
-
- if( $callback( $name, $sha, $mode ) === false ) {
- break;
- }
-
- $pos = $eos + 21;
- }
- }
-
- private function isTreeData( string $data ): bool {
- $len = \strlen( $data );
- $patt = '/^(40000|100644|100755|120000|160000) /';
- $match = $len >= 25 && \preg_match( $patt, $data );
- $eos = $match ? \strpos( $data, "\0" ) : false;
-
- return $match && $eos !== false && $eos + 21 <= $len;
- }
-
- private function getLoosePath( string $sha ): string {
- return "{$this->objPath}/" . \substr( $sha, 0, 2 ) . "/" .
- \substr( $sha, 2 );
- }
-
- private function getLooseObjectSize( string $sha ): int {
- $path = $this->getLoosePath( $sha );
- $size = 0;
-
- if( \is_file( $path ) ) {
- $this->iterateInflated(
- $path,
- function( $c, $head ) use ( &$size ) {
- if( $head !== '' ) {
- $parts = \explode( ' ', $head );
- $size = isset( $parts[1] ) ? (int)$parts[1] : 0;
- }
-
- return false;
- }
- );
- }
-
- return $size;
- }
-
- public function collectObjects( array $wants, array $haves = [] ): array {
- $objs = $this->traverseObjects( $wants );
- $result = [];
-
- if( !empty( $haves ) ) {
- $haveObjs = $this->traverseObjects( $haves );
-
- foreach( $haveObjs as $sha => $type ) {
- if( isset( $objs[$sha] ) ) {
- unset( $objs[$sha] );
- }
- }
- }
-
- $result = $objs;
-
- return $result;
- }
-
- private function traverseObjects( array $roots ): array {
- $objs = [];
- $queue = [];
-
- foreach( $roots as $sha ) {
- $queue[] = [ 'sha' => $sha, 'type' => 0 ];
- }
-
- while( !empty( $queue ) ) {
- $item = \array_pop( $queue );
- $sha = $item['sha'];
- $type = $item['type'];
-
- if( isset( $objs[$sha] ) ) {
- continue;
- }
-
- $data = '';
-
- if( $type !== 3 ) {
- $data = $this->read( $sha );
-
- if( $type === 0 ) {
- $type = $this->getObjectType( $data );
- }
- }
-
- $objs[$sha] = $type;
-
- if( $type === 1 ) {
- $hasTree = \preg_match( '/^tree ([0-9a-f]{40})/m', $data, $m );
-
- if( $hasTree ) {
- $queue[] = [ 'sha' => $m[1], 'type' => 2 ];
- }
-
- $hasParents = \preg_match_all(
- '/^parent ([0-9a-f]{40})/m',
- $data,
- $m
- );
-
- if( $hasParents ) {
- foreach( $m[1] as $parentSha ) {
- $queue[] = [ 'sha' => $parentSha, 'type' => 1 ];
- }
- }
- } elseif( $type === 2 ) {
- $pos = 0;
- $len = \strlen( $data );
-
- while( $pos < $len ) {
- $space = \strpos( $data, ' ', $pos );
- $eos = \strpos( $data, "\0", $space );
-
- if( $space === false || $eos === false ) {
- break;
- }
-
- $mode = \substr( $data, $pos, $space - $pos );
- $hash = \bin2hex( \substr( $data, $eos + 1, 20 ) );
-
- if( $mode !== '160000' ) {
- $isDir = $mode === '40000' || $mode === '040000';
- $queue[] = [ 'sha' => $hash, 'type' => $isDir ? 2 : 3 ];
- }
-
- $pos = $eos + 21;
- }
- } elseif( $type === 4 ) {
- $isTagTgt = \preg_match( '/^object ([0-9a-f]{40})/m', $data, $m );
-
- if( $isTagTgt ) {
- $nextType = 1;
-
- if( \preg_match( '/^type (commit|tree|blob|tag)/m', $data, $t ) ) {
- $map = [
- 'commit' => 1,
- 'tree' => 2,
- 'blob' => 3,
- 'tag' => 4
- ];
- $nextType = $map[$t[1]] ?? 1;
- }
-
- $queue[] = [ 'sha' => $m[1], 'type' => $nextType ];
- }
- }
- }
-
- return $objs;
- }
-
- private function getObjectType( string $data ): int {
- $isTree = \strpos( $data, "tree " ) === 0;
- $isObj = \strpos( $data, "object " ) === 0;
- $result = 3;
-
- if( $isTree ) {
- $result = 1;
- } elseif( $isObj ) {
+ $this->refs->scanRefs(
+ 'refs/tags',
+ function( $name, $sha ) use ( $callback ) {
+ $callback(
+ $this->parseTagData( $name, $sha, $this->read( $sha ) )
+ );
+ }
+ );
+ }
+
+ public function walk(
+ string $refOrSha,
+ callable $callback,
+ string $path = ''
+ ): void {
+ $sha = $this->resolve( $refOrSha );
+ $treeSha = $sha !== '' ? $this->getTreeSha( $sha ) : '';
+
+ if( $path !== '' && $treeSha !== '' ) {
+ $info = $this->resolvePath( $treeSha, $path );
+ $treeSha = $info['isDir'] ? $info['sha'] : '';
+ }
+
+ if( $treeSha !== '' ) {
+ $this->walkTree( $treeSha, $callback );
+ }
+ }
+
+ public function readFile( string $ref, string $path ): File {
+ $sha = $this->resolve( $ref );
+ $tree = $sha !== '' ? $this->getTreeSha( $sha ) : '';
+ $info = $tree !== '' ? $this->resolvePath( $tree, $path ) : [];
+
+ return isset( $info['sha'] ) && !$info['isDir'] && $info['sha'] !== ''
+ ? new File(
+ \basename( $path ),
+ $info['sha'],
+ $info['mode'],
+ 0,
+ $this->getObjectSize( $info['sha'] ),
+ $this->peek( $info['sha'] )
+ )
+ : new MissingFile();
+ }
+
+ public function getObjectSize( string $sha, string $path = '' ): int {
+ $target = $sha;
+ $result = 0;
+
+ if( $path !== '' ) {
+ $info = $this->resolvePath(
+ $this->getTreeSha( $this->resolve( $sha ) ),
+ $path
+ );
+ $target = $info['sha'] ?? '';
+ }
+
+ if( $target !== '' ) {
+ $result = $this->packs->getSize( $target );
+
+ if( $result === 0 ) {
+ $result = $this->getLooseObjectSize( $target );
+ }
+ }
+
+ return $result;
+ }
+
+ public function stream(
+ string $sha,
+ callable $callback,
+ string $path = ''
+ ): void {
+ $target = $sha;
+
+ if( $path !== '' ) {
+ $info = $this->resolvePath(
+ $this->getTreeSha( $this->resolve( $sha ) ),
+ $path
+ );
+ $target = isset( $info['isDir'] ) && !$info['isDir']
+ ? $info['sha']
+ : '';
+ }
+
+ if( $target !== '' ) {
+ $this->slurp( $target, $callback );
+ }
+ }
+
+ public function peek( string $sha, int $length = 255 ): string {
+ $size = $this->packs->getSize( $sha );
+
+ return $size === 0
+ ? $this->peekLooseObject( $sha, $length )
+ : $this->packs->peek( $sha, $length );
+ }
+
+ public function read( string $sha ): string {
+ $size = $this->getObjectSize( $sha );
+ $content = '';
+
+ if( $size > 0 && $size <= self::MAX_READ ) {
+ $this->slurp( $sha, function( $chunk ) use ( &$content ) {
+ $content .= $chunk;
+ } );
+ }
+
+ return $content;
+ }
+
+ public function history(
+ string $ref,
+ int $limit,
+ callable $callback
+ ): void {
+ $sha = $this->resolve( $ref );
+ $count = 0;
+ $done = false;
+
+ while( !$done && $sha !== '' && $count < $limit ) {
+ $commit = $this->parseCommit( $sha );
+
+ if( $commit['sha'] === '' ) {
+ $sha = '';
+ $done = true;
+ } elseif( $callback( $commit ) === false ) {
+ $done = true;
+ } else {
+ $sha = $commit['parentSha'];
+ $count++;
+ }
+ }
+ }
+
+ public function streamRaw( string $subPath ): bool {
+ $result = false;
+
+ if( \strpos( $subPath, '..' ) === false ) {
+ $path = "{$this->repoPath}/$subPath";
+
+ if( \is_file( $path ) ) {
+ $real = \realpath( $path );
+ $repo = \realpath( $this->repoPath );
+
+ if( $real !== false && \strpos( $real, $repo ) === 0 ) {
+ \header( 'X-Accel-Redirect: ' . $path );
+ \header( 'Content-Type: application/octet-stream' );
+ $result = true;
+ }
+ }
+ }
+
+ return $result;
+ }
+
+ public function eachRef( callable $callback ): void {
+ $head = $this->resolve( 'HEAD' );
+
+ if( $head !== '' ) {
+ $callback( 'HEAD', $head );
+ }
+
+ $this->refs->scanRefs(
+ 'refs/heads',
+ function( $n, $s ) use ( $callback ) {
+ $callback( "refs/heads/$n", $s );
+ }
+ );
+
+ $this->refs->scanRefs(
+ 'refs/tags',
+ function( $n, $s ) use ( $callback ) {
+ $callback( "refs/tags/$n", $s );
+ }
+ );
+ }
+
+ public function generatePackfile( array $objs ): Generator {
+ $ctx = \hash_init( 'sha1' );
+ $head = "PACK" . \pack( 'N', 2 ) . \pack( 'N', \count( $objs ) );
+
+ \hash_update( $ctx, $head );
+ yield $head;
+
+ foreach( $objs as $sha => $type ) {
+ $size = $this->getObjectSize( $sha );
+ $byte = $type << 4 | $size & 0x0f;
+ $sz = $size >> 4;
+ $hdr = '';
+
+ while( $sz > 0 ) {
+ $hdr .= \chr( $byte | 0x80 );
+ $byte = $sz & 0x7f;
+ $sz >>= 7;
+ }
+
+ $hdr .= \chr( $byte );
+ \hash_update( $ctx, $hdr );
+ yield $hdr;
+
+ foreach( $this->streamCompressed( $sha ) as $compressed ) {
+ \hash_update( $ctx, $compressed );
+ yield $compressed;
+ }
+ }
+
+ yield \hash_final( $ctx, true );
+ }
+
+ private function streamCompressed( string $sha ): Generator {
+ $yielded = false;
+
+ foreach( $this->packs->streamRawCompressed( $sha ) as $chunk ) {
+ $yielded = true;
+ yield $chunk;
+ }
+
+ if( !$yielded ) {
+ $deflate = \deflate_init( \ZLIB_ENCODING_DEFLATE );
+
+ foreach( $this->slurpChunks( $sha ) as $raw ) {
+ $compressed = \deflate_add( $deflate, $raw, \ZLIB_NO_FLUSH );
+
+ if( $compressed !== '' ) {
+ yield $compressed;
+ }
+ }
+
+ $final = \deflate_add( $deflate, '', \ZLIB_FINISH );
+
+ if( $final !== '' ) {
+ yield $final;
+ }
+ }
+ }
+
+ private function slurpChunks( string $sha ): Generator {
+ $path = $this->getLoosePath( $sha );
+
+ if( \is_file( $path ) ) {
+ foreach( $this->streamInflatedObjects( $path ) as $chunk ) {
+ if( $chunk['body'] !== '' ) {
+ yield $chunk['body'];
+ }
+ }
+ } else {
+ $any = false;
+
+ foreach( $this->packs->streamGenerator( $sha ) as $chunk ) {
+ $any = true;
+ yield $chunk;
+ }
+
+ if( !$any ) {
+ $data = $this->packs->read( $sha );
+
+ if( $data !== '' ) {
+ yield $data;
+ }
+ }
+ }
+ }
+
+ private function streamInflatedObjects(
+ string $path,
+ int $bufSz = 16384
+ ): Generator {
+ $reader = new BufferedReader( $path );
+ $infl = $reader->isOpen()
+ ? \inflate_init( \ZLIB_ENCODING_DEFLATE )
+ : false;
+
+ if( $reader->isOpen() && $infl !== false ) {
+ $found = false;
+ $buffer = '';
+
+ while( !$reader->eof() ) {
+ $chunk = $reader->read( $bufSz );
+ $inflated = \inflate_add( $infl, $chunk );
+
+ if( $inflated === false ) {
+ break;
+ }
+
+ if( !$found ) {
+ $buffer .= $inflated;
+ $eos = \strpos( $buffer, "\0" );
+
+ if( $eos !== false ) {
+ $found = true;
+
+ yield [
+ 'head' => \substr( $buffer, 0, $eos ),
+ 'body' => \substr( $buffer, $eos + 1 )
+ ];
+ }
+ } elseif( $inflated !== '' ) {
+ yield [ 'head' => '', 'body' => $inflated ];
+ }
+ }
+ }
+ }
+
+ private function getTreeSha( string $commitOrTreeSha ): string {
+ $data = $this->read( $commitOrTreeSha );
+ $sha = $commitOrTreeSha;
+
+ if( \preg_match( '/^object ([0-9a-f]{40})/m', $data, $matches ) ) {
+ $sha = $this->getTreeSha( $matches[1] );
+ }
+
+ if( $sha === $commitOrTreeSha &&
+ \preg_match( '/^tree ([0-9a-f]{40})/m', $data, $matches ) ) {
+ $sha = $matches[1];
+ }
+
+ return $sha;
+ }
+
+ private function resolvePath( string $treeSha, string $path ): array {
+ $parts = \explode( '/', \trim( $path, '/' ) );
+ $sha = $treeSha;
+ $mode = '40000';
+
+ foreach( $parts as $part ) {
+ $entry = $part !== '' && $sha !== ''
+ ? $this->findTreeEntry( $sha, $part )
+ : [ 'sha' => '', 'mode' => '' ];
+
+ $sha = $entry['sha'];
+ $mode = $entry['mode'];
+ }
+
+ return [
+ 'sha' => $sha,
+ 'mode' => $mode,
+ 'isDir' => $mode === '40000' || $mode === '040000'
+ ];
+ }
+
+ private function findTreeEntry( string $treeSha, string $name ): array {
+ $entry = [ 'sha' => '', 'mode' => '' ];
+
+ $this->parseTreeData(
+ $this->read( $treeSha ),
+ function( $n, $s, $m ) use ( $name, &$entry ) {
+ if( $n === $name ) {
+ $entry = [ 'sha' => $s, 'mode' => $m ];
+
+ return false;
+ }
+ }
+ );
+
+ return $entry;
+ }
+
+ private function parseTagData(
+ string $name,
+ string $sha,
+ string $data
+ ): Tag {
+ $isAnn = \strncmp( $data, 'object ', 7 ) === 0;
+ $id = $this->parseIdentity(
+ $data,
+ $isAnn
+ ? '/^tagger (.*) <(.*)> (\d+) [+\-]\d{4}$/m'
+ : '/^author (.*) <(.*)> (\d+) [+\-]\d{4}$/m'
+ );
+
+ return new Tag(
+ $name,
+ $sha,
+ $isAnn ? $this->extractPattern( $data, '/^object (.*)$/m', 1, $sha ) : $sha,
+ $id['timestamp'],
+ $this->extractMessage( $data ),
+ $id['name']
+ );
+ }
+
+ private function extractPattern(
+ string $data,
+ string $pattern,
+ int $group,
+ string $default = ''
+ ): string {
+ return \preg_match( $pattern, $data, $matches )
+ ? $matches[$group]
+ : $default;
+ }
+
+ private function parseIdentity( string $data, string $pattern ): array {
+ $found = \preg_match( $pattern, $data, $matches );
+
+ return [
+ 'name' => $found ? \trim( $matches[1] ) : 'Unknown',
+ 'email' => $found ? $matches[2] : '',
+ 'timestamp' => $found ? (int)$matches[3] : 0
+ ];
+ }
+
+ private function extractMessage( string $data ): string {
+ $pos = \strpos( $data, "\n\n" );
+
+ return $pos !== false ? \trim( \substr( $data, $pos + 2 ) ) : '';
+ }
+
+ private function slurp( string $sha, callable $callback ): void {
+ $path = $this->getLoosePath( $sha );
+
+ if( \is_file( $path ) ) {
+ foreach( $this->streamInflatedObjects( $path ) as $chunk ) {
+ if( $chunk['body'] !== '' ) {
+ $callback( $chunk['body'] );
+ }
+ }
+ } elseif( !$this->packs->stream( $sha, $callback ) ) {
+ $data = $this->packs->read( $sha );
+
+ if( $data !== '' ) {
+ $callback( $data );
+ }
+ }
+ }
+
+ private function peekLooseObject( string $sha, int $length ): string {
+ $path = $this->getLoosePath( $sha );
+ $buf = '';
+
+ if( \is_file( $path ) ) {
+ foreach( $this->streamInflatedObjects( $path, 8192 ) as $chunk ) {
+ $buf .= $chunk['body'];
+
+ if( \strlen( $buf ) >= $length ) {
+ break;
+ }
+ }
+ }
+
+ return \substr( $buf, 0, $length );
+ }
+
+ private function parseCommit( string $sha ): array {
+ $data = $this->read( $sha );
+ $result = [ 'sha' => '' ];
+
+ if( $data !== '' ) {
+ $id = $this->parseIdentity( $data, '/^author (.*) <(.*)> (\d+)/m' );
+
+ $result = [
+ 'sha' => $sha,
+ 'message' => $this->extractMessage( $data ),
+ 'author' => $id['name'],
+ 'email' => $id['email'],
+ 'date' => $id['timestamp'],
+ 'parentSha' => $this->extractPattern( $data, '/^parent (.*)$/m', 1 )
+ ];
+ }
+
+ return $result;
+ }
+
+ private function walkTree( string $sha, callable $callback ): void {
+ $data = $this->read( $sha );
+ $tree = $data !== '' && \preg_match( '/^tree (.*)$/m', $data, $m )
+ ? $this->read( $m[1] )
+ : $data;
+
+ if( $tree !== '' && $this->isTreeData( $tree ) ) {
+ $this->parseTreeData(
+ $tree,
+ function( $n, $s, $m ) use ( $callback ) {
+ $dir = $m === '40000' || $m === '040000';
+ $isSub = $m === '160000';
+
+ $callback( new File(
+ $n,
+ $s,
+ $m,
+ 0,
+ $dir || $isSub ? 0 : $this->getObjectSize( $s ),
+ $dir || $isSub ? '' : $this->peek( $s )
+ ) );
+ }
+ );
+ }
+ }
+
+ public function parseTreeData( string $data, callable $callback ): void {
+ $pos = 0;
+ $len = \strlen( $data );
+
+ while( $pos < $len ) {
+ $space = \strpos( $data, ' ', $pos );
+ $eos = \strpos( $data, "\0", $space );
+
+ if( $space === false || $eos === false || $eos + 21 > $len ) {
+ break;
+ }
+
+ $mode = \substr( $data, $pos, $space - $pos );
+ $name = \substr( $data, $space + 1, $eos - $space - 1 );
+ $sha = \bin2hex( \substr( $data, $eos + 1, 20 ) );
+
+ if( $callback( $name, $sha, $mode ) === false ) {
+ break;
+ }
+
+ $pos = $eos + 21;
+ }
+ }
+
+ private function isTreeData( string $data ): bool {
+ $len = \strlen( $data );
+ $match = $len >= 25 &&
+ \preg_match( '/^(40000|100644|100755|120000|160000) /', $data );
+ $eos = $match ? \strpos( $data, "\0" ) : false;
+
+ return $match && $eos !== false && $eos + 21 <= $len;
+ }
+
+ private function getLoosePath( string $sha ): string {
+ return "{$this->objPath}/" . \substr( $sha, 0, 2 ) . "/" .
+ \substr( $sha, 2 );
+ }
+
+ private function getLooseObjectSize( string $sha ): int {
+ $path = $this->getLoosePath( $sha );
+ $size = 0;
+
+ if( \is_file( $path ) ) {
+ foreach( $this->streamInflatedObjects( $path ) as $chunk ) {
+ $parts = \explode( ' ', $chunk['head'] );
+ $size = isset( $parts[1] ) ? (int)$parts[1] : 0;
+ break;
+ }
+ }
+
+ return $size;
+ }
+
+ public function collectObjects( array $wants, array $haves = [] ): array {
+ $objs = $this->traverseObjects( $wants );
+
+ if( !empty( $haves ) ) {
+ foreach( $this->traverseObjects( $haves ) as $sha => $type ) {
+ unset( $objs[$sha] );
+ }
+ }
+
+ return $objs;
+ }
+
+ private function traverseObjects( array $roots ): array {
+ $objs = [];
+ $queue = [];
+
+ foreach( $roots as $sha ) {
+ $queue[] = [ 'sha' => $sha, 'type' => 0 ];
+ }
+
+ while( !empty( $queue ) ) {
+ $item = \array_pop( $queue );
+ $sha = $item['sha'];
+ $type = $item['type'];
+
+ if( !isset( $objs[$sha] ) ) {
+ $data = $type !== 3 ? $this->read( $sha ) : '';
+ $type = $type === 0 ? $this->getObjectType( $data ) : $type;
+
+ $objs[$sha] = $type;
+
+ if( $type === 1 ) {
+ if( \preg_match( '/^tree ([0-9a-f]{40})/m', $data, $m ) ) {
+ $queue[] = [ 'sha' => $m[1], 'type' => 2 ];
+ }
+
+ if( \preg_match_all( '/^parent ([0-9a-f]{40})/m', $data, $m ) ) {
+ foreach( $m[1] as $parentSha ) {
+ $queue[] = [ 'sha' => $parentSha, 'type' => 1 ];
+ }
+ }
+ } elseif( $type === 2 ) {
+ $pos = 0;
+ $len = \strlen( $data );
+
+ while( $pos < $len ) {
+ $space = \strpos( $data, ' ', $pos );
+ $eos = \strpos( $data, "\0", $space );
+
+ if( $space === false || $eos === false ) {
+ break;
+ }
+
+ $mode = \substr( $data, $pos, $space - $pos );
+ $hash = \bin2hex( \substr( $data, $eos + 1, 20 ) );
+
+ if( $mode !== '160000' ) {
+ $queue[] = [
+ 'sha' => $hash,
+ 'type' => $mode === '40000' || $mode === '040000' ? 2 : 3
+ ];
+ }
+
+ $pos = $eos + 21;
+ }
+ } elseif( $type === 4 ) {
+ if( \preg_match( '/^object ([0-9a-f]{40})/m', $data, $m ) ) {
+ $nextType = 1;
+
+ if( \preg_match( '/^type (commit|tree|blob|tag)/m', $data, $t ) ) {
+ $map = [
+ 'commit' => 1,
+ 'tree' => 2,
+ 'blob' => 3,
+ 'tag' => 4
+ ];
+ $nextType = $map[$t[1]] ?? 1;
+ }
+
+ $queue[] = [ 'sha' => $m[1], 'type' => $nextType ];
+ }
+ }
+ }
+ }
+
+ return $objs;
+ }
+
+ private function getObjectType( string $data ): int {
+ $result = 3;
+
+ if( \strpos( $data, "tree " ) === 0 ) {
+ $result = 1;
+ } elseif( \strpos( $data, "object " ) === 0 ) {
$result = 4;
} elseif( $this->isTreeData( $data ) ) {
git/PackEntryReader.php
return $context->computeIntDedicated(
function( StreamReader $stream, int $offset ): int {
- $stream->seek( $offset );
-
- $header = $this->readVarInt( $stream );
- $size = $header['value'];
- $type = $header['byte'] >> 4 & 7;
-
- if( $type === 6 || $type === 7 ) {
- $size = $this->decoder->readDeltaTargetSize( $stream, $type );
- }
+ $hdr = $this->readEntryHeader( $stream, $offset );
- return $size;
+ return $hdr['type'] === 6 || $hdr['type'] === 7
+ ? $this->decoder->readDeltaTargetSize( $stream, $hdr['type'] )
+ : $hdr['size'];
},
0
): string {
return $context->computeStringDedicated(
- function( StreamReader $stream, int $offset ) use (
- $cap,
- $readShaBaseFn
- ): string {
- return $this->readWithStream(
- $stream,
- $offset,
- $cap,
- $readShaBaseFn
- );
+ function( StreamReader $s, int $o ) use ( $cap, $readShaBaseFn ): string {
+ return $this->readWithStream( $s, $o, $cap, $readShaBaseFn );
},
''
if( isset( $this->cache[$offset] ) ) {
- $result = $this->cache[$offset];
-
- if( $cap > 0 && \strlen( $result ) > $cap ) {
- $result = \substr( $result, 0, $cap );
- }
+ $result = $cap > 0 && \strlen( $this->cache[$offset] ) > $cap
+ ? \substr( $this->cache[$offset], 0, $cap )
+ : $this->cache[$offset];
} else {
- $stream->seek( $offset );
-
- $header = $this->readVarInt( $stream );
- $type = $header['byte'] >> 4 & 7;
+ $hdr = $this->readEntryHeader( $stream, $offset );
+ $type = $hdr['type'];
if( $type === 6 ) {
yield from $context->streamGenerator(
function( StreamReader $stream, int $offset ): Generator {
- $stream->seek( $offset );
-
- $header = $this->readVarInt( $stream );
- $type = $header['byte'] >> 4 & 7;
- $gen = [];
-
- if( $type !== 6 && $type !== 7 ) {
- $gen = CompressionStream::createExtractor()->stream( $stream );
- }
+ $hdr = $this->readEntryHeader( $stream, $offset );
- yield from $gen;
+ yield from $hdr['type'] !== 6 && $hdr['type'] !== 7
+ ? CompressionStream::createExtractor()->stream( $stream )
+ : [];
}
);
}
public function streamEntryGenerator( PackContext $context ): Generator {
yield from $context->streamGeneratorDedicated(
function( StreamReader $stream, int $offset ) use (
$context
): Generator {
- $stream->seek( $offset );
+ $hdr = $this->readEntryHeader( $stream, $offset );
- $header = $this->readVarInt( $stream );
- $type = $header['byte'] >> 4 & 7;
- $gen = $type === 6 || $type === 7
+ yield from $hdr['type'] === 6 || $hdr['type'] === 7
? $this->streamDeltaObjectGenerator(
$stream,
$context,
- $type,
+ $hdr['type'],
$offset
)
: CompressionStream::createInflater()->stream( $stream );
-
- yield from $gen;
}
);
+ }
+
+ private function readEntryHeader( StreamReader $stream, int $offset ): array {
+ $stream->seek( $offset );
+
+ $header = $this->readVarInt( $stream );
+
+ return [
+ 'type' => $header['byte'] >> 4 & 7,
+ 'size' => $header['value']
+ ];
}
private function streamDeltaObjectGenerator(
StreamReader $stream,
PackContext $context,
int $type,
int $offset
): Generator {
- $gen = [];
-
- if( $context->isWithinDepth( self::MAX_DEPTH ) ) {
- $gen = $type === 6
- ? $this->processOffsetDelta( $stream, $context, $offset )
- : $this->processRefDelta( $stream, $context );
- }
+ $gen = $context->isWithinDepth( self::MAX_DEPTH )
+ ? ( $type === 6
+ ? $this->processOffsetDelta( $stream, $context, $offset )
+ : $this->processRefDelta( $stream, $context )
+ )
+ : [];
yield from $gen;
}
-
- private function readSizeWithStream(
- StreamReader $stream,
- int $offset
- ): int {
- if( isset( $this->cache[$offset] ) ) {
- return \strlen( $this->cache[$offset] );
- }
- $cur = $stream->tell();
+ private function readSizeWithStream( StreamReader $stream, int $offset ): int {
+ $result = 0;
- $stream->seek( $offset );
+ if( isset( $this->cache[$offset] ) ) {
+ $result = \strlen( $this->cache[$offset] );
+ } else {
+ $cur = $stream->tell();
+ $hdr = $this->readEntryHeader( $stream, $offset );
- $header = $this->readVarInt( $stream );
- $size = $header['value'];
- $type = $header['byte'] >> 4 & 7;
+ $result = $hdr['type'] === 6 || $hdr['type'] === 7
+ ? $this->decoder->readDeltaTargetSize( $stream, $hdr['type'] )
+ : $hdr['size'];
- if( $type === 6 || $type === 7 ) {
- $size = $this->decoder->readDeltaTargetSize( $stream, $type );
+ $stream->seek( $cur );
}
-
- $stream->seek( $cur );
- return $size;
+ return $result;
}
if( isset( $this->cache[$baseOff] ) ) {
$baseSrc = $this->cache[$baseOff];
- } elseif( $this->readSizeWithStream( $stream, $baseOff ) <= self::MAX_BASE_RAM ) {
+ } elseif(
+ $this->readSizeWithStream( $stream, $baseOff ) <= self::MAX_BASE_RAM
+ ) {
$baseSrc = $this->readWithStream(
$stream,
$baseOff,
0,
function( string $sha, int $cap ) use ( $context ): string {
return $this->resolveBaseSha( $sha, $cap, $context );
}
);
} else {
- $baseCtx = $context->deriveOffsetContext( $neg );
- [ $b, $tmp ] = $this->collectBase(
+ $baseCtx = $context->deriveOffsetContext( $neg );
+ [$b, $tmp] = $this->collectBase(
$this->streamEntryGenerator( $baseCtx )
);
- $baseSrc = $tmp instanceof BufferedReader ? $tmp : $b;
+ $baseSrc = $tmp instanceof BufferedReader ? $tmp : $b;
}
$baseSrc = $this->resolveBaseSha( $baseSha, 0, $context );
} else {
- [ $b, $tmp ] = $this->collectBase(
+ [$b, $tmp] = $this->collectBase(
$context->resolveBaseStream( $baseSha )
);
- $baseSrc = $tmp instanceof BufferedReader ? $tmp : $b;
+ $baseSrc = $tmp instanceof BufferedReader ? $tmp : $b;
}
while( $byte & 128 ) {
$byte = isset( $data[$pos] ) ? \ord( $data[$pos++] ) : 0;
- $val |= ($byte & 127) << $shft;
+ $val |= ( $byte & 127 ) << $shft;
$shft += 7;
}
$rem = \strlen( $data ) - $pos;
- $rem > 0 ? $stream->seek( -$rem, SEEK_CUR ) : null;
+ if( $rem > 0 ) {
+ $stream->seek( -$rem, SEEK_CUR );
+ }
return [ 'value' => $val, 'byte' => $fst ];
while( $byte & 128 ) {
$byte = isset( $data[$pos] ) ? \ord( $data[$pos++] ) : 0;
- $result = ($result + 1) << 7 | $byte & 127;
+ $result = ( $result + 1 ) << 7 | $byte & 127;
}
git/PackStreamManager.php
private function release( string $path, BufferedReader $reader ): void {
- isset( $this->readers[$path] ) ? null : $this->readers[$path] = [];
+ if( !isset( $this->readers[$path] ) ) {
+ $this->readers[$path] = [];
+ }
$this->readers[$path][] = $reader;
pages/ClonePage.php
}
- public function render() {
- if( $this->subPath === '' ) {
+ public function render(): void {
+ $path = $this->subPath;
+
+ if( $path === '' ) {
$this->redirectBrowser();
- } elseif( str_ends_with( $this->subPath, 'info/refs' ) ) {
+ } elseif( \str_ends_with( $path, 'info/refs' ) ) {
$this->renderInfoRefs();
- } elseif( str_ends_with( $this->subPath, 'git-upload-pack' ) ) {
+ } elseif( \str_ends_with( $path, 'git-upload-pack' ) ) {
$this->handleUploadPack();
- } elseif( str_ends_with( $this->subPath, 'git-receive-pack' ) ) {
- http_response_code( 403 );
+ } elseif( \str_ends_with( $path, 'git-receive-pack' ) ) {
+ \http_response_code( 403 );
echo "Read-only repository.";
- } elseif( $this->subPath === 'HEAD' ) {
+ } elseif( $path === 'HEAD' ) {
$this->serve( 'HEAD', 'text/plain' );
- } elseif( strpos( $this->subPath, 'objects/' ) === 0 ) {
- $this->serve( $this->subPath, 'application/x-git-object' );
+ } elseif( \strpos( $path, 'objects/' ) === 0 ) {
+ $this->serve( $path, 'application/x-git-object' );
} else {
- http_response_code( 404 );
+ \http_response_code( 404 );
echo "Not Found";
}
exit;
}
private function redirectBrowser(): void {
- $url = str_replace( '.git', '', $_SERVER['REQUEST_URI'] );
-
- header( "Location: $url" );
+ \header(
+ "Location: " . \str_replace( '.git', '', $_SERVER['REQUEST_URI'] )
+ );
}
private function renderInfoRefs(): void {
- $service = $_GET['service'] ?? '';
-
- if( $service === 'git-upload-pack' ) {
- header( 'Content-Type: application/x-git-upload-pack-advertisement' );
- header( 'Cache-Control: no-cache' );
+ if( ( $_GET['service'] ?? '' ) === 'git-upload-pack' ) {
+ \header( 'Content-Type: application/x-git-upload-pack-advertisement' );
+ \header( 'Cache-Control: no-cache' );
$this->packetWrite( "# service=git-upload-pack\n" );
$this->packetFlush();
$refs = [];
+
$this->git->eachRef( function( $ref, $sha ) use ( &$refs ) {
- $refs[] = ['ref' => $ref, 'sha' => $sha];
+ $refs[] = [ 'ref' => $ref, 'sha' => $sha ];
} );
);
- for( $i = 1; $i < count( $refs ); $i++ ) {
+ for( $i = 1; $i < \count( $refs ); $i++ ) {
$this->packetWrite(
$refs[$i]['sha'] . " " . $refs[$i]['ref'] . "\n"
);
}
}
$this->packetFlush();
} else {
- header( 'Content-Type: text/plain' );
+ \header( 'Content-Type: text/plain' );
if( !$this->git->streamRaw( 'info/refs' ) ) {
private function handleUploadPack(): void {
- set_time_limit( 0 );
-
- header( 'Content-Type: application/x-git-upload-pack-result' );
- header( 'Cache-Control: no-cache' );
+ \set_time_limit( 0 );
+ \header( 'Content-Type: application/x-git-upload-pack-result' );
+ \header( 'Cache-Control: no-cache' );
$wants = [];
$haves = [];
- $handle = fopen( 'php://input', 'rb' );
+ $handle = \fopen( 'php://input', 'rb' );
if( $handle ) {
- // If the input is gzipped, we wrap the stream
if( isset( $_SERVER['HTTP_CONTENT_ENCODING'] ) &&
$_SERVER['HTTP_CONTENT_ENCODING'] === 'gzip' ) {
- stream_filter_append( $handle, 'zlib.inflate', STREAM_FILTER_READ, [
- 'window' => 31
- ] );
+ \stream_filter_append(
+ $handle,
+ 'zlib.inflate',
+ \STREAM_FILTER_READ,
+ [ 'window' => 31 ]
+ );
}
-
- while( !feof( $handle ) ) {
- $lenHex = fread( $handle, 4 );
-
- if( strlen( $lenHex ) < 4 ) {
- break;
- }
- $len = hexdec( $lenHex );
+ while( !\feof( $handle ) ) {
+ $lenHex = \fread( $handle, 4 );
+ $len = \strlen( $lenHex ) === 4 ? \hexdec( $lenHex ) : 0;
- if( $len === 0 ) { // Flush packet
+ if( $len === 0 ) {
break;
- }
-
- if( $len <= 4 ) {
- continue;
}
-
- $line = fread( $handle, $len - 4 );
- $trim = trim( $line );
- if( strpos( $trim, 'want ' ) === 0 ) {
- $wants[] = explode( ' ', $trim )[1];
- } elseif( strpos( $trim, 'have ' ) === 0 ) {
- $haves[] = explode( ' ', $trim )[1];
- }
+ if( $len > 4 ) {
+ $trim = \trim( \fread( $handle, $len - 4 ) );
- if( $trim === 'done' ) {
- break;
+ if( \strpos( $trim, 'want ' ) === 0 ) {
+ $wants[] = \explode( ' ', $trim )[1];
+ } elseif( \strpos( $trim, 'have ' ) === 0 ) {
+ $haves[] = \explode( ' ', $trim )[1];
+ } elseif( $trim === 'done' ) {
+ break;
+ }
}
}
- fclose( $handle );
+ \fclose( $handle );
}
if( !empty( $wants ) ) {
$this->packetWrite( "NAK\n" );
- $objects = $this->git->collectObjects( $wants, $haves );
- $lastHeartbeat = time();
+ $objects = $this->git->collectObjects( $wants, $haves );
+ $lastHb = \time();
foreach( $this->git->generatePackfile( $objects ) as $chunk ) {
if( $chunk !== '' ) {
$this->sendSidebandData( 1, $chunk );
}
- $now = time();
- if( $now - $lastHeartbeat >= 5 ) {
+ $now = \time();
+
+ if( $now - $lastHb >= 5 ) {
$this->sendSidebandData( 2, "\r" );
- $lastHeartbeat = $now;
+ $lastHb = $now;
}
}
}
$this->packetFlush();
}
private function sendSidebandData( int $band, string $data ): void {
$chunkSize = 65515;
- $len = strlen( $data );
+ $len = \strlen( $data );
for( $offset = 0; $offset < $len; $offset += $chunkSize ) {
- $chunk = substr( $data, $offset, $chunkSize );
-
- $this->packetWrite( chr( $band ) . $chunk );
- }
- }
-
- private function readPacketLine( string $input, int $offset ): array {
- $line = '';
- $next = $offset;
-
- if( $offset + 4 <= strlen( $input ) ) {
- $lenHex = substr( $input, $offset, 4 );
-
- if( ctype_xdigit( $lenHex ) ) {
- $len = hexdec( $lenHex );
-
- if( $len === 0 ) {
- $next = $offset + 4;
- } elseif( $len >= 4 ) {
- if( $offset + $len <= strlen( $input ) ) {
- $line = substr( $input, $offset + 4, $len - 4 );
- $next = $offset + $len;
- }
- }
- }
+ $this->packetWrite(
+ \chr( $band ) . \substr( $data, $offset, $chunkSize )
+ );
}
-
- return [$line, $next];
}
private function serve( string $path, string $contentType ): void {
- header( 'Content-Type: ' . $contentType );
+ \header( 'Content-Type: ' . $contentType );
if( !$this->git->streamRaw( $path ) ) {
- http_response_code( 404 );
+ \http_response_code( 404 );
echo "Missing: $path";
}
}
private function packetWrite( string $data ): void {
- printf( "%04x%s", strlen( $data ) + 4, $data );
+ \printf( "%04x%s", \strlen( $data ) + 4, $data );
}
Delta860 lines added, 1021 lines removed, 161-line decrease