init
This commit is contained in:
21 files changed
+1394
No files matched your search
@@ -0,0 +1,7 @@
|
||||
/vendor
|
||||
/composer.lock
|
||||
/.phpunit.cache
|
||||
/.pest.cache
|
||||
/.idea
|
||||
/.vscode
|
||||
/.DS_Store
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Meghdad Fadaee
|
||||
|
||||
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.
|
||||
@@ -0,0 +1,110 @@
|
||||
# Laravel FTP Deploy
|
||||
|
||||
Deploy changed Laravel project files over FTP using a SamKirkland-compatible sync-state manifest.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
composer require meghdadfadaee/laravel-ftp-deploy
|
||||
```
|
||||
|
||||
The package registers itself through Laravel package discovery.
|
||||
|
||||
## Configuration
|
||||
|
||||
Add an FTP deploy disk to `config/filesystems.php`:
|
||||
|
||||
```php
|
||||
'ftp_deploy' => [
|
||||
'driver' => 'ftp',
|
||||
'host' => env('FTP_DEPLOY_HOST'),
|
||||
'username' => env('FTP_DEPLOY_USERNAME'),
|
||||
'password' => env('FTP_DEPLOY_PASSWORD'),
|
||||
'port' => (int) env('FTP_DEPLOY_PORT', 21),
|
||||
'root' => env('FTP_DEPLOY_ROOT'),
|
||||
'passive' => env('FTP_DEPLOY_PASSIVE', true),
|
||||
'ssl' => env('FTP_DEPLOY_SSL', false),
|
||||
'timeout' => (int) env('FTP_DEPLOY_TIMEOUT', 30),
|
||||
'throw' => true,
|
||||
'report' => false,
|
||||
],
|
||||
```
|
||||
|
||||
Customize deploy behavior in `config/services.php`:
|
||||
|
||||
```php
|
||||
'ftp_deploy' => [
|
||||
'disk' => env('FTP_DEPLOY_DISK', 'ftp_deploy'),
|
||||
'local_root' => env('FTP_DEPLOY_LOCAL_ROOT', base_path()),
|
||||
'state_path' => env('FTP_DEPLOY_STATE_PATH', 'storage/app/.ftp-deploy-sync-state.json'),
|
||||
'api_token' => env('FTP_DEPLOY_API_TOKEN'),
|
||||
'route' => [
|
||||
'enabled' => env('FTP_DEPLOY_ROUTE_ENABLED', true),
|
||||
'path' => env('FTP_DEPLOY_ROUTE_PATH', 'ftp/generate-sync-state'),
|
||||
'name' => env('FTP_DEPLOY_ROUTE_NAME', 'ftp-deploy.generate-sync-state'),
|
||||
'middleware' => ['api'],
|
||||
],
|
||||
'exclude' => array_filter(array_map('trim', explode(',', env(
|
||||
'FTP_DEPLOY_EXCLUDE',
|
||||
'.git,.idea,.vscode,.env,node_modules,storage/logs,storage/framework/cache,storage/framework/sessions,storage/framework/views,storage/app/.ftp-deploy-sync-state.json,.ftp-deploy-sync-state.json',
|
||||
)))),
|
||||
],
|
||||
```
|
||||
|
||||
Useful environment keys:
|
||||
|
||||
```dotenv
|
||||
FTP_DEPLOY_HOST=
|
||||
FTP_DEPLOY_USERNAME=
|
||||
FTP_DEPLOY_PASSWORD=
|
||||
FTP_DEPLOY_PORT=21
|
||||
FTP_DEPLOY_ROOT=
|
||||
FTP_DEPLOY_PASSIVE=true
|
||||
FTP_DEPLOY_SSL=false
|
||||
FTP_DEPLOY_TIMEOUT=30
|
||||
FTP_DEPLOY_DISK=ftp_deploy
|
||||
FTP_DEPLOY_STATE_PATH=storage/app/.ftp-deploy-sync-state.json
|
||||
FTP_DEPLOY_API_TOKEN=
|
||||
```
|
||||
|
||||
## Commands
|
||||
|
||||
Preview changed files:
|
||||
|
||||
```bash
|
||||
php artisan ftp:deploy --dry-run
|
||||
```
|
||||
|
||||
Upload changed files and update the remote sync-state:
|
||||
|
||||
```bash
|
||||
php artisan ftp:deploy --yes
|
||||
```
|
||||
|
||||
Generate a sync-state file locally:
|
||||
|
||||
```bash
|
||||
php artisan ftp:generate-sync-state --output=storage/app/.ftp-deploy-sync-state.json
|
||||
```
|
||||
|
||||
Extra excludes may be passed as repeated options or comma-separated values:
|
||||
|
||||
```bash
|
||||
php artisan ftp:deploy --exclude=vendor --exclude="*.map" --yes
|
||||
```
|
||||
|
||||
## JSON API
|
||||
|
||||
The package registers `GET /ftp/generate-sync-state` by default. It requires either:
|
||||
|
||||
```http
|
||||
Authorization: Bearer your-token
|
||||
```
|
||||
|
||||
or:
|
||||
|
||||
```http
|
||||
X-Ftp-Deploy-Token: your-token
|
||||
```
|
||||
|
||||
The route generates the current sync-state, persists it to `services.ftp_deploy.state_path`, and returns JSON with summary metadata and the full state payload.
|
||||
@@ -0,0 +1,62 @@
|
||||
{
|
||||
"name": "meghdadfadaee/laravel-ftp-deploy",
|
||||
"description": "Deploy changed Laravel project files over FTP using a sync-state manifest.",
|
||||
"type": "library",
|
||||
"license": "MIT",
|
||||
"keywords": [
|
||||
"laravel",
|
||||
"ftp",
|
||||
"deploy",
|
||||
"sync-state"
|
||||
],
|
||||
"authors": [
|
||||
{
|
||||
"name": "Meghdad Fadaee"
|
||||
}
|
||||
],
|
||||
"require": {
|
||||
"php": "^8.3",
|
||||
"illuminate/console": "^13.0",
|
||||
"illuminate/contracts": "^13.0",
|
||||
"illuminate/filesystem": "^13.0",
|
||||
"illuminate/routing": "^13.0",
|
||||
"illuminate/support": "^13.0",
|
||||
"laravel/prompts": "^0.3",
|
||||
"league/flysystem-ftp": "^3.0"
|
||||
},
|
||||
"require-dev": {
|
||||
"laravel/pint": "^1.27",
|
||||
"orchestra/testbench": "^11.1",
|
||||
"pestphp/pest": "^4.7",
|
||||
"pestphp/pest-plugin-laravel": "^4.1"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"MeghdadFadaee\\LaravelFtpDeploy\\": "src/"
|
||||
}
|
||||
},
|
||||
"autoload-dev": {
|
||||
"psr-4": {
|
||||
"MeghdadFadaee\\LaravelFtpDeploy\\Tests\\": "tests/"
|
||||
}
|
||||
},
|
||||
"extra": {
|
||||
"laravel": {
|
||||
"providers": [
|
||||
"MeghdadFadaee\\LaravelFtpDeploy\\LaravelFtpDeployServiceProvider"
|
||||
]
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"format": "pint",
|
||||
"test": "pest"
|
||||
},
|
||||
"config": {
|
||||
"sort-packages": true,
|
||||
"allow-plugins": {
|
||||
"pestphp/pest-plugin": true
|
||||
}
|
||||
},
|
||||
"minimum-stability": "stable",
|
||||
"prefer-stable": true
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
'disks' => [
|
||||
'ftp_deploy' => [
|
||||
'driver' => 'ftp',
|
||||
'host' => env('FTP_DEPLOY_HOST'),
|
||||
'username' => env('FTP_DEPLOY_USERNAME'),
|
||||
'password' => env('FTP_DEPLOY_PASSWORD'),
|
||||
'port' => (int) env('FTP_DEPLOY_PORT', 21),
|
||||
'root' => env('FTP_DEPLOY_ROOT'),
|
||||
'passive' => env('FTP_DEPLOY_PASSIVE', true),
|
||||
'ssl' => env('FTP_DEPLOY_SSL', false),
|
||||
'timeout' => (int) env('FTP_DEPLOY_TIMEOUT', 30),
|
||||
'throw' => true,
|
||||
'report' => false,
|
||||
],
|
||||
],
|
||||
];
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
'ftp_deploy' => [
|
||||
'disk' => env('FTP_DEPLOY_DISK', 'ftp_deploy'),
|
||||
'local_root' => env('FTP_DEPLOY_LOCAL_ROOT', base_path()),
|
||||
'state_path' => env('FTP_DEPLOY_STATE_PATH', 'storage/app/.ftp-deploy-sync-state.json'),
|
||||
'api_token' => env('FTP_DEPLOY_API_TOKEN'),
|
||||
'route' => [
|
||||
'enabled' => env('FTP_DEPLOY_ROUTE_ENABLED', true),
|
||||
'path' => env('FTP_DEPLOY_ROUTE_PATH', 'ftp/generate-sync-state'),
|
||||
'name' => env('FTP_DEPLOY_ROUTE_NAME', 'ftp-deploy.generate-sync-state'),
|
||||
'middleware' => ['api'],
|
||||
],
|
||||
'exclude' => array_filter(array_map('trim', explode(',', env(
|
||||
'FTP_DEPLOY_EXCLUDE',
|
||||
'.git,.idea,.vscode,.env,node_modules,storage/logs,storage/framework/cache,storage/framework/sessions,storage/framework/views,storage/app/.ftp-deploy-sync-state.json,.ftp-deploy-sync-state.json',
|
||||
)))),
|
||||
],
|
||||
];
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
|
||||
bootstrap="vendor/autoload.php"
|
||||
colors="true"
|
||||
>
|
||||
<testsuites>
|
||||
<testsuite name="Feature">
|
||||
<directory>tests/Feature</directory>
|
||||
</testsuite>
|
||||
</testsuites>
|
||||
<source>
|
||||
<include>
|
||||
<directory>src</directory>
|
||||
</include>
|
||||
</source>
|
||||
<php>
|
||||
<env name="APP_ENV" value="testing"/>
|
||||
<env name="APP_KEY" value="base64:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="/>
|
||||
</php>
|
||||
</phpunit>
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use MeghdadFadaee\LaravelFtpDeploy\Http\Controllers\GenerateSyncStateController;
|
||||
use MeghdadFadaee\LaravelFtpDeploy\Http\Middleware\EnsureValidFtpDeployToken;
|
||||
|
||||
$middleware = Arr::wrap(config('services.ftp_deploy.route.middleware', ['api']));
|
||||
$middleware[] = EnsureValidFtpDeployToken::class;
|
||||
|
||||
Route::middleware($middleware)
|
||||
->get(config('services.ftp_deploy.route.path', 'ftp/generate-sync-state'), GenerateSyncStateController::class)
|
||||
->name(config('services.ftp_deploy.route.name', 'ftp-deploy.generate-sync-state'));
|
||||
@@ -0,0 +1,200 @@
|
||||
<?php
|
||||
|
||||
namespace MeghdadFadaee\LaravelFtpDeploy\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Number;
|
||||
use Laravel\Prompts\Progress;
|
||||
use MeghdadFadaee\LaravelFtpDeploy\Services\FtpDeployManager;
|
||||
use Throwable;
|
||||
|
||||
use function Laravel\Prompts\confirm;
|
||||
use function Laravel\Prompts\error;
|
||||
use function Laravel\Prompts\info;
|
||||
use function Laravel\Prompts\intro;
|
||||
use function Laravel\Prompts\outro;
|
||||
use function Laravel\Prompts\progress;
|
||||
use function Laravel\Prompts\table;
|
||||
use function Laravel\Prompts\warning;
|
||||
|
||||
#[Signature('ftp:deploy
|
||||
{path? : Local directory to deploy (defaults to services.ftp_deploy.local_root)}
|
||||
{--disk= : Filesystem disk configured for the FTP server}
|
||||
{--state= : Remote sync-state file path}
|
||||
{--exclude=* : Extra exclude path or wildcard pattern; comma-separated values are supported}
|
||||
{--dry-run : Show what would be uploaded without changing the FTP server}
|
||||
{--force : Upload every included local file}
|
||||
{--yes : Skip the confirmation prompt}')]
|
||||
#[Description('Deploy local changes to the configured FTP server using the remote sync-state file')]
|
||||
class DeployFtpChangedFilesCommand extends Command
|
||||
{
|
||||
public function __construct(private readonly FtpDeployManager $ftpDeployManager)
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
try {
|
||||
$diskName = $this->ftpDeployManager->diskName($this->optionString('disk'));
|
||||
$localRoot = $this->ftpDeployManager->localRoot($this->argumentString('path'));
|
||||
$statePath = $this->ftpDeployManager->statePath($this->optionString('state'));
|
||||
$excludedPatterns = $this->ftpDeployManager->excludedPatterns($this->option('exclude'), $statePath);
|
||||
|
||||
intro('Preparing FTP deployment');
|
||||
info("Local root: {$localRoot}");
|
||||
info("FTP disk: {$diskName}");
|
||||
info("Remote state: {$statePath}");
|
||||
|
||||
if ($excludedPatterns !== []) {
|
||||
info('Excluding: '.implode(', ', $excludedPatterns));
|
||||
}
|
||||
|
||||
$remoteDisk = Storage::disk($diskName);
|
||||
$currentState = $this->ftpDeployManager->buildCurrentState($localRoot, $excludedPatterns);
|
||||
$remoteState = $this->ftpDeployManager->readRemoteState($remoteDisk, $statePath);
|
||||
|
||||
if ($remoteState === null) {
|
||||
warning("Remote sync-state file was not found at [{$statePath}]. Every included local file will be uploaded.");
|
||||
$remoteState = $this->ftpDeployManager->emptySyncState();
|
||||
}
|
||||
|
||||
$changedFiles = $this->ftpDeployManager->changedFiles($currentState, $remoteState, (bool) $this->option('force'));
|
||||
|
||||
$this->renderSummary($currentState, $changedFiles, $excludedPatterns);
|
||||
|
||||
if ($changedFiles === []) {
|
||||
info('No changed files detected.');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
if ((bool) $this->option('dry-run')) {
|
||||
$this->renderChangedFiles($changedFiles);
|
||||
outro('Dry run complete. No files were uploaded.');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
if (! $this->shouldContinue(count($changedFiles), $diskName)) {
|
||||
warning('FTP deployment cancelled.');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$this->uploadChangedFiles($remoteDisk, $localRoot, $changedFiles);
|
||||
$this->ftpDeployManager->writeRemoteState($remoteDisk, $statePath, $currentState);
|
||||
|
||||
outro('FTP deployment finished. Uploaded '.Number::format(count($changedFiles)).' files.');
|
||||
|
||||
return self::SUCCESS;
|
||||
} catch (Throwable $exception) {
|
||||
error($exception->getMessage());
|
||||
|
||||
if ($this->output->isVerbose()) {
|
||||
throw $exception;
|
||||
}
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{data: array<int, array<string, mixed>>} $currentState
|
||||
* @param array<int, array<string, mixed>> $changedFiles
|
||||
* @param array<int, string> $excludedPatterns
|
||||
*/
|
||||
private function renderSummary(array $currentState, array $changedFiles, array $excludedPatterns): void
|
||||
{
|
||||
table(
|
||||
headers: ['Metric', 'Value'],
|
||||
rows: [
|
||||
['Included files', Number::format($this->fileCount($currentState))],
|
||||
['Files to upload', Number::format(count($changedFiles))],
|
||||
['Exclude patterns', Number::format(count($excludedPatterns))],
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{data: array<int, array<string, mixed>>} $state
|
||||
*/
|
||||
private function fileCount(array $state): int
|
||||
{
|
||||
return collect($state['data'])
|
||||
->filter(fn (mixed $entry): bool => is_array($entry) && ($entry['type'] ?? null) === 'file')
|
||||
->count();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, array<string, mixed>> $changedFiles
|
||||
*/
|
||||
private function renderChangedFiles(array $changedFiles): void
|
||||
{
|
||||
table(
|
||||
headers: ['Path', 'Size'],
|
||||
rows: collect($changedFiles)
|
||||
->take(20)
|
||||
->map(fn (array $entry): array => [
|
||||
(string) $entry['name'],
|
||||
Number::fileSize((int) $entry['size']),
|
||||
])
|
||||
->values()
|
||||
->all(),
|
||||
);
|
||||
|
||||
if (count($changedFiles) > 20) {
|
||||
info('...and '.Number::format(count($changedFiles) - 20).' more files.');
|
||||
}
|
||||
}
|
||||
|
||||
private function shouldContinue(int $changedFileCount, string $diskName): bool
|
||||
{
|
||||
if ((bool) $this->option('yes') || ! $this->input->isInteractive()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return confirm(
|
||||
label: 'Upload '.Number::format($changedFileCount)." changed files to [{$diskName}]?",
|
||||
default: false,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, array<string, mixed>> $changedFiles
|
||||
*/
|
||||
private function uploadChangedFiles(mixed $remoteDisk, string $localRoot, array $changedFiles): void
|
||||
{
|
||||
progress(
|
||||
label: 'Uploading changed files',
|
||||
steps: $changedFiles,
|
||||
callback: function (array $entry, Progress $progress) use ($remoteDisk, $localRoot): void {
|
||||
$path = (string) $entry['name'];
|
||||
|
||||
$progress
|
||||
->label("Uploading {$path}")
|
||||
->hint(Number::fileSize((int) $entry['size']));
|
||||
|
||||
$this->ftpDeployManager->uploadFile($remoteDisk, $localRoot, $path);
|
||||
},
|
||||
hint: Number::format(count($changedFiles)).' files',
|
||||
);
|
||||
}
|
||||
|
||||
private function argumentString(string $key): ?string
|
||||
{
|
||||
$value = $this->argument($key);
|
||||
|
||||
return is_string($value) && trim($value) !== '' ? $value : null;
|
||||
}
|
||||
|
||||
private function optionString(string $key): ?string
|
||||
{
|
||||
$value = $this->option($key);
|
||||
|
||||
return is_string($value) && trim($value) !== '' ? $value : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
<?php
|
||||
|
||||
namespace MeghdadFadaee\LaravelFtpDeploy\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Number;
|
||||
use MeghdadFadaee\LaravelFtpDeploy\Services\FtpDeployManager;
|
||||
use MeghdadFadaee\LaravelFtpDeploy\Services\SyncStateGenerator;
|
||||
use Throwable;
|
||||
|
||||
use function Laravel\Prompts\error;
|
||||
use function Laravel\Prompts\info;
|
||||
use function Laravel\Prompts\intro;
|
||||
use function Laravel\Prompts\outro;
|
||||
use function Laravel\Prompts\table;
|
||||
|
||||
class GenerateFtpSyncStateCommand extends Command
|
||||
{
|
||||
protected $signature = 'ftp:generate-sync-state
|
||||
{path=. : Directory path to scan}
|
||||
{--output= : Output file path (default: {path}/.ftp-deploy-sync-state.json)}
|
||||
{--exclude= : Comma-separated exclude patterns (relative to path)}';
|
||||
|
||||
protected $description = 'Generate .ftp-deploy-sync-state.json from local files';
|
||||
|
||||
public function __construct(
|
||||
private readonly FtpDeployManager $ftpDeployManager,
|
||||
private readonly SyncStateGenerator $syncStateGenerator,
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
try {
|
||||
$localRoot = $this->ftpDeployManager->localRoot((string) $this->argument('path'));
|
||||
$outputPath = $this->outputPath($localRoot);
|
||||
$excludedPatterns = $this->ftpDeployManager->excludedPatterns($this->option('exclude'));
|
||||
$state = $this->syncStateGenerator->generate($localRoot, $excludedPatterns, $outputPath);
|
||||
$counts = $this->syncStateGenerator->counts($state);
|
||||
|
||||
intro('Generating FTP sync-state');
|
||||
info("Scanning: {$localRoot}");
|
||||
info("Output file: {$outputPath}");
|
||||
|
||||
if ($excludedPatterns !== []) {
|
||||
info('Excluding: '.implode(', ', $excludedPatterns));
|
||||
}
|
||||
|
||||
$this->syncStateGenerator->writeToPath($outputPath, $state);
|
||||
|
||||
table(
|
||||
headers: ['Metric', 'Count'],
|
||||
rows: [
|
||||
['Files', Number::format($counts['files'])],
|
||||
['Folders', Number::format($counts['folders'])],
|
||||
],
|
||||
);
|
||||
|
||||
outro("Sync state saved to: {$outputPath}");
|
||||
|
||||
return self::SUCCESS;
|
||||
} catch (Throwable $exception) {
|
||||
error($exception->getMessage());
|
||||
|
||||
if ($this->output->isVerbose()) {
|
||||
throw $exception;
|
||||
}
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
}
|
||||
|
||||
private function outputPath(string $localRoot): string
|
||||
{
|
||||
$output = $this->option('output');
|
||||
|
||||
if (is_string($output) && trim($output) !== '') {
|
||||
if (str_starts_with($output, DIRECTORY_SEPARATOR) || preg_match('/^[A-Za-z]:[\/\\\\]/', $output) === 1) {
|
||||
return str_replace('\\', '/', $output);
|
||||
}
|
||||
|
||||
return str_replace('\\', '/', getcwd().DIRECTORY_SEPARATOR.$output);
|
||||
}
|
||||
|
||||
return "{$localRoot}/.ftp-deploy-sync-state.json";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
namespace MeghdadFadaee\LaravelFtpDeploy\Http\Controllers;
|
||||
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use MeghdadFadaee\LaravelFtpDeploy\Services\FtpDeployManager;
|
||||
use MeghdadFadaee\LaravelFtpDeploy\Services\SyncStateGenerator;
|
||||
|
||||
class GenerateSyncStateController
|
||||
{
|
||||
public function __construct(
|
||||
private readonly FtpDeployManager $ftpDeployManager,
|
||||
private readonly SyncStateGenerator $syncStateGenerator,
|
||||
) {}
|
||||
|
||||
public function __invoke(): JsonResponse
|
||||
{
|
||||
$localRoot = $this->ftpDeployManager->localRoot();
|
||||
$statePath = $this->ftpDeployManager->statePath();
|
||||
$outputPath = $this->ftpDeployManager->localStateOutputPath();
|
||||
$excludedPatterns = $this->ftpDeployManager->excludedPatterns([], $statePath);
|
||||
$state = $this->syncStateGenerator->generate($localRoot, $excludedPatterns, $outputPath);
|
||||
$counts = $this->syncStateGenerator->counts($state);
|
||||
|
||||
$this->syncStateGenerator->writeToPath($outputPath, $state);
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'path' => $outputPath,
|
||||
'files' => $counts['files'],
|
||||
'folders' => $counts['folders'],
|
||||
'generated_time' => $state['generatedTime'],
|
||||
'state' => $state,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
namespace MeghdadFadaee\LaravelFtpDeploy\Http\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class EnsureValidFtpDeployToken
|
||||
{
|
||||
/**
|
||||
* @param Closure(Request): Response $next
|
||||
*/
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
$configuredToken = config('services.ftp_deploy.api_token');
|
||||
|
||||
if (! is_string($configuredToken) || $configuredToken === '') {
|
||||
return $this->forbidden('FTP deploy API token is not configured.');
|
||||
}
|
||||
|
||||
$providedToken = $request->bearerToken() ?: $request->header('X-Ftp-Deploy-Token');
|
||||
|
||||
if (! is_string($providedToken) || ! hash_equals($configuredToken, $providedToken)) {
|
||||
return $this->forbidden('Invalid FTP deploy API token.');
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
private function forbidden(string $message): JsonResponse
|
||||
{
|
||||
return response()->json([
|
||||
'message' => $message,
|
||||
], 403);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
namespace MeghdadFadaee\LaravelFtpDeploy;
|
||||
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
use MeghdadFadaee\LaravelFtpDeploy\Console\Commands\DeployFtpChangedFilesCommand;
|
||||
use MeghdadFadaee\LaravelFtpDeploy\Console\Commands\GenerateFtpSyncStateCommand;
|
||||
use MeghdadFadaee\LaravelFtpDeploy\Services\ExcludeMatcher;
|
||||
use MeghdadFadaee\LaravelFtpDeploy\Services\FtpDeployManager;
|
||||
use MeghdadFadaee\LaravelFtpDeploy\Services\SyncStateGenerator;
|
||||
|
||||
class LaravelFtpDeployServiceProvider extends ServiceProvider
|
||||
{
|
||||
public function register(): void
|
||||
{
|
||||
$this->replaceConfigRecursivelyFrom(__DIR__.'/../config/filesystems.php', 'filesystems');
|
||||
$this->replaceConfigRecursivelyFrom(__DIR__.'/../config/services.php', 'services');
|
||||
|
||||
$this->app->singleton(ExcludeMatcher::class);
|
||||
$this->app->singleton(SyncStateGenerator::class);
|
||||
$this->app->singleton(FtpDeployManager::class);
|
||||
}
|
||||
|
||||
public function boot(): void
|
||||
{
|
||||
if ($this->app->runningInConsole()) {
|
||||
$this->commands([
|
||||
DeployFtpChangedFilesCommand::class,
|
||||
GenerateFtpSyncStateCommand::class,
|
||||
]);
|
||||
|
||||
$this->publishes([
|
||||
__DIR__.'/../config/filesystems.php' => config_path('ftp-deploy-filesystems.php'),
|
||||
__DIR__.'/../config/services.php' => config_path('ftp-deploy-services.php'),
|
||||
], 'ftp-deploy-config');
|
||||
}
|
||||
|
||||
if (config('services.ftp_deploy.route.enabled', true)) {
|
||||
$this->loadRoutesFrom(__DIR__.'/../routes/api.php');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
namespace MeghdadFadaee\LaravelFtpDeploy\Services;
|
||||
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Str;
|
||||
use MeghdadFadaee\LaravelFtpDeploy\Support\Path;
|
||||
|
||||
class ExcludeMatcher
|
||||
{
|
||||
/**
|
||||
* @return array<int, string>
|
||||
*/
|
||||
public function patterns(mixed $values): array
|
||||
{
|
||||
return collect(Arr::wrap($values))
|
||||
->flatMap(fn (mixed $value): array => explode(',', (string) $value))
|
||||
->map(fn (string $pattern): string => Path::normalizeRelative($pattern))
|
||||
->filter()
|
||||
->unique()
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $patterns
|
||||
*/
|
||||
public function isExcluded(string $relativePath, array $patterns): bool
|
||||
{
|
||||
$relativePath = Path::normalizeRelative($relativePath);
|
||||
|
||||
foreach ($patterns as $pattern) {
|
||||
if ($relativePath === $pattern || Str::startsWith($relativePath, "{$pattern}/")) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (Str::is($pattern, $relativePath) || Str::is("{$pattern}/*", $relativePath)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
<?php
|
||||
|
||||
namespace MeghdadFadaee\LaravelFtpDeploy\Services;
|
||||
|
||||
use Illuminate\Contracts\Filesystem\Filesystem;
|
||||
use Illuminate\Support\Arr;
|
||||
use JsonException;
|
||||
use MeghdadFadaee\LaravelFtpDeploy\Support\Path;
|
||||
use RuntimeException;
|
||||
|
||||
class FtpDeployManager
|
||||
{
|
||||
public function __construct(
|
||||
private readonly SyncStateGenerator $syncStateGenerator,
|
||||
private readonly ExcludeMatcher $excludeMatcher,
|
||||
) {}
|
||||
|
||||
public function diskName(?string $disk = null): string
|
||||
{
|
||||
$diskName = $disk ?: config('services.ftp_deploy.disk', 'ftp_deploy');
|
||||
|
||||
if (! is_string($diskName) || trim($diskName) === '') {
|
||||
throw new RuntimeException('No FTP deploy disk is configured.');
|
||||
}
|
||||
|
||||
return trim($diskName);
|
||||
}
|
||||
|
||||
public function localRoot(?string $path = null): string
|
||||
{
|
||||
$path = $path ?: config('services.ftp_deploy.local_root', base_path());
|
||||
$root = realpath((string) $path);
|
||||
|
||||
if ($root === false || ! is_dir($root)) {
|
||||
throw new RuntimeException("Local deploy path not found: {$path}");
|
||||
}
|
||||
|
||||
return rtrim(str_replace('\\', '/', $root), '/');
|
||||
}
|
||||
|
||||
public function statePath(?string $statePath = null): string
|
||||
{
|
||||
$statePath = $statePath ?: config('services.ftp_deploy.state_path', 'storage/app/.ftp-deploy-sync-state.json');
|
||||
|
||||
if (! is_string($statePath) || trim($statePath) === '') {
|
||||
throw new RuntimeException('No FTP deploy sync-state path is configured.');
|
||||
}
|
||||
|
||||
return Path::normalizeRelative($statePath);
|
||||
}
|
||||
|
||||
public function localStateOutputPath(?string $statePath = null): string
|
||||
{
|
||||
$statePath = $statePath ?: config('services.ftp_deploy.state_path', 'storage/app/.ftp-deploy-sync-state.json');
|
||||
|
||||
if (! is_string($statePath) || trim($statePath) === '') {
|
||||
throw new RuntimeException('No FTP deploy sync-state path is configured.');
|
||||
}
|
||||
|
||||
return Path::absoluteFromBase($statePath);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, string>
|
||||
*/
|
||||
public function excludedPatterns(mixed $extraExcludes = [], ?string $statePath = null): array
|
||||
{
|
||||
return $this->excludeMatcher->patterns([
|
||||
...Arr::wrap(config('services.ftp_deploy.exclude', [])),
|
||||
...Arr::wrap($extraExcludes),
|
||||
$statePath ?: config('services.ftp_deploy.state_path', 'storage/app/.ftp-deploy-sync-state.json'),
|
||||
'.ftp-deploy-sync-state.json',
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $excludedPatterns
|
||||
* @return array{description: string, version: string, generatedTime: int, data: array<int, array<string, mixed>>}
|
||||
*/
|
||||
public function buildCurrentState(string $localRoot, array $excludedPatterns, ?string $outputPath = null): array
|
||||
{
|
||||
return $this->syncStateGenerator->generate($localRoot, $excludedPatterns, $outputPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{description: string, version: string, generatedTime: int, data: array<int, array<string, mixed>>}|null
|
||||
*/
|
||||
public function readRemoteState(Filesystem $remoteDisk, string $statePath): ?array
|
||||
{
|
||||
if (! $remoteDisk->exists($statePath)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$contents = $remoteDisk->get($statePath);
|
||||
|
||||
if (! is_string($contents) || trim($contents) === '') {
|
||||
throw new RuntimeException("Remote sync-state file [{$statePath}] is empty.");
|
||||
}
|
||||
|
||||
return $this->decodeSyncState($contents, $statePath);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{description: string, version: string, generatedTime: int, data: array<int, array<string, mixed>>}
|
||||
*/
|
||||
public function emptySyncState(): array
|
||||
{
|
||||
return [
|
||||
'description' => SyncStateGenerator::DESCRIPTION,
|
||||
'version' => '1.0.0',
|
||||
'generatedTime' => 0,
|
||||
'data' => [],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{data: array<int, array<string, mixed>>} $currentState
|
||||
* @param array{data: array<int, array<string, mixed>>} $remoteState
|
||||
* @return array<int, array{type: string, name: string, size: int, hash: string}>
|
||||
*/
|
||||
public function changedFiles(array $currentState, array $remoteState, bool $force = false): array
|
||||
{
|
||||
$remoteFiles = collect($remoteState['data'])
|
||||
->filter(fn (mixed $entry): bool => is_array($entry) && ($entry['type'] ?? null) === 'file' && isset($entry['name']))
|
||||
->keyBy(fn (array $entry): string => (string) $entry['name']);
|
||||
|
||||
return collect($currentState['data'])
|
||||
->filter(fn (mixed $entry): bool => is_array($entry) && ($entry['type'] ?? null) === 'file')
|
||||
->filter(function (array $entry) use ($remoteFiles, $force): bool {
|
||||
if ($force) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$remoteEntry = $remoteFiles->get($entry['name']);
|
||||
|
||||
if (! is_array($remoteEntry)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return (int) ($remoteEntry['size'] ?? -1) !== (int) $entry['size']
|
||||
|| (string) ($remoteEntry['hash'] ?? '') !== (string) $entry['hash'];
|
||||
})
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
|
||||
public function uploadFile(Filesystem $remoteDisk, string $localRoot, string $relativePath): void
|
||||
{
|
||||
$this->ensureRemoteDirectoryExists($remoteDisk, dirname($relativePath));
|
||||
|
||||
$localPath = "{$localRoot}/{$relativePath}";
|
||||
$stream = fopen($localPath, 'rb');
|
||||
|
||||
if ($stream === false) {
|
||||
throw new RuntimeException("Unable to open local file for upload: {$relativePath}");
|
||||
}
|
||||
|
||||
try {
|
||||
if (! $remoteDisk->put($relativePath, $stream)) {
|
||||
throw new RuntimeException("Unable to upload file: {$relativePath}");
|
||||
}
|
||||
} finally {
|
||||
fclose($stream);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{description: string, version: string, generatedTime: int, data: array<int, array<string, mixed>>} $currentState
|
||||
*/
|
||||
public function writeRemoteState(Filesystem $remoteDisk, string $statePath, array $currentState): void
|
||||
{
|
||||
try {
|
||||
$encoded = json_encode($currentState, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);
|
||||
} catch (JsonException $exception) {
|
||||
throw new RuntimeException("Unable to encode updated sync-state JSON: {$exception->getMessage()}", previous: $exception);
|
||||
}
|
||||
|
||||
$this->ensureRemoteDirectoryExists($remoteDisk, dirname($statePath));
|
||||
|
||||
if (! $remoteDisk->put($statePath, $encoded)) {
|
||||
throw new RuntimeException("Unable to write remote sync-state file: {$statePath}");
|
||||
}
|
||||
}
|
||||
|
||||
private function ensureRemoteDirectoryExists(Filesystem $remoteDisk, string $directory): void
|
||||
{
|
||||
if ($directory === '.' || $directory === '/' || $directory === '') {
|
||||
return;
|
||||
}
|
||||
|
||||
$segments = explode('/', Path::normalizeRelative($directory));
|
||||
$path = '';
|
||||
|
||||
foreach ($segments as $segment) {
|
||||
$path = $path === '' ? $segment : "{$path}/{$segment}";
|
||||
|
||||
if (method_exists($remoteDisk, 'directoryExists') && $remoteDisk->directoryExists($path)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$remoteDisk->makeDirectory($path);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{description: string, version: string, generatedTime: int, data: array<int, array<string, mixed>>}
|
||||
*/
|
||||
private function decodeSyncState(string $contents, string $source): array
|
||||
{
|
||||
try {
|
||||
$state = json_decode($contents, true, flags: JSON_THROW_ON_ERROR);
|
||||
} catch (JsonException $exception) {
|
||||
throw new RuntimeException("Remote sync-state file [{$source}] is not valid JSON: {$exception->getMessage()}", previous: $exception);
|
||||
}
|
||||
|
||||
if (! is_array($state) || ! isset($state['data']) || ! is_array($state['data'])) {
|
||||
throw new RuntimeException("Remote sync-state file [{$source}] does not contain a valid data array.");
|
||||
}
|
||||
|
||||
return [
|
||||
'description' => (string) ($state['description'] ?? SyncStateGenerator::DESCRIPTION),
|
||||
'version' => (string) ($state['version'] ?? '1.0.0'),
|
||||
'generatedTime' => (int) ($state['generatedTime'] ?? 0),
|
||||
'data' => $state['data'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
<?php
|
||||
|
||||
namespace MeghdadFadaee\LaravelFtpDeploy\Services;
|
||||
|
||||
use FilesystemIterator;
|
||||
use JsonException;
|
||||
use MeghdadFadaee\LaravelFtpDeploy\Support\Path;
|
||||
use RecursiveCallbackFilterIterator;
|
||||
use RecursiveDirectoryIterator;
|
||||
use RecursiveIteratorIterator;
|
||||
use RuntimeException;
|
||||
use SplFileInfo;
|
||||
|
||||
class SyncStateGenerator
|
||||
{
|
||||
public const DESCRIPTION = 'DO NOT DELETE THIS FILE. This file is used to keep track of which files have been synced in the most recent deployment. If you delete this file a resync will need to be done (which can take a while) - read more: https://github.com/SamKirkland/FTP-Deploy-Action';
|
||||
|
||||
public function __construct(private readonly ExcludeMatcher $excludeMatcher) {}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $excludedPatterns
|
||||
* @return array{description: string, version: string, generatedTime: int, data: array<int, array<string, mixed>>}
|
||||
*/
|
||||
public function generate(string $root, array $excludedPatterns = [], ?string $outputPath = null): array
|
||||
{
|
||||
$root = $this->resolveRoot($root);
|
||||
$excludedPatterns = $this->excludeMatcher->patterns($excludedPatterns);
|
||||
|
||||
if ($outputPath !== null) {
|
||||
$outputRelativePath = $this->relativePathIfInsideRoot($root, $outputPath);
|
||||
|
||||
if ($outputRelativePath !== null) {
|
||||
$excludedPatterns = $this->excludeMatcher->patterns([...$excludedPatterns, $outputRelativePath]);
|
||||
}
|
||||
}
|
||||
|
||||
$files = [];
|
||||
$folders = [];
|
||||
$directory = new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS);
|
||||
$filter = new RecursiveCallbackFilterIterator(
|
||||
$directory,
|
||||
function (SplFileInfo $item) use ($root, $excludedPatterns): bool {
|
||||
if ($item->isLink()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return ! $this->excludeMatcher->isExcluded(
|
||||
Path::relativeToRoot($root, $item->getPathname()),
|
||||
$excludedPatterns,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
$iterator = new RecursiveIteratorIterator($filter, RecursiveIteratorIterator::SELF_FIRST);
|
||||
|
||||
foreach ($iterator as $item) {
|
||||
/** @var SplFileInfo $item */
|
||||
$relativePath = Path::relativeToRoot($root, $item->getPathname());
|
||||
|
||||
if ($relativePath === '' || $this->excludeMatcher->isExcluded($relativePath, $excludedPatterns)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($item->isDir()) {
|
||||
$folders[$relativePath] = true;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! $item->isFile()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$files[] = $this->fileEntry($item, $relativePath);
|
||||
$this->rememberParentFolders($folders, $relativePath);
|
||||
}
|
||||
|
||||
$folderEntries = collect(array_keys($folders))
|
||||
->sort()
|
||||
->map(fn (string $name): array => [
|
||||
'type' => 'folder',
|
||||
'name' => $name,
|
||||
])
|
||||
->values()
|
||||
->all();
|
||||
|
||||
usort($files, fn (array $first, array $second): int => strcmp($first['name'], $second['name']));
|
||||
|
||||
return [
|
||||
'description' => self::DESCRIPTION,
|
||||
'version' => '1.0.0',
|
||||
'generatedTime' => $this->currentMillis(),
|
||||
'data' => array_merge($files, $folderEntries),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{data: array<int, array<string, mixed>>} $state
|
||||
* @return array{files: int, folders: int}
|
||||
*/
|
||||
public function counts(array $state): array
|
||||
{
|
||||
return [
|
||||
'files' => collect($state['data'])
|
||||
->filter(fn (mixed $entry): bool => is_array($entry) && ($entry['type'] ?? null) === 'file')
|
||||
->count(),
|
||||
'folders' => collect($state['data'])
|
||||
->filter(fn (mixed $entry): bool => is_array($entry) && ($entry['type'] ?? null) === 'folder')
|
||||
->count(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{description: string, version: string, generatedTime: int, data: array<int, array<string, mixed>>} $state
|
||||
*/
|
||||
public function writeToPath(string $path, array $state): void
|
||||
{
|
||||
$directory = dirname($path);
|
||||
|
||||
if (! is_dir($directory) && ! mkdir($directory, 0755, true) && ! is_dir($directory)) {
|
||||
throw new RuntimeException(sprintf('Directory "%s" was not created.', $directory));
|
||||
}
|
||||
|
||||
try {
|
||||
file_put_contents($path, json_encode($state, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR));
|
||||
} catch (JsonException $exception) {
|
||||
throw new RuntimeException("Unable to encode sync-state JSON: {$exception->getMessage()}", previous: $exception);
|
||||
}
|
||||
}
|
||||
|
||||
private function resolveRoot(string $root): string
|
||||
{
|
||||
$realRoot = realpath($root);
|
||||
|
||||
if ($realRoot === false || ! is_dir($realRoot)) {
|
||||
throw new RuntimeException("Local deploy path not found: {$root}");
|
||||
}
|
||||
|
||||
return rtrim(str_replace('\\', '/', $realRoot), '/');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{type: string, name: string, size: int, hash: string}
|
||||
*/
|
||||
private function fileEntry(SplFileInfo $file, string $relativePath): array
|
||||
{
|
||||
$hash = hash_file('sha256', $file->getPathname());
|
||||
|
||||
if ($hash === false) {
|
||||
throw new RuntimeException("Unable to hash file: {$relativePath}");
|
||||
}
|
||||
|
||||
return [
|
||||
'type' => 'file',
|
||||
'name' => $relativePath,
|
||||
'size' => $file->getSize(),
|
||||
'hash' => $hash,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, bool> $folders
|
||||
*/
|
||||
private function rememberParentFolders(array &$folders, string $relativePath): void
|
||||
{
|
||||
$parent = dirname($relativePath);
|
||||
|
||||
while ($parent !== '.' && $parent !== '/' && $parent !== '') {
|
||||
$folders[$parent] = true;
|
||||
$parent = dirname($parent);
|
||||
}
|
||||
}
|
||||
|
||||
private function relativePathIfInsideRoot(string $root, string $path): ?string
|
||||
{
|
||||
$absolutePath = Path::isAbsolute($path) ? str_replace('\\', '/', $path) : str_replace('\\', '/', getcwd().DIRECTORY_SEPARATOR.$path);
|
||||
$absoluteDirectory = realpath(dirname($absolutePath));
|
||||
|
||||
if ($absoluteDirectory === false) {
|
||||
$absoluteDirectory = dirname($absolutePath);
|
||||
}
|
||||
|
||||
$candidate = rtrim(str_replace('\\', '/', $absoluteDirectory), '/').'/'.basename($absolutePath);
|
||||
|
||||
if (! str_starts_with($candidate, "{$root}/") && $candidate !== $root) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return Path::relativeToRoot($root, $candidate);
|
||||
}
|
||||
|
||||
private function currentMillis(): int
|
||||
{
|
||||
return (int) round(microtime(true) * 1000);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace MeghdadFadaee\LaravelFtpDeploy\Support;
|
||||
|
||||
final class Path
|
||||
{
|
||||
public static function normalizeRelative(string $path): string
|
||||
{
|
||||
$path = str_replace('\\', '/', trim($path));
|
||||
$path = preg_replace('#/+#', '/', $path) ?: $path;
|
||||
|
||||
return trim($path, '/');
|
||||
}
|
||||
|
||||
public static function isAbsolute(string $path): bool
|
||||
{
|
||||
return str_starts_with($path, DIRECTORY_SEPARATOR)
|
||||
|| preg_match('/^[A-Za-z]:[\/\\\\]/', $path) === 1;
|
||||
}
|
||||
|
||||
public static function absoluteFromBase(string $path): string
|
||||
{
|
||||
if (self::isAbsolute($path)) {
|
||||
return str_replace('\\', '/', $path);
|
||||
}
|
||||
|
||||
return str_replace('\\', '/', base_path(self::normalizeRelative($path)));
|
||||
}
|
||||
|
||||
public static function relativeToRoot(string $root, string $path): string
|
||||
{
|
||||
return self::normalizeRelative(substr(str_replace('\\', '/', $path), strlen($root)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
|
||||
beforeEach(function (): void {
|
||||
$this->localRoot = storage_path('framework/testing/ftp-deploy-local');
|
||||
$this->statePath = storage_path('framework/testing/ftp-deploy-state.json');
|
||||
|
||||
File::deleteDirectory($this->localRoot);
|
||||
File::ensureDirectoryExists($this->localRoot);
|
||||
File::delete($this->statePath);
|
||||
|
||||
config([
|
||||
'services.ftp_deploy.disk' => 'ftp_deploy',
|
||||
'services.ftp_deploy.local_root' => $this->localRoot,
|
||||
'services.ftp_deploy.state_path' => 'storage/framework/testing/ftp-deploy-state.json',
|
||||
'services.ftp_deploy.api_token' => 'secret-token',
|
||||
'services.ftp_deploy.exclude' => ['ignored', '*.tmp'],
|
||||
]);
|
||||
|
||||
Storage::fake('ftp_deploy');
|
||||
});
|
||||
|
||||
afterEach(function (): void {
|
||||
File::deleteDirectory($this->localRoot);
|
||||
File::delete($this->statePath);
|
||||
});
|
||||
|
||||
test('package registers default config commands and route', function () {
|
||||
expect(config('filesystems.disks.ftp_deploy.driver'))->toBe('ftp')
|
||||
->and(config('services.ftp_deploy.disk'))->toBe('ftp_deploy')
|
||||
->and(Artisan::all())->toHaveKeys([
|
||||
'ftp:deploy',
|
||||
'ftp:generate-sync-state',
|
||||
])
|
||||
->and(Route::has('ftp-deploy.generate-sync-state'))->toBeTrue();
|
||||
});
|
||||
|
||||
test('generate sync state command writes state and honors excludes', function () {
|
||||
ftpDeployWriteLocalFile($this->localRoot, 'keep.txt', 'keep contents');
|
||||
ftpDeployWriteLocalFile($this->localRoot, 'ignored/file.txt', 'ignored contents');
|
||||
ftpDeployWriteLocalFile($this->localRoot, 'nested/cache.tmp', 'ignored contents');
|
||||
|
||||
$outputPath = "{$this->localRoot}/storage/app/.ftp-deploy-sync-state.json";
|
||||
|
||||
$this->artisan('ftp:generate-sync-state', [
|
||||
'path' => $this->localRoot,
|
||||
'--output' => $outputPath,
|
||||
])->assertExitCode(0);
|
||||
|
||||
$state = json_decode(File::get($outputPath), true, flags: JSON_THROW_ON_ERROR);
|
||||
$fileNames = collect($state['data'])
|
||||
->where('type', 'file')
|
||||
->pluck('name')
|
||||
->all();
|
||||
|
||||
expect($fileNames)->toEqualCanonicalizing(['keep.txt']);
|
||||
});
|
||||
|
||||
test('json route requires a configured token', function () {
|
||||
$this->getJson('/ftp/generate-sync-state')
|
||||
->assertForbidden();
|
||||
|
||||
$this->withHeader('Authorization', 'Bearer wrong-token')
|
||||
->getJson('/ftp/generate-sync-state')
|
||||
->assertForbidden();
|
||||
});
|
||||
|
||||
test('json route persists and returns the current sync state with a valid token', function () {
|
||||
ftpDeployWriteLocalFile($this->localRoot, 'keep.txt', 'keep contents');
|
||||
ftpDeployWriteLocalFile($this->localRoot, 'ignored/file.txt', 'ignored contents');
|
||||
|
||||
$response = $this->withHeader('Authorization', 'Bearer secret-token')
|
||||
->getJson('/ftp/generate-sync-state')
|
||||
->assertSuccessful()
|
||||
->assertJsonPath('success', true)
|
||||
->assertJsonPath('files', 1);
|
||||
|
||||
expect(File::exists($this->statePath))->toBeTrue()
|
||||
->and($response->json('state.data.0.name'))->toBe('keep.txt');
|
||||
});
|
||||
|
||||
test('ftp deploy uploads only files missing or changed from the remote sync state', function () {
|
||||
ftpDeployWriteLocalFile($this->localRoot, 'same.txt', 'same contents');
|
||||
ftpDeployWriteLocalFile($this->localRoot, 'changed.txt', 'local changed contents');
|
||||
ftpDeployWriteLocalFile($this->localRoot, 'nested/new.txt', 'new contents');
|
||||
ftpDeployWriteLocalFile($this->localRoot, 'ignored/cache.tmp', 'ignored contents');
|
||||
|
||||
Storage::disk('ftp_deploy')->put('same.txt', 'same contents');
|
||||
Storage::disk('ftp_deploy')->put('changed.txt', 'remote old contents');
|
||||
Storage::disk('ftp_deploy')->put('storage/framework/testing/ftp-deploy-state.json', ftpDeploySyncState([
|
||||
'same.txt' => 'same contents',
|
||||
'changed.txt' => 'remote old contents',
|
||||
]));
|
||||
|
||||
$this->artisan('ftp:deploy', ['--yes' => true])
|
||||
->assertExitCode(0);
|
||||
|
||||
expect(Storage::disk('ftp_deploy')->get('same.txt'))->toBe('same contents')
|
||||
->and(Storage::disk('ftp_deploy')->get('changed.txt'))->toBe('local changed contents')
|
||||
->and(Storage::disk('ftp_deploy')->get('nested/new.txt'))->toBe('new contents')
|
||||
->and(Storage::disk('ftp_deploy')->exists('ignored/cache.tmp'))->toBeFalse();
|
||||
|
||||
$updatedState = json_decode(
|
||||
Storage::disk('ftp_deploy')->get('storage/framework/testing/ftp-deploy-state.json'),
|
||||
true,
|
||||
flags: JSON_THROW_ON_ERROR,
|
||||
);
|
||||
|
||||
$fileNames = collect($updatedState['data'])
|
||||
->where('type', 'file')
|
||||
->pluck('name')
|
||||
->all();
|
||||
|
||||
expect($fileNames)->toEqualCanonicalizing([
|
||||
'changed.txt',
|
||||
'nested/new.txt',
|
||||
'same.txt',
|
||||
]);
|
||||
});
|
||||
|
||||
test('ftp deploy dry run leaves remote files and state untouched', function () {
|
||||
ftpDeployWriteLocalFile($this->localRoot, 'changed.txt', 'local changed contents');
|
||||
|
||||
$remoteState = ftpDeploySyncState([
|
||||
'changed.txt' => 'remote old contents',
|
||||
]);
|
||||
|
||||
Storage::disk('ftp_deploy')->put('changed.txt', 'remote old contents');
|
||||
Storage::disk('ftp_deploy')->put('storage/framework/testing/ftp-deploy-state.json', $remoteState);
|
||||
|
||||
$this->artisan('ftp:deploy', ['--dry-run' => true])
|
||||
->assertExitCode(0);
|
||||
|
||||
expect(Storage::disk('ftp_deploy')->get('changed.txt'))->toBe('remote old contents')
|
||||
->and(Storage::disk('ftp_deploy')->get('storage/framework/testing/ftp-deploy-state.json'))->toBe($remoteState);
|
||||
});
|
||||
|
||||
test('ftp deploy force uploads every included file', function () {
|
||||
ftpDeployWriteLocalFile($this->localRoot, 'same.txt', 'same contents');
|
||||
ftpDeployWriteLocalFile($this->localRoot, 'other.txt', 'other contents');
|
||||
|
||||
Storage::disk('ftp_deploy')->put('same.txt', 'remote contents');
|
||||
Storage::disk('ftp_deploy')->put('other.txt', 'remote contents');
|
||||
Storage::disk('ftp_deploy')->put('storage/framework/testing/ftp-deploy-state.json', ftpDeploySyncState([
|
||||
'same.txt' => 'same contents',
|
||||
'other.txt' => 'other contents',
|
||||
]));
|
||||
|
||||
$this->artisan('ftp:deploy', [
|
||||
'--force' => true,
|
||||
'--yes' => true,
|
||||
])->assertExitCode(0);
|
||||
|
||||
expect(Storage::disk('ftp_deploy')->get('same.txt'))->toBe('same contents')
|
||||
->and(Storage::disk('ftp_deploy')->get('other.txt'))->toBe('other contents');
|
||||
});
|
||||
|
||||
function ftpDeployWriteLocalFile(string $root, string $path, string $contents): void
|
||||
{
|
||||
$fullPath = "{$root}/{$path}";
|
||||
|
||||
File::ensureDirectoryExists(dirname($fullPath));
|
||||
File::put($fullPath, $contents);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, string> $files
|
||||
*/
|
||||
function ftpDeploySyncState(array $files): string
|
||||
{
|
||||
return json_encode([
|
||||
'description' => 'test sync state',
|
||||
'version' => '1.0.0',
|
||||
'generatedTime' => 1,
|
||||
'data' => collect($files)
|
||||
->map(fn (string $contents, string $name): array => [
|
||||
'type' => 'file',
|
||||
'name' => $name,
|
||||
'size' => strlen($contents),
|
||||
'hash' => hash('sha256', $contents),
|
||||
])
|
||||
->values()
|
||||
->all(),
|
||||
], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
<?php
|
||||
|
||||
use MeghdadFadaee\LaravelFtpDeploy\Tests\TestCase;
|
||||
|
||||
pest()->extend(TestCase::class)->in('Feature');
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace MeghdadFadaee\LaravelFtpDeploy\Tests;
|
||||
|
||||
use MeghdadFadaee\LaravelFtpDeploy\LaravelFtpDeployServiceProvider;
|
||||
use Orchestra\Testbench\TestCase as Orchestra;
|
||||
|
||||
abstract class TestCase extends Orchestra
|
||||
{
|
||||
/**
|
||||
* @return array<int, class-string>
|
||||
*/
|
||||
protected function getPackageProviders($app): array
|
||||
{
|
||||
return [
|
||||
LaravelFtpDeployServiceProvider::class,
|
||||
];
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user