Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add reusable workflows for cs and static analysis #148

Merged
merged 23 commits into from
Aug 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions .github/workflows/code-standards.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
name: PHP Code Standards

on:
workflow_call:
inputs:
version:
type: string
default: "^3.0"
config:
type: string
default: ""
path:
type: string
default: "."
rules:
type: string
default: |
{
"@PSR2": true,
"array_syntax": {"syntax":"short"},
"concat_space": {"spacing":"one"},
"no_unused_imports": true,
"ordered_imports": true,
"new_with_parentheses": true,
"whitespace_after_comma_in_array": true,
"method_argument_space": {
"keep_multiple_spaces_after_comma": true,
"on_multiline": "ignore"
},
"return_type_declaration": {"space_before": "none"},
"single_quote": true
}

permissions:
contents: read

jobs:
php_code_standards:
runs-on: ubuntu-latest
name: PHP Code Standards
steps:
- uses: actions/checkout@v4
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: '8.2'
- name: Run PHP CS Fixer
run: |
composer global require friendsofphp/php-cs-fixer:${{ inputs.version }} -q
CONFIG="${{ inputs.config }}"
RULES=$(echo $'${{ inputs.rules }}'|tr -d '\n\t\r ')

set -x

~/.composer/vendor/bin/php-cs-fixer fix \
${{ inputs.path }} \
$(if [ ! -z "$CONFIG" ]; then echo "--config=$CONFIG"; elif [ ! -z "$RULES" ]; then echo --rules=$RULES; fi) \
--dry-run --diff
33 changes: 33 additions & 0 deletions .github/workflows/static-analysis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
name: PHP Static Analysis
on:
workflow_call:
inputs:
version:
type: string
default: "^1.8"
paths:
type: string
default: "src"
autoload-file:
type: string
default: "vendor/autoload.php"

permissions:
contents: read

jobs:
static_analysis:
runs-on: ubuntu-latest
name: PHPStan Static Analysis
steps:
- uses: actions/checkout@v4
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: '8.2'
- name: Run Script
run: |
composer install -q
composer global require phpstan/phpstan:${{ inputs.version }} -q
~/.composer/vendor/bin/phpstan analyse ${{ inputs.paths }} \
--autoload-file=${{ inputs.autoload-file }}
25 changes: 8 additions & 17 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,20 +31,11 @@ jobs:
- name: Run Script
run: vendor/bin/phpunit

style:
runs-on: ubuntu-latest
name: PHP Style Check
steps:
- uses: actions/checkout@v4
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: "8.1"
- name: Install Dependencies
uses: nick-invision/retry@v3
with:
timeout_minutes: 10
max_attempts: 3
command: composer install
- name: Run Script
run: vendor/bin/php-cs-fixer fix .
code-standards:
uses: ./.github/workflows/code-standards.yml
with:
path: src

static-analysis:
uses: ./.github/workflows/static-analysis.yml

16 changes: 0 additions & 16 deletions .php-cs-fixer.dist.php

This file was deleted.

2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
"paragonie/random_compat": ">=2",
"phpunit/phpunit": "^9",
"phpspec/prophecy-phpunit": "^2.0",
"friendsofphp/php-cs-fixer": "^3.21",
"friendsofphp/php-cs-fixer": "^3.62",
"google/cloud-dlp": "^1.10",
"google/cloud-storage": "^1.33",
"google/cloud-secret-manager": "^1.12"
Expand Down
33 changes: 11 additions & 22 deletions src/Fixers/ClientUpgradeFixer/ClientUpgradeFixer.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,21 @@
namespace Google\Cloud\Fixers\ClientUpgradeFixer;

use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\FixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\Fixer\Import\OrderedImportsFixer;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer;
use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use ReflectionClass;
use ReflectionMethod;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;

