Browse Source

Replaced the Gulp build system by PowerShell scripts

master
Cédric Belin 6 months ago
parent
commit
a572c1812e
21 changed files with 108 additions and 95 deletions
  1. +0
    -5
      .gulp.json
  2. +2
    -5
      doc/installation.md
  3. +4
    -3
      lib/fast_transformer.js
  4. +1
    -0
      lib/php/index.php
  5. +1
    -0
      lib/php/server.php
  6. +0
    -1
      lib/server.php
  7. +2
    -2
      lib/transformer.d.ts
  8. +3
    -4
      package.json
  9. +1
    -1
      src/php/index.php
  10. +6
    -0
      tool/build.ps1
  11. +11
    -0
      tool/clean.ps1
  12. +4
    -0
      tool/coverage.ps1
  13. +7
    -0
      tool/doc.ps1
  14. +4
    -0
      tool/fix.ps1
  15. +5
    -74
      tool/gulpfile.cjs
  16. +4
    -0
      tool/lint.ps1
  17. +6
    -0
      tool/publish.ps1
  18. +4
    -0
      tool/serve.ps1
  19. +6
    -0
      tool/test.ps1
  20. +10
    -0
      tool/upgrade.ps1
  21. +27
    -0
      tool/watch.ps1

+ 0
- 5
.gulp.json View File

@@ -1,5 +0,0 @@
{
"flags": {
"gulpfile": "tool/gulpfile.cjs"
}
}

+ 2
- 5
doc/installation.md View File

