Skip to main content
Drupal API
User account menu
  • Log in

Breadcrumb

  1. Drupal Core 11.1.x
  2. ArchiveCommand.php

class ArchiveCommand

Creates an archive of a package for distribution.

@author Nils Adermann <naderman@naderman.de>

Hierarchy

  • class \Symfony\Component\Console\Command\Command
    • class \Composer\Command\BaseCommand extends \Symfony\Component\Console\Command\Command
      • class \Composer\Command\ArchiveCommand extends \Composer\Command\BaseCommand uses \Composer\Command\CompletionTrait

Expanded class hierarchy of ArchiveCommand

File

vendor/composer/composer/src/Composer/Command/ArchiveCommand.php, line 44

Namespace

Composer\Command
View source
class ArchiveCommand extends BaseCommand {
    use CompletionTrait;
    private const FORMATS = [
        'tar',
        'tar.gz',
        'tar.bz2',
        'zip',
    ];
    protected function configure() : void {
        $this->setName('archive')
            ->setDescription('Creates an archive of this composer package')
            ->setDefinition([
            new InputArgument('package', InputArgument::OPTIONAL, 'The package to archive instead of the current project', null, $this->suggestAvailablePackage()),
            new InputArgument('version', InputArgument::OPTIONAL, 'A version constraint to find the package to archive'),
            new InputOption('format', 'f', InputOption::VALUE_REQUIRED, 'Format of the resulting archive: tar, tar.gz, tar.bz2 or zip (default tar)', null, self::FORMATS),
            new InputOption('dir', null, InputOption::VALUE_REQUIRED, 'Write the archive to this directory'),
            new InputOption('file', null, InputOption::VALUE_REQUIRED, 'Write the archive with the given file name.' . ' Note that the format will be appended.'),
            new InputOption('ignore-filters', null, InputOption::VALUE_NONE, 'Ignore filters when saving package'),
        ])
            ->setHelp(<<<EOT
The <info>archive</info> command creates an archive of the specified format
containing the files and directories of the Composer project or the specified
package in the specified version and writes it to the specified directory.

<info>php composer.phar archive [--format=zip] [--dir=/foo] [--file=filename] [package [version]]</info>

Read more at https://getcomposer.org/doc/03-cli.md#archive
EOT
);
    }
    protected function execute(InputInterface $input, OutputInterface $output) : int {
        $composer = $this->tryComposer();
        $config = null;
        if ($composer) {
            $config = $composer->getConfig();
            $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'archive', $input, $output);
            $eventDispatcher = $composer->getEventDispatcher();
            $eventDispatcher->dispatch($commandEvent->getName(), $commandEvent);
            $eventDispatcher->dispatchScript(ScriptEvents::PRE_ARCHIVE_CMD);
        }
        if (!$config) {
            $config = Factory::createConfig();
        }
        $format = $input->getOption('format') ?? $config->get('archive-format');
        $dir = $input->getOption('dir') ?? $config->get('archive-dir');
        $returnCode = $this->archive($this->getIO(), $config, $input->getArgument('package'), $input->getArgument('version'), $format, $dir, $input->getOption('file'), $input->getOption('ignore-filters'), $composer);
        if (0 === $returnCode && $composer) {
            $composer->getEventDispatcher()
                ->dispatchScript(ScriptEvents::POST_ARCHIVE_CMD);
        }
        return $returnCode;
    }
    
    /**
     * @throws \Exception
     */
    protected function archive(IOInterface $io, Config $config, ?string $packageName, ?string $version, string $format, string $dest, ?string $fileName, bool $ignoreFilters, ?Composer $composer) : int {
        if ($composer) {
            $archiveManager = $composer->getArchiveManager();
        }
        else {
            $factory = new Factory();
            $process = new ProcessExecutor();
            $httpDownloader = Factory::createHttpDownloader($io, $config);
            $downloadManager = $factory->createDownloadManager($io, $config, $httpDownloader, $process);
            $archiveManager = $factory->createArchiveManager($config, $downloadManager, new Loop($httpDownloader, $process));
        }
        if ($packageName) {
            $package = $this->selectPackage($io, $packageName, $version);
            if (!$package) {
                return 1;
            }
        }
        else {
            $package = $this->requireComposer()
                ->getPackage();
        }
        $io->writeError('<info>Creating the archive into "' . $dest . '".</info>');
        $packagePath = $archiveManager->archive($package, $format, $dest, $fileName, $ignoreFilters);
        $fs = new Filesystem();
        $shortPath = $fs->findShortestPath(Platform::getCwd(), $packagePath, true);
        $io->writeError('Created: ', false);
        $io->write(strlen($shortPath) < strlen($packagePath) ? $shortPath : $packagePath);
        return 0;
    }
    
    /**
     * @return (BasePackage&CompletePackageInterface)|false
     */
    protected function selectPackage(IOInterface $io, string $packageName, ?string $version = null) {
        $io->writeError('<info>Searching for the specified package.</info>');
        if ($composer = $this->tryComposer()) {
            $localRepo = $composer->getRepositoryManager()
                ->getLocalRepository();
            $repo = new CompositeRepository(array_merge([
                $localRepo,
            ], $composer->getRepositoryManager()
                ->getRepositories()));
            $minStability = $composer->getPackage()
                ->getMinimumStability();
        }
        else {
            $defaultRepos = RepositoryFactory::defaultReposWithDefaultManager($io);
            $io->writeError('No composer.json found in the current directory, searching packages from ' . implode(', ', array_keys($defaultRepos)));
            $repo = new CompositeRepository($defaultRepos);
            $minStability = 'stable';
        }
        if ($version !== null && Preg::isMatchStrictGroups('{@(stable|RC|beta|alpha|dev)$}i', $version, $match)) {
            $minStability = VersionParser::normalizeStability($match[1]);
            $version = (string) substr($version, 0, -strlen($match[0]));
        }
        $repoSet = new RepositorySet($minStability);
        $repoSet->addRepository($repo);
        $parser = new VersionParser();
        $constraint = $version !== null ? $parser->parseConstraints($version) : null;
        $packages = $repoSet->findPackages(strtolower($packageName), $constraint);
        if (count($packages) > 1) {
            $versionSelector = new VersionSelector($repoSet);
            $package = $versionSelector->findBestCandidate(strtolower($packageName), $version, $minStability);
            if ($package === false) {
                $package = reset($packages);
            }
            $io->writeError('<info>Found multiple matches, selected ' . $package->getPrettyString() . '.</info>');
            $io->writeError('Alternatives were ' . implode(', ', array_map(static function ($p) : string {
                return $p->getPrettyString();
            }, $packages)) . '.');
            $io->writeError('<comment>Please use a more specific constraint to pick a different package.</comment>');
        }
        elseif (count($packages) === 1) {
            $package = reset($packages);
            $io->writeError('<info>Found an exact match ' . $package->getPrettyString() . '.</info>');
        }
        else {
            $io->writeError('<error>Could not find a package matching ' . $packageName . '.</error>');
            return false;
        }
        if (!$package instanceof CompletePackageInterface) {
            throw new \LogicException('Expected a CompletePackageInterface instance but found ' . get_class($package));
        }
        if (!$package instanceof BasePackage) {
            throw new \LogicException('Expected a BasePackage instance but found ' . get_class($package));
        }
        return $package;
    }

}