class ClientUpgradeFixer extends AbstractFixer implements ConfigurableFixerInterface
{
use ConfigurableFixerTrait;

/**
* Check if the fixer is a candidate for given Tokens collection.
*
Expand All @@ -34,19 +32,10 @@ public function isCandidate(Tokens $tokens): bool
return true;
}

/**
* @param array<string, mixed> $configuration
*/
public function configure(array $configuration): void
{
// no configuration assumes true
$this->configuration = $configuration;
}

/**
* Defines the available configuration options of the fixer.
*/
public function getConfigurationDefinition(): FixerConfigurationResolverInterface
protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('clientVars', 'A map of client variables to their new class names'))
Expand Down Expand Up @@ -199,10 +188,10 @@ protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
$importedClasses = array_map(fn ($useDeclaration) => $useDeclaration->getFullName(), $useDeclarations);
$classesToImport = array_filter(
$classesToImport,
fn($requestClass) => !isset($importedClasses[$requestClass->getName()])
fn ($requestClass) => !isset($importedClasses[$requestClass->getName()])
);
$requestClassImportTokens = array_map(
fn($requestClass) => $requestClass->getImportTokens(),
fn ($requestClass) => $requestClass->getImportTokens(),
array_values($classesToImport)
);
$tokens->insertAt($importStart, array_merge(...$requestClassImportTokens));
Expand Down
1 change: 0 additions & 1 deletion src/Fixers/ClientUpgradeFixer/RequestClass.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
namespace Google\Cloud\Fixers\ClientUpgradeFixer;

use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use ReflectionClass;

class RequestClass
Expand Down
2 changes: 0 additions & 2 deletions src/Fixers/ClientUpgradeFixer/RequestVariableCounter.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@

namespace Google\Cloud\Fixers\ClientUpgradeFixer;

use PhpCsFixer\Tokenizer\Tokens;

