default services conflit ?

This commit is contained in:
armansansd
2022-04-27 11:30:43 +02:00
parent 28190a5749
commit 8bb1064a3b
8132 changed files with 900138 additions and 426 deletions

View File

@@ -0,0 +1,34 @@
name: Self update testing
on: push
jobs:
# Checkout in separate job because docker image is alpine based and checkout action doesn't work.
functional:
runs-on: ubuntu-latest
defaults:
run:
working-directory: self-update-fixture
container:
image: quay.io/pantheon-public/php-ci:v7.4
name: Run functional tests
steps:
- name: Checkout
uses: actions/checkout@v2
with:
path: self-update
- name: Checkout self-update-fixtures
uses: actions/checkout@v2
with:
repository: consolidation/self-update-fixture
path: self-update-fixture
ref: self-update
- name: Run Composer Install
run: composer install
- name: Add path repository
run: composer config repositories.self-update path ../self-update
- name: Require self-update package
run: COMPOSER_MIRROR_PATH_REPOS=1 composer require consolidation/self-update:"*"
- name: Phar Build
run: composer phar:build
- name: Run tests
run: ./.github/workflows/test.sh ../self-update-fixture
working-directory: self-update

View File

@@ -0,0 +1,52 @@
#!/bin/bash
if [ "$#" -ne 1 ]; then
echo "You should use fixtures path as parameter"
exit 1
fi
set -ex
cd $1
echo "Get wonder current version"
./wonder info | grep "1.2"
echo "Backup current binary"
cp ./wonder ./wonder-backup
echo "Self update --stable"
cp -r ./wonder-backup wonder && ./wonder self:update --stable
./wonder info | grep "2.0"
echo "Self update"
cp -r ./wonder-backup wonder && ./wonder self:update
./wonder info | grep "2.0"
echo "Self update --preview"
cp -r ./wonder-backup wonder && ./wonder self:update --preview
./wonder info | grep "2.1-beta1"
echo "Self update --stable --compatible"
cp -r ./wonder-backup wonder && ./wonder self:update --stable --compatible
./wonder info | grep "1.3"
echo "Self update --compatible"
cp -r ./wonder-backup wonder && ./wonder self:update --compatible
./wonder info | grep "1.3"
echo "Self update version_constraint arg test #1"
cp -r ./wonder-backup wonder && ./wonder self:update ^1.2
./wonder info | grep "1.3"
echo "Self update version_constraint arg test #2"
cp -r ./wonder-backup wonder && ./wonder self:update 2.0
./wonder info | grep "2.0"
echo "Self update version_constraint arg test #3"
cp -r ./wonder-backup wonder && ./wonder self:update ^1 --preview
./wonder info | grep "1.4-alpha1"
echo "Self update version_constraint arg test #4"
cp -r ./wonder-backup wonder && ./wonder self:update ^1 --stable
./wonder info | grep "1.3"

View File

@@ -0,0 +1 @@
vendor

View File

@@ -0,0 +1,20 @@
The MIT License (MIT)
Copyright (c) 2014 Codegyre Developers Team, Consolidation Team
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,17 @@
# SelfUpdate
Symfony Console command to update a phar in place.
## Usage
To use the self:update command, instantiate it with the name of the application,
its current version, and the full name of the GitHub project.
```
$cmd = new SelfUpdateCommand('MyAppName', '1.0.0', 'org/my-app');
$app->add($cmd);
```
## Similar Projects
- https://github.com/DavaHome/self-update
- https://github.com/padraic/phar-updater

View File

@@ -0,0 +1,41 @@
{
"name": "consolidation/self-update",
"description": "Provides a self:update command for Symfony Console applications.",
"license": "MIT",
"authors": [
{
"name": "Alexander Menk",
"email": "menk@mestrona.net"
},
{
"name": "Greg Anderson",
"email": "greg.1.anderson@greenknowe.org"
}
],
"autoload":{
"psr-4":{
"SelfUpdate\\":"src"
}
},
"require": {
"php": ">=5.5.0",
"composer/semver": "^3.2",
"symfony/console": "^2.8 || ^3 || ^4 || ^5 || ^6",
"symfony/filesystem": "^2.5 || ^3 || ^4 || ^5 || ^6"
},
"bin": [
"scripts/release"
],
"scripts": {
"release": "./scripts/release VERSION"
},
"config": {
"optimize-autoloader": true,
"sort-packages": true
},
"extra": {
"branch-alias": {
"dev-main": "2.x-dev"
}
}
}

