public function download(PackageInterface $package, $targetDir, $preferSource = null)
    {
        $preferSource = null !== $preferSource ? $preferSource : $this->preferSource;
        $sourceType = $package->getSourceType();
        $distType = $package->getDistType();

        $sources = array();
        if ($sourceType) {
            $sources[] = 'source';
        }
        if ($distType) {
            $sources[] = 'dist';
        }

        if (empty($sources)) {
            throw new \InvalidArgumentException('Package '.$package.' must have a source or dist specified');
        }

        if (!$preferSource && ($this->preferDist || 'dist' === $this->resolvePackageInstallPreference($package))) {
            $sources = array_reverse($sources);
        }

        $this->filesystem->ensureDirectoryExists($targetDir);

        foreach ($sources as $i => $source) {
            if (isset($e)) {
                $this->io->writeError('    <warning>Now trying to download from ' . $source . '</warning>');
            }
            $package->setInstallationSource($source);
            try {
                $downloader = $this->getDownloaderForInstalledPackage($package);
                if ($downloader) {
                    $downloader->download($package, $targetDir);
                }
                break;
            } catch (\RuntimeException $e) {
                if ($i === count($sources) - 1) {
                    throw $e;
                }

                $this->io->writeError(
                    '    <warning>Failed to download '.
                    $package->getPrettyName().
                    ' from ' . $source . ': '.
                    $e->getMessage().'</warning>'
                );
            }
        }
    }