Dave Jarvis' Repositories

git clone https://repo.autonoma.ca/repo/treetrek.git
<?php
require_once __DIR__ . '/Page.php';

class ClonePage implements Page {
  private $git;
  private $subPath;

  public function __construct( Git $git, string $subPath ) {
    $this->git = $git;
    $this->subPath = $subPath;
  }

  public function render() {
    if( $this->subPath === 'info/refs' ) {
      $this->renderInfoRefs();
      return;
    }

    if( $this->subPath === 'HEAD' ) {
      $this->serve( 'HEAD', 'text/plain' );
      return;
    }

    if( strpos( $this->subPath, 'objects/' ) === 0 ) {
      $this->serve( $this->subPath, 'application/x-git-object' );
      return;
    }

    $this->serve( $this->subPath, 'text/plain' );
  }

  private function renderInfoRefs(): void {
    header( 'Content-Type: text/plain' );

    if( $this->git->streamRaw( 'info/refs' ) ) {
      exit;
    }

    $this->git->eachRef( function( $ref, $sha ) {
      echo "$sha\t$ref\n";
    } );

    exit;
  }

  private function serve( string $path, string $contentType ): void {
    header( 'Content-Type: ' . $contentType );

    $success = $this->git->streamRaw( $path );

    if( !$success ) {
      http_response_code( 404 );
      echo "File not found: $path";
    }

    exit;
  }
}