View File

@@ -0,0 +1,178 @@
#!/usr/bin/env php
<?php
/**
* Usage:
*
* ./vendor/bin/release VERSION
*/
$semverRegEx = '(?<version>[0-9]+\.[0-9]+\.[0-9]+)(?<prerelease>-[0-9a-zA-Z.]+)?(?<build>\+[0-9a-zA-Z.]*)?';
$optind = null;
$options = getopt ("dvy", [
'pattern:',
'simulate',
'yes',
], $optind) + [
'pattern' => "^SEMVER$",
];
$simulate = array_key_exists('simulate', $options);
$yes = array_key_exists('yes', $options) || array_key_exists('y', $options);
$pos_args = array_slice($argv, $optind);
$path = array_shift($pos_args);
if (empty($path)) {
print "Path to version file must be specified as a commandline argument\n";
exit(1);
}
if (!file_exists($path)) {
print "Version file not found at $path\n";
exit(1);
}
// The --pattern option is expected to contain the string SEMVER
$regex = str_replace('SEMVER', "$semverRegEx", $options['pattern']);
if ($regex == $options['pattern']) {
print "Pattern '$regex' must contain the string 'SEMVER'.\n";
exit(1);
}
// Read the contents of the version file and find the version string
$contents = file_get_contents($path);
if (!preg_match("#$regex#m", $contents, $matches)) {
print "A semver version not found in $path\n";
exit(1);
}
$matches += ['prerelease' => '', 'build' => ''];
// Calculate the stable and next version strings
$original_version_match = $matches[0];
$original_version = $matches['version'] . $matches['prerelease'] . $matches['build'];
$stable_version = $matches['version'] . (has_prerelease($matches) ? $matches['prerelease'] : '');
$next_version = next_version($matches);
$stable_version_replacement = str_replace($original_version, $stable_version, $original_version_match);
$next_version_replacement = str_replace($original_version, $next_version, $original_version_match);
$stable_version_contents = str_replace($original_version_match, $stable_version_replacement, $contents);
$next_version_contents = str_replace($original_version_match, $next_version_replacement, $contents);
$composerContents = file_get_contents('composer.json');
$composerData = json_decode($composerContents, true);
$project = $composerData['name'];
$msg = "Release $project version $stable_version";
$dashes = str_pad('', strlen($msg) + 8, '-', STR_PAD_LEFT);
print "\n$dashes\n\n";
print " $msg\n";
print "\n$dashes\n\n";
// Write the stable version into the version file, tag and push the release
if (!$simulate) {
file_put_contents($path, $stable_version_contents);
}
else {
print "Replace stable version in $path:\n> $stable_version_replacement\n";
}
run('git add {path}', ['{path}' => $path], $simulate);
run('git commit -m "Version {version}"', ['{version}' => $stable_version], $simulate);
run('git tag {version}', ['{version}' => $stable_version], $simulate);
run('git push origin {version}', ['{version}' => $stable_version], $simulate);
// Put the next version into the version file and push the result back to master
if (!$simulate) {
file_put_contents($path, $next_version_contents);
}
else {
print "Replace next version in $path:\n> $next_version_replacement\n";
}
run('git add {path}', ['{path}' => $path], $simulate);
run('git commit -m "[ci skip] Back to {version}"', ['{version}' => $next_version], $simulate);
run('git push origin master', [], $simulate);
exit(0);
/**
* inflect replaces the placeholders in the command with the provided parameter values
* @param string $cmd
* @param array $parameters
* @return string
*/
function inflect($cmd, $parameters = [])
{
if (!empty($parameters)) {
return str_replace(array_keys($parameters), array_values($parameters), $cmd);
}
return $cmd;
}
/**
* Run the specified command. Abort most rudely if an error is encountered
*/
function run($cmd, $parameters = [], $simulate = false)
{
$cmd = inflect($cmd, $parameters);
if ($simulate) {
print "$cmd\n";
return;
}
passthru($cmd, $status);
if ($status) {
exit($status);
}
}
/**
* Determine the next version after the current release
*/
function next_version($matches)
{
$version = $matches['version'];
$next_version = next_version_prerelease($matches);
if ($next_version !== false) {
return $next_version;
}
return next_version_stable($matches);
}
/**
* Determine the next version given that the current version is stable
*/
function next_version_stable($matches)
{
$version_parts = explode('.', $matches['version']);
$last_version = array_pop($version_parts);
$last_version++;
$version_parts[] = $last_version;
return implode('.', $version_parts) . (empty($matches['prerelease']) ? '-dev' : $matches['prerelease']);
}
function has_prerelease($matches)
{
if (empty($matches['prerelease'])) {
return false;
}
return is_numeric(substr($matches['prerelease'], -1));
}
/**
* Determine the next version given that the current version has a pre-release
* (e.g. '-alpha5').
*/
function next_version_prerelease($version_parts)
{
if (!preg_match('#(.*?)([0-9]+)$#', $version_parts['prerelease'], $matches)) {
return false;
}
$next = $matches[2] + 1;
return $version_parts['version'] . $matches[1] . $next . '+dev';
}