Members

Title Sort descending Deprecated Modifiers Object type Summary Overriden Title Overrides
ArchiveCommand::archive protected function
ArchiveCommand::configure protected function Configures the current command. Overrides Command::configure
ArchiveCommand::execute protected function Executes the current command. Overrides Command::execute
ArchiveCommand::FORMATS private constant
ArchiveCommand::selectPackage protected function
BaseCommand::$composer private property
BaseCommand::$io private property
BaseCommand::complete public function @inheritdoc Overrides Command::complete 1
BaseCommand::createComposerInstance protected function Calls {
BaseCommand::formatRequirements protected function
BaseCommand::getApplication public function Gets the application instance for this command. Overrides Command::getApplication
BaseCommand::getAuditFormat protected function @internal
BaseCommand::getComposer Deprecated public function
BaseCommand::getIO public function
BaseCommand::getPlatformRequirementFilter protected function
BaseCommand::getPreferredInstallOptions protected function Returns preferSource and preferDist values based on the configuration.
BaseCommand::getTerminalWidth protected function
BaseCommand::initialize protected function @inheritDoc Overrides Command::initialize 1
BaseCommand::isProxyCommand public function Whether or not this command is meant to call another command. 2
BaseCommand::normalizeRequirements protected function
BaseCommand::renderTable protected function
BaseCommand::resetComposer public function Removes the cached composer instance
BaseCommand::setComposer public function
BaseCommand::setIO public function
BaseCommand::tryComposer public function Retrieves the default Composer\Composer instance or null
Command::$aliases private property 1
Command::$application private property
Command::$code private property
Command::$definition private property
Command::$description private property 1
Command::$fullDefinition private property
Command::$help private property
Command::$helperSet private property
Command::$hidden private property
Command::$ignoreValidationErrors private property 2
Command::$name private property
Command::$processTitle private property
Command::$synopsis private property
Command::$usages private property
Command::addArgument public function Adds an argument. 2
Command::addOption public function Adds an option. 2
Command::addUsage public function Add a command usage example, it&#039;ll be prefixed with the command name. 2
Command::FAILURE public constant
Command::getAliases public function Returns the aliases for the command.
Command::getDefaultDescription public static function
Command::getDefaultName public static function
Command::getDefinition public function Gets the InputDefinition attached to this Command. 2
Command::getDescription public function Returns the description for the command.
Command::getHelp public function Returns the help for the command. 2
Command::getHelper public function Gets a helper instance by name. 2
Command::getHelperSet public function Gets the helper set. 1
Command::getName public function Returns the command name.
Command::getNativeDefinition public function Gets the InputDefinition to be used to create representations of this Command. 2
Command::getProcessedHelp public function Returns the processed help for the command replacing the %command.name% and
%command.full_name% patterns with the real values dynamically.
2
Command::getSynopsis public function Returns the synopsis for the command. 2
Command::getUsages public function Returns alternative usages of the command. 2
Command::ignoreValidationErrors public function Ignores validation errors. 2
Command::interact protected function Interacts with the user. 5
Command::INVALID public constant
Command::isEnabled public function Checks whether the command is enabled or not in the current environment. 2
Command::isHidden public function
Command::mergeApplicationDefinition public function Merges the application definition with the command definition. 2
Command::run public function Runs the command. 4
Command::setAliases public function Sets the aliases for the command.
Command::setApplication public function 2
Command::setCode public function Sets the code to execute when running this command. 2
Command::setDefinition public function Sets an array of argument and option instances. 2
Command::setDescription public function Sets the description for the command.
Command::setHelp public function Sets the help for the command. 2
Command::setHelperSet public function 2
Command::setHidden public function
Command::setName public function Sets the name of the command.
Command::setProcessTitle public function Sets the process title of the command. 2
Command::SUCCESS public constant
Command::validateName private function Validates a command name.
Command::__construct public function 15
CompletionTrait::requireComposer abstract public function
CompletionTrait::suggestAvailablePackage private function Suggest package names available on all configured repositories.
CompletionTrait::suggestAvailablePackageInclPlatform private function Suggest package names available on all configured repositories or
platform packages from the ones available on the currently-running PHP
CompletionTrait::suggestInstalledPackage private function Suggest package names from installed.
CompletionTrait::suggestInstalledPackageTypes private function Suggest package names from installed.
CompletionTrait::suggestPlatformPackage private function Suggest platform packages from the ones available on the currently-running PHP
CompletionTrait::suggestPreferInstall private function Suggestion values for &quot;prefer-install&quot; option
CompletionTrait::suggestRootRequirement private function Suggest package names from root requirements.

API Navigation

  • Drupal Core 11.1.x
  • Topics
  • Classes
  • Functions
  • Constants
  • Globals
  • Files
  • Namespaces
  • Deprecated
  • Services
RSS feed
Powered by Drupal