Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: bdca728311
Fetching contributors…

Cannot retrieve contributors at this time

file 258 lines (219 sloc) 10.797 kb
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
<?php

/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Composer\Downloader;

use Composer\Package\PackageInterface;

/**
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class GitDownloader extends VcsDownloader
{
    /**
* {@inheritDoc}
*/
    public function doDownload(PackageInterface $package, $path)
    {
        $ref = $package->getSourceReference();
        $command = 'git clone %s %s && cd %2$s && git remote add composer %1$s && git fetch composer';
        $this->io->write(" Cloning ".$ref);

        // added in git 1.7.1, prevents prompting the user
        putenv('GIT_ASKPASS=echo');
        $commandCallable = function($url) use ($ref, $path, $command) {
            return sprintf($command, escapeshellarg($url), escapeshellarg($path), escapeshellarg($ref));
        };

        $this->runCommand($commandCallable, $package->getSourceUrl(), $path);
        $this->setPushUrl($package, $path);

        $this->updateToCommit($path, $ref, $package->getPrettyVersion(), $package->getReleaseDate());
    }

    /**
* {@inheritDoc}
*/
    public function doUpdate(PackageInterface $initial, PackageInterface $target, $path)
    {
        $ref = $target->getSourceReference();
        $this->io->write(" Checking out ".$ref);
        $command = 'cd %s && git remote set-url composer %s && git fetch composer && git fetch --tags composer';

        // capture username/password from github URL if there is one
        $this->process->execute(sprintf('cd %s && git remote -v', escapeshellarg($path)), $output);
        if (preg_match('{^composer\s+https://(.+):(.+)@'.$this->getGitHubDomainsRegex().'/}im', $output, $match)) {
            $this->io->setAuthorization($match[3], $match[1], $match[2]);
        }

        $commandCallable = function($url) use ($ref, $path, $command) {
            return sprintf($command, escapeshellarg($path), escapeshellarg($url), escapeshellarg($ref));
        };

        $this->runCommand($commandCallable, $target->getSourceUrl());
        $this->updateToCommit($path, $ref, $target->getPrettyVersion(), $target->getReleaseDate());
    }

    /**
* {@inheritDoc}
*/
    public function getLocalChanges($path)
    {
        $command = sprintf('cd %s && git status --porcelain --untracked-files=no', escapeshellarg($path));
        if (0 !== $this->process->execute($command, $output)) {
            throw new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput());
        }

        return trim($output) ?: null;
    }

    protected function updateToCommit($path, $reference, $branch, $date)
    {
        $template = 'git checkout %s && git reset --hard %1$s';

        // check whether non-commitish are branches or tags, and fetch branches with the remote name
        $gitRef = $reference;
        if (!preg_match('{^[a-f0-9]{40}$}', $reference)
            && 0 === $this->process->execute('git branch -r', $output, $path)
            && preg_match('{^\s+composer/'.preg_quote($reference).'$}m', $output)
        ) {
            $gitRef = 'composer/'.$reference;
        }

        $command = sprintf($template, escapeshellarg($gitRef));
        if (0 === $this->process->execute($command, $output, $path)) {
            return;
        }

        // reference was not found (prints "fatal: reference is not a tree: $ref")
        if ($date && false !== strpos($this->process->getErrorOutput(), $reference)) {
            $branch = preg_replace('{(?:^dev-|(?:\.x)?-dev$)}i', '', $branch);
            $date = $date->format('U');

            // guess which remote branch to look at first
            $command = 'git branch -r';
            if (0 !== $this->process->execute($command, $output, $path)) {
                throw new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput());
            }

            $guessTemplate = 'git log --until=%s --date=raw -n1 --pretty=%%H %s';
            foreach ($this->process->splitLines($output) as $line) {
                if (preg_match('{^composer/'.preg_quote($branch).'(?:\.x)?$}i', trim($line))) {
                    // find the previous commit by date in the given branch
                    if (0 === $this->process->execute(sprintf($guessTemplate, $date, escapeshellarg(trim($line))), $output, $path)) {
                        $newReference = trim($output);
                    }

                    break;
                }
            }

            if (empty($newReference)) {
                // no matching branch found, find the previous commit by date in all commits
                if (0 !== $this->process->execute(sprintf($guessTemplate, $date, '--all'), $output, $path)) {
                    throw new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput());
                }
                $newReference = trim($output);
            }

            // checkout the new recovered ref
            $command = sprintf($template, escapeshellarg($reference));
            if (0 === $this->process->execute($command, $output, $path)) {
                $this->io->write(' '.$reference.' is gone (history was rewritten?), recovered by checking out '.$newReference);

                return;
            }
        }

        throw new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput());
    }

    /**
* Runs a command doing attempts for each protocol supported by github.
*
* @param callable $commandCallable A callable building the command for the given url
* @param string $url
* @param string $path The directory to remove for each attempt (null if not needed)
* @throws \RuntimeException
*/
    protected function runCommand($commandCallable, $url, $path = null)
    {
        $handler = array($this, 'outputHandler');

        // public github, autoswitch protocols
        if (preg_match('{^(?:https?|git)(://'.$this->getGitHubDomainsRegex().'/.*)}', $url, $match)) {
            $protocols = $this->config->get('github-protocols');
            if (!is_array($protocols)) {
                throw new \RuntimeException('Config value "github-protocols" must be an array, got '.gettype($protocols));
            }
            $messages = array();
            foreach ($protocols as $protocol) {
                $url = $protocol . $match[1];
                if (0 === $this->process->execute(call_user_func($commandCallable, $url), $handler)) {
                    return;
                }
                $messages[] = '- ' . $url . "\n" . preg_replace('#^#m', ' ', $this->process->getErrorOutput());
                if (null !== $path) {
                    $this->filesystem->removeDirectory($path);
                }
            }

            // failed to checkout, first check git accessibility
            $this->throwException('Failed to clone ' . $url .' via git, https and http protocols, aborting.' . "\n\n" . implode("\n", $messages), $url);
        }

        $command = call_user_func($commandCallable, $url);
        if (0 !== $this->process->execute($command, $handler)) {
            if (preg_match('{^git@'.$this->getGitHubDomainsRegex().':(.+?)\.git$}i', $url, $match) && $this->io->isInteractive()) {
                // private github repository without git access, try https with auth
                $retries = 3;
                $retrying = false;
                do {
                    if ($retrying) {
                        $this->io->write('Invalid credentials');
                    }
                    if (!$this->io->hasAuthorization($match[1]) || $retrying) {
                        $username = $this->io->ask('Username: ');
                        $password = $this->io->askAndHideAnswer('Password: ');
                        $this->io->setAuthorization($match[1], $username, $password);
                    }

                    $auth = $this->io->getAuthorization($match[1]);
                    $url = 'https://'.$auth['username'] . ':' . $auth['password'] . '@'.$match[1].'/'.$match[2].'.git';

                    $command = call_user_func($commandCallable, $url);
                    if (0 === $this->process->execute($command, $handler)) {
                        return;
                    }
                    if (null !== $path) {
                        $this->filesystem->removeDirectory($path);
                    }
                    $retrying = true;
                } while (--$retries);
            }

            if (null !== $path) {
                $this->filesystem->removeDirectory($path);
            }
            $this->throwException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput(), $url);
        }
    }

    public function outputHandler($type, $buffer)
    {
        if ($type !== 'out') {
            return;
        }
        if ($this->io->isVerbose()) {
            $this->io->write($buffer, false);
        }
    }

    protected function getGitHubDomainsRegex()
    {
        return '('.implode('|', array_map('preg_quote', $this->config->get('github-domains'))).')';
    }

    protected function throwException($message, $url)
    {
        if (0 !== $this->process->execute('git --version', $ignoredOutput)) {
            throw new \RuntimeException('Failed to clone '.$url.', git was not found, check that it is installed and in your PATH env.' . "\n\n" . $this->process->getErrorOutput());
        }

        throw new \RuntimeException($message);
    }

    protected function setPushUrl(PackageInterface $package, $path)
    {
        // set push url for github projects
        if (preg_match('{^(?:https?|git)://'.$this->getGitHubDomainsRegex().'/([^/]+)/([^/]+?)(?:\.git)?$}', $package->getSourceUrl(), $match)) {
            $pushUrl = 'git@'.$match[1].':'.$match[2].'/'.$match[3].'.git';
            $cmd = sprintf('git remote set-url --push origin %s', escapeshellarg($pushUrl));
            $this->process->execute($cmd, $ignoredOutput, $path);
        }
    }

    /**
* {@inheritDoc}
*/
    protected function getCommitLogs($fromReference, $toReference, $path)
    {
        $command = sprintf('cd %s && git log %s..%s --pretty=format:"%%h - %%an: %%s"', escapeshellarg($path), $fromReference, $toReference);

        if (0 !== $this->process->execute($command, $output)) {
            throw new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput());
        }

        return $output;
    }
}
Something went wrong with that request. Please try again.