View File

@@ -0,0 +1,277 @@
<?php
namespace SelfUpdate;
use Composer\Semver\VersionParser;
use Composer\Semver\Semver;
use Composer\Semver\Comparator;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Filesystem\Filesystem as sfFilesystem;
/**
* Update the *.phar from the latest github release.
*
* @author Alexander Menk <alex.menk@gmail.com>
*/
class SelfUpdateCommand extends Command
{
const SELF_UPDATE_COMMAND_NAME = 'self:update';
protected $gitHubRepository;
protected $currentVersion;
protected $applicationName;
protected $ignorePharRunningCheck;
public function __construct($applicationName = null, $currentVersion = null, $gitHubRepository = null)
{
$this->applicationName = $applicationName;
$this->currentVersion = $currentVersion;
$this->gitHubRepository = $gitHubRepository;
$this->ignorePharRunningCheck = false;
parent::__construct(self::SELF_UPDATE_COMMAND_NAME);
}
/**
* Set ignorePharRunningCheck to true.
*/
public function ignorePharRunningCheck($ignore = true)
{
$this->ignorePharRunningCheck = $ignore;
}
/**
* {@inheritdoc}
*/
protected function configure()
{
$app = $this->applicationName;
// Follow Composer's pattern of command and channel names.
$this
->setAliases(array('update', 'self-update'))
->setDescription("Updates $app to the latest version.")
->addArgument('version_constraint', InputArgument::OPTIONAL, 'Apply version constraint')
->addOption('stable', NULL, InputOption::VALUE_NONE, 'Use stable releases (default)')
->addOption('preview', NULL, InputOption::VALUE_NONE, 'Preview unstable (e.g., alpha, beta, etc.) releases')
->addOption('compatible', NULL, InputOption::VALUE_NONE, 'Stay on current major version')
->setHelp(
<<<EOT
The <info>self-update</info> command checks github for newer
versions of $app and if found, installs the latest.
EOT
);
}
/**
* Get all releases from GitHub.
*
* @throws \Exception
*
* @return array
*/
protected function getReleasesFromGithub()
{
$version_parser = new VersionParser();
$opts = [
'http' => [
'method' => 'GET',
'header' => [
'User-Agent: ' . $this->applicationName . ' (' . $this->gitHubRepository . ')' . ' Self-Update (PHP)',
],
],
];
$context = stream_context_create($opts);
$releases = file_get_contents('https://api.github.com/repos/' . $this->gitHubRepository . '/releases', false, $context);
$releases = json_decode($releases);
if (!isset($releases[0])) {
throw new \Exception('API error - no release found at GitHub repository ' . $this->gitHubRepository);
}
$parsed_releases = [];
foreach ($releases as $release) {
try {
$normalized = $version_parser->normalize($release->tag_name);
} catch (\UnexpectedValueException $e) {
// If this version does not look quite right, let's ignore it.
continue;
}
$parsed_releases[$normalized] = [
'tag_name' => $normalized,
'assets' => $release->assets,
];
}
$sorted_versions = Semver::rsort(array_keys($parsed_releases));
$sorted_releases = [];
foreach ($sorted_versions as $version) {
$sorted_releases[$version] = $parsed_releases[$version];
}
return $sorted_releases;
}
/**
* Get the latest release version and download URL according to given constraints.
*
* @param array
*
* @throws \Exception
*
* @return string[]|null
* "version" and "download_url" elements if the latest release is available, otherwise - NULL.
*/
public function getLatestReleaseFromGithub(array $options)
{
$options = array_merge([
'preview' => false,
'compatible' => false,
'version_constraint' => null,
], $options);
foreach ($this->getReleasesFromGithub() as $release) {
// We do not care about this release if it does not contain assets.
if (!isset($release['assets'][0]) || !is_object($release['assets'][0])) {
continue;
}
$releaseVersion = $release['tag_name'];
if ($options['compatible'] && !$this->satisfiesMajorVersionConstraint($releaseVersion)) {
// If it does not satisfies, look for the next one.
continue;
}
if (!$options['preview'] && VersionParser::parseStability($releaseVersion) !== 'stable') {
// If preview not requested and current version is not stable, look for the next one.
continue;
}
if (null !== $options['version_constraint'] && !Semver::satisfies($releaseVersion, $options['version_constraint'])) {
// Release version does not match version constraint option.
continue;
}
return [
'version' => $releaseVersion,
'download_url' => $release['assets'][0]->browser_download_url,
];
}
return null;
}
/**
* {@inheritdoc}
*
* @throws \Exception
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
if (!$this->ignorePharRunningCheck && empty(\Phar::running())) {
throw new \Exception(self::SELF_UPDATE_COMMAND_NAME . ' only works when running the phar version of ' . $this->applicationName . '.');
}
$localFilename = realpath($_SERVER['argv'][0]) ?: $_SERVER['argv'][0];
$programName = basename($localFilename);
$tempFilename = dirname($localFilename) . '/' . basename($localFilename, '.phar') . '-temp.phar';
// check for permissions in local filesystem before start connection process
if (! is_writable($tempDirectory = dirname($tempFilename))) {
throw new \Exception(
$programName . ' update failed: the "' . $tempDirectory .
'" directory used to download the temp file could not be written'
);
}
if (!is_writable($localFilename)) {
throw new \Exception(
$programName . ' update failed: the "' . $localFilename . '" file could not be written (execute with sudo)'
);
}
$isPreviewOptionSet = $input->getOption('preview');
$isStable = $input->getOption('stable') || !$isPreviewOptionSet;
if ($isPreviewOptionSet && $isStable) {
throw new \Exception(self::SELF_UPDATE_COMMAND_NAME . ' support either stable or preview, not both.');
}
$isCompatibleOptionSet = $input->getOption('compatible');
$versionConstraintArg = $input->getArgument('version_constraint');
$latestRelease = $this->getLatestReleaseFromGithub([
'preview' => $isPreviewOptionSet,
'compatible' => $isCompatibleOptionSet,
'version_constraint' => $versionConstraintArg,
]);
if (null === $latestRelease || Comparator::greaterThanOrEqualTo($this->currentVersion, $latestRelease['version'])) {
$output->writeln('No update available');
return 0;
}
$fs = new sfFilesystem();
$output->writeln('Downloading ' . $this->applicationName . ' (' . $this->gitHubRepository . ') ' . $latestRelease['version']);
$fs->copy($latestRelease['download_url'], $tempFilename);
$output->writeln('Download finished');
try {
\error_reporting(E_ALL); // supress notices
@chmod($tempFilename, 0777 & ~umask());
// test the phar validity
$phar = new \Phar($tempFilename);
// free the variable to unlock the file
unset($phar);
@rename($tempFilename, $localFilename);
$output->writeln('<info>Successfully updated ' . $programName . '</info>');
$this->_exit();
} catch (\Exception $e) {
@unlink($tempFilename);
if (! $e instanceof \UnexpectedValueException && ! $e instanceof \PharException) {
throw $e;
}
$output->writeln('<error>The download is corrupted (' . $e->getMessage() . ').</error>');
$output->writeln('<error>Please re-run the self-update command to try again.</error>');
return 1;
}
}
/**
* Returns TRUE if the release version satisfies current major version constraint.
*
* @return bool
*/
protected function satisfiesMajorVersionConstraint(string $releaseVersion)
{
if (preg_match('/^v?(\d+)/', $this->currentVersion, $matches)) {
return Semver::satisfies($releaseVersion , '^' . $matches[1]);
}
return false;
}
/**
* Stop execution
*
* This is a workaround to prevent warning of dispatcher after replacing
* the phar file.
*
* @return void
*/
protected function _exit()
{
exit;
}
}