@@ -3,15 +3,12 @@
## Requirements
Before installing **Gulp-PHP-Minify**, you need to make sure you have [Node.js](https://nodejs.org) and [npm](https://www.npmjs.com), the Node.js package manager, up and running.
You also need the [Command Line Utility for Gulp](https://www.npmjs.com/package/gulp-cli).

!!! warning
Gulp-PHP-Minify requires Node.js >= **14.1.0** and Gulp >= **4.0.0**.
You can verify if you're already good to go with the following commands:

```shell
node --version
# v14.1.0
# v14.2.0

npm --version
# 6.14.4
@@ -35,7 +32,7 @@ npm install @cedx/gulp-php-minify
```

### 2. Import it
Now in your [JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript) or [TypeScript](https://www.typescriptlang.org) code, you can use:
Now in your [JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript) code, you can use:

```js
import {phpMinify} from '@cedx/gulp-php-minify';


+ 4
- 3
lib/fast_transformer.js View File

@@ -15,7 +15,7 @@ var _executable, _port, _process;
import { spawn } from 'child_process';
import { createServer } from 'net';
import fetch from 'node-fetch';
import { dirname, normalize, resolve } from 'path';
import { dirname, normalize, join, resolve } from 'path';
import { fileURLToPath } from 'url';
/** Removes comments and whitespace from a PHP script, by calling a Web service. */
export class FastTransformer {
@@ -56,7 +56,8 @@ export class FastTransformer {
return __classPrivateFieldGet(this, _port);
__classPrivateFieldSet(this, _port, await this._getPort());
return new Promise((fulfill, reject) => {
const args = ['-S', `${FastTransformer.address}:${__classPrivateFieldGet(this, _port)}`, '-t', dirname(fileURLToPath(import.meta.url))];
const libDir = dirname(fileURLToPath(import.meta.url));
const args = ['-S', `${FastTransformer.address}:${__classPrivateFieldGet(this, _port)}`, '-t', join(libDir, 'php')];
__classPrivateFieldSet(this, _process, spawn(normalize(__classPrivateFieldGet(this, _executable)), args));
__classPrivateFieldGet(this, _process).on('error', err => reject(err));
setTimeout(() => fulfill(__classPrivateFieldGet(this, _port)), 1000);
@@ -70,7 +71,7 @@ export class FastTransformer {
async transform(script) {
const file = encodeURIComponent(resolve(script));
const port = await this.listen();
const res = await fetch(`http://${FastTransformer.address}:${port}/server.php?file=${file}`);
const res = await fetch(`http://${FastTransformer.address}:${port}/?file=${file}`);
if (!res.ok)
throw new Error('An error occurred while transforming the script.');
return res.text();


+ 1
- 0
lib/php/index.php View File

@@ -0,0 +1 @@
<?php declare(strict_types=1); use Gulp\PhpMinify\{Server}; require_once __DIR__.'/server.php'; (new Server)->run($_GET);

+ 1
- 0
lib/php/server.php View File

@@ -0,0 +1 @@
<?php declare(strict_types=1); namespace Gulp\PhpMinify; class Server { function run(array $args = []): void { try { $this->sendResponse($this->processRequest($args)); } catch (\Throwable $e) { $code = $e->getCode(); $this->sendResponse($e->getMessage(), $code >= 400 && $code < 600 ? $code : 500); } } function sendResponse(string $body, int $status = 200): void { assert($status >= 100 && $status < 600); http_response_code($status); if (!headers_sent()) { header('Content-Length: '.strlen($body)); header('Content-Type: text/plain; charset='.mb_internal_encoding()); } echo $body; } private function processRequest(array $args): string { if (!isset($args['file']) || !mb_strlen($args['file'])) throw new \LogicException('Bad Request', 400); $file = new \SplFileInfo($args['file']); if (!$file->isReadable()) throw new \RuntimeException('Not Found', 404); $output = php_strip_whitespace($file->getPathname()); if (!mb_strlen($output)) throw new \RuntimeException('Internal Server Error', 500); return $output; } }

+ 0
- 1
lib/server.php View File

@@ -1 +0,0 @@
<?php declare(strict_types=1); namespace Gulp\PhpMinify; class Server { function handleError(int $severity, string $message, string $file = __FILE__, int $line = __LINE__): bool { assert(mb_strlen($file) > 0); assert($line > 0); if (error_reporting() & $severity) throw new \ErrorException($message, 0, $severity, $file, $line); return false; } function run(array $args = []): void { set_error_handler([$this, 'handleError']); try { $this->sendResponse($this->processRequest($args)); } catch (\Throwable $e) { $this->sendResponse($e->getMessage(), $e->getCode()); } } function sendResponse(string $body, int $status = 200): void { assert($status >= 100 && $status < 600); http_response_code($status); header('Content-Length: '.strlen($body)); header('Content-Type: text/plain; charset='.mb_internal_encoding()); echo $body; } private function processRequest(array $args): string { if (!isset($args['file']) || !mb_strlen($args['file'])) throw new \LogicException('Bad Request', 400); $file = new \SplFileInfo($args['file']); if (!$file->isReadable()) throw new \RuntimeException('Not Found', 404); $output = php_strip_whitespace($file->getPathname()); if (!mb_strlen($output)) throw new \RuntimeException('Internal Server Error', 500); return $output; } } (new Server)->run($_GET);

+ 2
- 2
lib/transformer.d.ts View File

@@ -4,11 +4,11 @@ export interface Transformer {
* Closes this transformer and releases any resources associated with it.
* @return Completes when the transformer is finally disposed.
*/
close(): Promise<void>;
close: () => Promise<void>;
/**
* Processes a PHP script.
* @param script The path to the PHP script.
* @return The transformed script.
*/
transform(script: string): Promise<string>;
transform: (script: string) => Promise<string>;
}

+ 3
- 4
package.json View File

@@ -60,9 +60,8 @@
"url": "https://git.belin.io/cedx/gulp-php-minify.git"
},
"scripts": {
"coverage": "gulp coverage",
"prepack": "gulp",
"start": "gulp watch",
"test": "gulp test"
"coverage": "coveralls var/lcov.info",
"prepack": "pwsh tool/build.ps1",
"test": "c8 --all --include=lib/**/*.js --report-dir=var --reporter=lcovonly node_modules/.bin/mocha --recursive"
}
}

+ 1
- 1
src/php/index.php View File

@@ -2,5 +2,5 @@
use Gulp\PhpMinify\{Server};

// Start the application.
require_once __DIR__.'/Server.php';
require_once __DIR__.'/server.php';
(new Server)->run($_GET);

+ 6
- 0
tool/build.ps1 View File

@@ -0,0 +1,6 @@
#!/usr/bin/env pwsh
Set-StrictMode -Version Latest
Set-Location (Split-Path $PSScriptRoot)

node_modules/.bin/tsc.ps1 --project src/tsconfig.json
node_modules/.bin/gulp.ps1 --gulpfile=tool/gulpfile.cjs

+ 11
- 0
tool/clean.ps1 View File

@@ -0,0 +1,11 @@
#!/usr/bin/env pwsh
Set-StrictMode -Version Latest
Set-Location (Split-Path $PSScriptRoot)

foreach ($item in @('build', 'doc/api', 'lib', 'www')) {
if (Test-Path $item) { Remove-Item $item -Recurse }
}

foreach ($item in Get-ChildItem var -Exclude .gitkeep) {
Remove-Item $item -Recurse
}

+ 4
- 0
tool/coverage.ps1 View File

@@ -0,0 +1,4 @@
#!/usr/bin/env pwsh
Set-StrictMode -Version Latest
Set-Location (Split-Path $PSScriptRoot)
node_modules/.bin/coveralls.ps1 var/lcov.info

+ 7
- 0
tool/doc.ps1 View File

@@ -0,0 +1,7 @@
#!/usr/bin/env pwsh
Set-StrictMode -Version Latest
Set-Location (Split-Path $PSScriptRoot)

node_modules/.bin/typedoc.ps1 --options etc/typedoc.json
Copy-Item doc/img/favicon.ico doc/api
mkdocs build --config-file=etc/mkdocs.yaml

+ 4
- 0
tool/fix.ps1 View File

@@ -0,0 +1,4 @@
#!/usr/bin/env pwsh
Set-StrictMode -Version Latest
Set-Location (Split-Path $PSScriptRoot)
node_modules/.bin/eslint.ps1 --config=etc/eslint.yaml --fix src/**/*.ts

+ 5
- 74
tool/gulpfile.cjs View File

@@ -1,77 +1,8 @@
const {spawn} = require('child_process');
const del = require('del');
const {dest, series, src, task, watch} = require('gulp');
const {delimiter, normalize, resolve} = require('path');

// Initialize the build system.
const _path = process.env.PATH ?? '';
const _vendor = resolve('node_modules/.bin');
if (!_path.includes(_vendor)) process.env.PATH = `${_vendor}${delimiter}${_path}`;
'use strict';
const {dest, series, src, task} = require('gulp');

/** Builds the project. */
let phpMinify;
task('build:import', () => import('../lib/index.js').then(mod => phpMinify = mod.phpMinify));
task('build:js', () => _exec('tsc', ['--project', 'src/tsconfig.json']));
task('build:php', () => src('src/*.php').pipe(phpMinify()).pipe(dest('lib')));
task('build', series('build:js', 'build:import', 'build:php'));

/** Deletes all generated files and reset any saved state. */
task('clean', () => del(['doc/api', 'lib', 'var/**/*', 'web']));

/** Uploads the results of the code coverage. */
task('coverage', () => _exec('coveralls', ['var/lcov.info']));

/** Builds the documentation. */
task('doc', async () => {
await _exec('typedoc', ['--options', 'etc/typedoc.json']);
return _exec('mkdocs', ['build', '--config-file=etc/mkdocs.yaml']);
});

/** Fixes the coding standards issues. */
task('fix', () => _exec('eslint', ['--config=etc/eslint.yaml', '--fix', 'src/**/*.ts']));

/** Performs the static analysis of source code. */
task('lint', () => _exec('eslint', ['--config=etc/eslint.yaml', 'src/**/*.ts']));

/** Publishes the package to the registry. */
task('publish:npm', () => _exec('npm', ['publish', '--registry=https://registry.npmjs.org']));
task('publish', series('clean', 'publish:npm'));

/** Starts the development server. */
task('serve', () => _exec('php', ['-S', '127.0.0.1:8000', '-t', 'src']));

/** Runs the test suites. */
const mocha = ['node_modules/.bin/mocha', '--recursive'];
task('test:run', () => _exec('c8', ['--all', '--include=lib/**/*.js', '--report-dir=var', '--reporter=lcovonly', ...mocha]));
task('test', series('build', 'test:run'));

/** Upgrades the project to the latest revision. */
task('upgrade', async () => {
await _exec('git', ['reset', '--hard']);
await _exec('git', ['fetch', '--all', '--prune']);
await _exec('git', ['pull', '--rebase']);
await _exec('npm', ['install', '--ignore-scripts', '--production=false']);
return _exec('npm', ['update', '--dev']);
});

/** Watches for file changes. */
task('watch', () => {
watch('src/**/*.ts', {ignoreInitial: false}, task('build'));
watch('test/**/*.js', task('test'));
});

/** Runs the default tasks. */
task('default', task('build'));

/**
* Spawns a new process using the specified command.
* @param {string} command The command to run.
* @param {string[]} args The command arguments.
* @param {SpawnOptionsWithoutStdio} options The settings to customize how the process is spawned.
* @return {Promise<void>} Completes when the command is finally terminated.
*/
function _exec(command, args = [], options = {}) {
return new Promise((fulfill, reject) => spawn(normalize(command), args, {shell: true, stdio: 'inherit', ...options})
.on('close', code => code ? reject(new Error(`${command}: ${code}`)) : fulfill())
);
}
task('phpMinify:import', () => import('../lib/index.js').then(mod => phpMinify = mod.phpMinify));
task('phpMinify:run', () => src('../src/php/*.php').pipe(phpMinify()).pipe(dest('../lib/php')));
task('default', series('phpMinify:import', 'phpMinify:run'));

+ 4
- 0
tool/lint.ps1 View File

@@ -0,0 +1,4 @@
#!/usr/bin/env pwsh
Set-StrictMode -Version Latest
Set-Location (Split-Path $PSScriptRoot)
node_modules/.bin/eslint.ps1 --config=etc/eslint.yaml src/**/*.ts

+ 6
- 0
tool/publish.ps1 View File

@@ -0,0 +1,6 @@
#!/usr/bin/env pwsh
Set-StrictMode -Version Latest
Set-Location (Split-Path $PSScriptRoot)

tool/clean.ps1
npm publish --registry=https://registry.npmjs.org

+ 4
- 0
tool/serve.ps1 View File

@@ -0,0 +1,4 @@
#!/usr/bin/env pwsh
Set-StrictMode -Version Latest
Set-Location (Split-Path $PSScriptRoot)
php -S 127.0.0.1:8000 -t src/php

+ 6
- 0
tool/test.ps1 View File

@@ -0,0 +1,6 @@
#!/usr/bin/env pwsh
Set-StrictMode -Version Latest
Set-Location (Split-Path $PSScriptRoot)

tool/build.ps1
node_modules/.bin/c8.ps1 --all --include=lib/**/*.js --report-dir=var --reporter=lcovonly node_modules/.bin/mocha.ps1 --recursive

+ 10
- 0
tool/upgrade.ps1 View File

@@ -0,0 +1,10 @@
#!/usr/bin/env pwsh
Set-StrictMode -Version Latest
Set-Location (Split-Path $PSScriptRoot)

git reset --hard
git fetch --all --prune
git pull --rebase

npm install --ignore-scripts --production=false
npm update --dev

+ 27
- 0
tool/watch.ps1 View File

@@ -0,0 +1,27 @@
#!/usr/bin/env pwsh
Set-StrictMode -Version Latest
Set-Location (Split-Path $PSScriptRoot)
[Console]::TreatControlCAsInput = $true

$action = {
$changeType = [String] $EventArgs.ChangeType
Write-Host "'$($EventArgs.Name)' was $($changeType.ToLower()): starting a new build..."
$timeSpan = Measure-Command { tool/build.ps1 }
Write-Host "> Finished the build after $($timeSpan.TotalSeconds) seconds."
}

$watcher = New-Object System.IO.FileSystemWatcher (Resolve-Path src).Path
$watcher.EnableRaisingEvents = $true
$watcher.IncludeSubdirectories = $true

foreach ($event in @('Changed', 'Created', 'Deleted', 'Renamed')) {
Register-ObjectEvent $watcher $event -Action $action | Out-Null
}

$console = $Host.UI.RawUI;
while ($true) {
if ($console.KeyAvailable -and ($console.ReadKey('AllowCtrlC,IncludeKeyUp,NoEcho').Character -eq 3)) { break }
Start-Sleep -Milliseconds 200
}

Get-EventSubscriber | Unregister-Event

Loading…
Cancel
Save