class RequestVariableCounter
{
private array $varCounts = [];
Expand Down
1 change: 0 additions & 1 deletion src/Fixers/ClientUpgradeFixer/RpcMethod.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use ReflectionMethod;
use ReflectionParameter;

class RpcMethod
{
Expand Down
2 changes: 1 addition & 1 deletion src/TestUtils/CloudFunctionDeploymentTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ public function setUpClient()

public function getBaseUri()
{
return self::$fn->getBaseUrl(getenv("GOOGLE_SKIP_DEPLOYMENT") === 'true');
return self::$fn->getBaseUrl(getenv('GOOGLE_SKIP_DEPLOYMENT') === 'true');
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/TestUtils/CloudSqlProxyTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@

namespace Google\Cloud\TestUtils;

use Symfony\Component\Process\Process;
use Exception;
use Symfony\Component\Process\Process;

/**
* Trait CloudSqlTestTrait
Expand Down
2 changes: 1 addition & 1 deletion src/TestUtils/FileUtil.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ class FileUtil
{
public static function randomName($length)
{
$array = array();
$array = [];
for ($i = 0; $i < $length; ++$i) {
array_push($array, chr(random_int(ord('a'), ord('z'))));
}
Expand Down
1 change: 1 addition & 0 deletions src/TestUtils/GcloudWrapper/AppEngine.php
Original file line number Diff line number Diff line change
Expand Up @@ -237,4 +237,5 @@ public function getBaseUrl($service = 'default')
}
}

// @phpstan-ignore-next-line
class_alias(AppEngine::class, \Google\Cloud\TestUtils\GcloudWrapper::class);
6 changes: 3 additions & 3 deletions src/TestUtils/GcloudWrapper/CloudFunction.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@

namespace Google\Cloud\TestUtils\GcloudWrapper;

use Symfony\Component\Process\Process;
use Symfony\Component\Process\PhpExecutableFinder;
use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\PhpExecutableFinder;
use Symfony\Component\Process\Process;

/**
* Class CloudFunction.
Expand Down Expand Up @@ -108,7 +108,7 @@ public static function fromArray(array $arr)
$args[] = $arr[$key] ?? '';
}

return new static(...$args);
return new self(...$args);
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/TestUtils/GcloudWrapper/CloudRun.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ public function __construct($project, array $options = [])
*
* @return bool true if deployment suceeds, false upon failure
*/
public function build($image, array $options = [], string $source = ".")
public function build($image, array $options = [], string $source = '.')
{
// Set default optioins
$options = array_merge([
Expand Down
4 changes: 2 additions & 2 deletions src/TestUtils/GcloudWrapper/GcloudWrapperTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@

namespace Google\Cloud\TestUtils\GcloudWrapper;

use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\Process;

/**
* Trait GcloudWrapperTrait.
Expand Down Expand Up @@ -89,7 +89,7 @@ protected function execWithRetry($cmd, $retries = 3, &$output = null)
*/
protected function runWithRetry(Process $cmd, $retries = 3)
{
$this->errorLog('Running: ' . str_replace("'", "", $cmd->getCommandLine()));
$this->errorLog('Running: ' . str_replace("'", '', $cmd->getCommandLine()));
for ($i = 0; $i <= $retries; ++$i) {
// TODO: Use ExponentialBackoffTrait for more sophisticated handling.
// Simple geometric backoff, .25 seconds * iteration.
Expand Down
5 changes: 3 additions & 2 deletions src/Utils/ContainerExec.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,8 @@ public function __construct(
throw new \InvalidArgumentException("$workdir is not a directory");
}
$this->gcloud = ($gcloud == null) ? new Gcloud() : $gcloud;
if (class_exists(\Twig_Loader_Filesystem::class)) {
if (class_exists(\Twig_Loader_Filesystem::class)
&& class_exists(\Twig_Environment::class)) {
$loader = new \Twig_Loader_Filesystem(__DIR__ . '/templates');
$this->twig = new \Twig_Environment($loader);
} else {
Expand Down Expand Up @@ -109,7 +110,7 @@ public function run()
implode(PHP_EOL, $cmdOutput)
);
if ($result !== 0) {
throw new \RuntimeException("Failed to run the command");
throw new \RuntimeException('Failed to run the command');
}
$ret = '';
if ($this->cloudSqlInstances) {
Expand Down
14 changes: 7 additions & 7 deletions src/Utils/Flex/FlexExecCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
use Symfony\Component\Filesystem\Filesystem;

/**
* CLI command for running a command with an image deployed to App Engine
Expand Down Expand Up @@ -151,7 +151,7 @@ protected function execute(InputInterface $input, OutputInterface $output)
}
$output->writeln("Using workdir: <info>$workdir</info>");
if ($preserveWorkdir) {
$output->writeln("<info>Preserving the workdir</info>");
$output->writeln('<info>Preserving the workdir</info>');
} else {
register_shutdown_function(function () use ($workdir, $fs) {
$fs->remove($workdir);
Expand Down Expand Up @@ -213,7 +213,7 @@ protected function resolveImage(
'describe',
$version,
"--service=$service",
"--format=json"
'--format=json'
]
);
if ($ret !== 0) {
Expand Down Expand Up @@ -244,7 +244,7 @@ protected function resolveImage(
* @param string $service
* @param InputInterface $input
* @param OutputInterface $output
* @return string The version for the latest deployment for the given
* @return ?string The version for the latest deployment for the given
* service.
*/
protected function detectLatestDeployedVersion(
Expand All @@ -258,9 +258,9 @@ protected function detectLatestDeployedVersion(
'versions',
'list',
"--service=$service",
"--format=get(version.id)",
"--sort-by=~version.createTime",
"--limit=1"
'--format=get(version.id)',
'--sort-by=~version.createTime',
'--limit=1'
]
);
if (!empty($cmdOutput)) {
Expand Down
2 changes: 1 addition & 1 deletion src/Utils/Gcloud.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ class Gcloud
public function __construct()
{
$auths = exec(
escapeshellcmd("gcloud auth list --format=value(account)"),
escapeshellcmd('gcloud auth list --format=value(account)'),
$output,
$ret
);
Expand Down
Loading