From cd9cc0dabfc533dd06e173b2f89bbb5ba46e7f98 Mon Sep 17 00:00:00 2001 From: Meghdad <61308304+MeghdadFadaee@users.noreply.github.com> Date: Thu, 25 Jun 2026 14:40:00 +0330 Subject: [PATCH] init --- .gitignore | 7 + LICENSE.md | 21 ++ README.md | 110 +++++++++ composer.json | 62 +++++ config/filesystems.php | 19 ++ config/services.php | 20 ++ phpunit.xml | 21 ++ pint.json | 3 + routes/api.php | 13 + .../Commands/DeployFtpChangedFilesCommand.php | 200 +++++++++++++++ .../Commands/GenerateFtpSyncStateCommand.php | 88 +++++++ .../GenerateSyncStateController.php | 36 +++ .../Middleware/EnsureValidFtpDeployToken.php | 38 +++ src/LaravelFtpDeployServiceProvider.php | 42 ++++ src/Services/ExcludeMatcher.php | 44 ++++ src/Services/FtpDeployManager.php | 227 ++++++++++++++++++ src/Services/SyncStateGenerator.php | 196 +++++++++++++++ src/Support/Path.php | 34 +++ tests/Feature/LaravelFtpDeployTest.php | 189 +++++++++++++++ tests/Pest.php | 5 + tests/TestCase.php | 19 ++ 21 files changed, 1394 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE.md create mode 100644 README.md create mode 100644 composer.json create mode 100644 config/filesystems.php create mode 100644 config/services.php create mode 100644 phpunit.xml create mode 100644 pint.json create mode 100644 routes/api.php create mode 100644 src/Console/Commands/DeployFtpChangedFilesCommand.php create mode 100644 src/Console/Commands/GenerateFtpSyncStateCommand.php create mode 100644 src/Http/Controllers/GenerateSyncStateController.php create mode 100644 src/Http/Middleware/EnsureValidFtpDeployToken.php create mode 100644 src/LaravelFtpDeployServiceProvider.php create mode 100644 src/Services/ExcludeMatcher.php create mode 100644 src/Services/FtpDeployManager.php create mode 100644 src/Services/SyncStateGenerator.php create mode 100644 src/Support/Path.php create mode 100644 tests/Feature/LaravelFtpDeployTest.php create mode 100644 tests/Pest.php create mode 100644 tests/TestCase.php diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1bae394 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +/vendor +/composer.lock +/.phpunit.cache +/.pest.cache +/.idea +/.vscode +/.DS_Store diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..59f8ffb --- /dev/null +++ b/LICENSE.md @@ -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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..20fd8f4 --- /dev/null +++ b/README.md @@ -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. diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..ea3458a --- /dev/null +++ b/composer.json @@ -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 +} diff --git a/config/filesystems.php b/config/filesystems.php new file mode 100644 index 0000000..d445d2a --- /dev/null +++ b/config/filesystems.php @@ -0,0 +1,19 @@ + [ + '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, + ], + ], +]; diff --git a/config/services.php b/config/services.php new file mode 100644 index 0000000..2b23617 --- /dev/null +++ b/config/services.php @@ -0,0 +1,20 @@ + [ + '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', + )))), + ], +]; diff --git a/phpunit.xml b/phpunit.xml new file mode 100644 index 0000000..2b3b88d --- /dev/null +++ b/phpunit.xml @@ -0,0 +1,21 @@ + + + + + tests/Feature + + + + + src + + + + + + + diff --git a/pint.json b/pint.json new file mode 100644 index 0000000..93061b6 --- /dev/null +++ b/pint.json @@ -0,0 +1,3 @@ +{ + "preset": "laravel" +} diff --git a/routes/api.php b/routes/api.php new file mode 100644 index 0000000..58caed3 --- /dev/null +++ b/routes/api.php @@ -0,0 +1,13 @@ +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')); diff --git a/src/Console/Commands/DeployFtpChangedFilesCommand.php b/src/Console/Commands/DeployFtpChangedFilesCommand.php new file mode 100644 index 0000000..5017e30 --- /dev/null +++ b/src/Console/Commands/DeployFtpChangedFilesCommand.php @@ -0,0 +1,200 @@ +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>} $currentState + * @param array> $changedFiles + * @param array $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>} $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> $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> $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; + } +} diff --git a/src/Console/Commands/GenerateFtpSyncStateCommand.php b/src/Console/Commands/GenerateFtpSyncStateCommand.php new file mode 100644 index 0000000..aa5ad64 --- /dev/null +++ b/src/Console/Commands/GenerateFtpSyncStateCommand.php @@ -0,0 +1,88 @@ +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"; + } +} diff --git a/src/Http/Controllers/GenerateSyncStateController.php b/src/Http/Controllers/GenerateSyncStateController.php new file mode 100644 index 0000000..904dec2 --- /dev/null +++ b/src/Http/Controllers/GenerateSyncStateController.php @@ -0,0 +1,36 @@ +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, + ]); + } +} diff --git a/src/Http/Middleware/EnsureValidFtpDeployToken.php b/src/Http/Middleware/EnsureValidFtpDeployToken.php new file mode 100644 index 0000000..8da0a44 --- /dev/null +++ b/src/Http/Middleware/EnsureValidFtpDeployToken.php @@ -0,0 +1,38 @@ +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); + } +} diff --git a/src/LaravelFtpDeployServiceProvider.php b/src/LaravelFtpDeployServiceProvider.php new file mode 100644 index 0000000..dc5f9b6 --- /dev/null +++ b/src/LaravelFtpDeployServiceProvider.php @@ -0,0 +1,42 @@ +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'); + } + } +} diff --git a/src/Services/ExcludeMatcher.php b/src/Services/ExcludeMatcher.php new file mode 100644 index 0000000..fb6346b --- /dev/null +++ b/src/Services/ExcludeMatcher.php @@ -0,0 +1,44 @@ + + */ + 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 $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; + } +} diff --git a/src/Services/FtpDeployManager.php b/src/Services/FtpDeployManager.php new file mode 100644 index 0000000..1cef086 --- /dev/null +++ b/src/Services/FtpDeployManager.php @@ -0,0 +1,227 @@ + + */ + 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 $excludedPatterns + * @return array{description: string, version: string, generatedTime: int, data: array>} + */ + 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>}|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>} + */ + public function emptySyncState(): array + { + return [ + 'description' => SyncStateGenerator::DESCRIPTION, + 'version' => '1.0.0', + 'generatedTime' => 0, + 'data' => [], + ]; + } + + /** + * @param array{data: array>} $currentState + * @param array{data: array>} $remoteState + * @return array + */ + 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>} $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>} + */ + 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'], + ]; + } +} diff --git a/src/Services/SyncStateGenerator.php b/src/Services/SyncStateGenerator.php new file mode 100644 index 0000000..fb0ac77 --- /dev/null +++ b/src/Services/SyncStateGenerator.php @@ -0,0 +1,196 @@ + $excludedPatterns + * @return array{description: string, version: string, generatedTime: int, data: array>} + */ + 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>} $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>} $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 $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); + } +} diff --git a/src/Support/Path.php b/src/Support/Path.php new file mode 100644 index 0000000..39398bb --- /dev/null +++ b/src/Support/Path.php @@ -0,0 +1,34 @@ +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 $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); +} diff --git a/tests/Pest.php b/tests/Pest.php new file mode 100644 index 0000000..dc22c1b --- /dev/null +++ b/tests/Pest.php @@ -0,0 +1,5 @@ +extend(TestCase::class)->in('Feature'); diff --git a/tests/TestCase.php b/tests/TestCase.php new file mode 100644 index 0000000..d802fea --- /dev/null +++ b/tests/TestCase.php @@ -0,0 +1,19 @@ + + */ + protected function getPackageProviders($app): array + { + return [ + LaravelFtpDeployServiceProvider::class, + ]; + } +}