#add env management

This commit is contained in:
2025-08-01 16:55:23 +08:00
parent 57a4d7d97e
commit 5c4492d8f8
16 changed files with 5524 additions and 5 deletions

View File

@@ -0,0 +1,265 @@
<?php
namespace App\Console\Commands;
use App\Services\EnvService;
use Illuminate\Console\Command;
class EnvCommand extends Command
{
protected $signature = 'env:manage
{action : 操作类型 (list|environments|apply|save|import|delete)}
{--project= : 项目名称}
{--environment= : 环境名称}
{--content= : 环境文件内容}';
protected $description = '环境文件管理工具';
private EnvService $envManager;
public function __construct(EnvService $envManager)
{
parent::__construct();
$this->envManager = $envManager;
}
public function handle(): int
{
$action = $this->argument('action');
try {
switch ($action) {
case 'list':
return $this->listProjects();
case 'environments':
return $this->listEnvironments();
case 'apply':
return $this->applyEnvironment();
case 'save':
return $this->saveEnvironment();
case 'import':
return $this->importEnvironment();
case 'delete':
return $this->deleteEnvironment();
default:
$this->error("未知操作: {$action}");
$this->showUsage();
return 1;
}
} catch (\Exception $e) {
$this->error("错误: " . $e->getMessage());
return 1;
}
}
/**
* 列出所有项目
*/
private function listProjects(): int
{
$projects = $this->envManager->getProjects();
if (empty($projects)) {
$this->info('没有找到任何项目');
return 0;
}
$this->info('项目列表:');
$this->table(
['项目名称', '路径', '有.env文件', '环境数量'],
array_map(function ($project) {
return [
$project['name'],
$project['path'],
$project['has_env'] ? '是' : '否',
count($project['envs'])
];
}, $projects)
);
return 0;
}
/**
* 列出项目的环境配置
*/
private function listEnvironments(): int
{
$project = $this->option('project');
if (!$project) {
$this->error('请指定项目名称: --project=项目名');
return 1;
}
$environments = $this->envManager->getProjectEnvs($project);
if (empty($environments)) {
$this->info("项目 {$project} 没有环境配置文件");
return 0;
}
$this->info("项目 {$project} 的环境配置:");
$this->table(
['环境名称', '文件大小', '修改时间'],
array_map(function ($env) {
return [
$env['name'],
$this->formatBytes($env['size']),
$env['modified_at']
];
}, $environments)
);
return 0;
}
/**
* 应用环境配置
*/
private function applyEnvironment(): int
{
$project = $this->option('project');
$environment = $this->option('environment');
if (!$project || !$environment) {
$this->error('请指定项目名称和环境名称: --project=项目名 --environment=环境名');
return 1;
}
if ($this->confirm("确定要将 {$environment} 环境应用到项目 {$project} 吗?")) {
$success = $this->envManager->applyEnv($project, $environment);
if ($success) {
$this->info("成功将 {$environment} 环境应用到项目 {$project}");
return 0;
} else {
$this->error("应用环境配置失败");
return 1;
}
}
$this->info('操作已取消');
return 0;
}
/**
* 保存环境配置
*/
private function saveEnvironment(): int
{
$project = $this->option('project');
$environment = $this->option('environment');
$content = $this->option('content');
if (!$project || !$environment) {
$this->error('请指定项目名称和环境名称: --project=项目名 --environment=环境名');
return 1;
}
if (!$content) {
$this->info('请输入环境配置内容 (输入完成后按 Ctrl+D):');
$content = '';
while (($line = fgets(STDIN)) !== false) {
$content .= $line;
}
}
if (empty(trim($content))) {
$this->error('环境配置内容不能为空');
return 1;
}
$success = $this->envManager->saveEnv($project, $environment, $content);
if ($success) {
$this->info("成功保存环境配置 {$project}/{$environment}");
return 0;
} else {
$this->error("保存环境配置失败");
return 1;
}
}
/**
* 从项目导入环境配置
*/
private function importEnvironment(): int
{
$project = $this->option('project');
$environment = $this->option('environment');
if (!$project || !$environment) {
$this->error('请指定项目名称和环境名称: --project=项目名 --environment=环境名');
return 1;
}
$success = $this->envManager->importFromProject($project, $environment);
if ($success) {
$this->info("成功从项目 {$project} 导入环境配置为 {$environment}");
return 0;
} else {
$this->error("导入环境配置失败");
return 1;
}
}
/**
* 删除环境配置
*/
private function deleteEnvironment(): int
{
$project = $this->option('project');
$environment = $this->option('environment');
if (!$project || !$environment) {
$this->error('请指定项目名称和环境名称: --project=项目名 --environment=环境名');
return 1;
}
if ($this->confirm("确定要删除环境配置 {$project}/{$environment} 吗?")) {
$success = $this->envManager->deleteEnv($project, $environment);
if ($success) {
$this->info("成功删除环境配置 {$project}/{$environment}");
return 0;
} else {
$this->error("删除环境配置失败");
return 1;
}
}
$this->info('操作已取消');
return 0;
}
/**
* 显示使用说明
*/
private function showUsage(): void
{
$this->info('使用说明:');
$this->line(' php artisan env:manage list # 列出所有项目');
$this->line(' php artisan env:manage environments --project=项目名 # 列出项目环境');
$this->line(' php artisan env:manage apply --project=项目名 --environment=环境名 # 应用环境');
$this->line(' php artisan env:manage save --project=项目名 --environment=环境名 # 保存环境');
$this->line(' php artisan env:manage import --project=项目名 --environment=环境名 # 导入环境');
$this->line(' php artisan env:manage delete --project=项目名 --environment=环境名 # 删除环境');
}
/**
* 格式化字节大小
*/
private function formatBytes(int $bytes): string
{
$units = ['B', 'KB', 'MB', 'GB'];
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
$bytes /= pow(1024, $pow);
return round($bytes, 2) . ' ' . $units[$pow];
}
}

View File

@@ -0,0 +1,264 @@
<?php
namespace App\Http\Controllers;
use App\Services\EnvService;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
class EnvController extends Controller
{
private EnvService $envManager;
public function __construct(EnvService $envManager)
{
$this->envManager = $envManager;
}
/**
* 显示环境管理页面
*/
public function index()
{
return view('env.index');
}
/**
* 获取所有项目列表
*/
public function getProjects(): JsonResponse
{
try {
$projects = $this->envManager->getProjects();
return response()->json([
'success' => true,
'data' => $projects
]);
} catch (\Exception $e) {
return response()->json([
'success' => false,
'message' => $e->getMessage()
], 500);
}
}
/**
* 获取项目的环境配置列表
*/
public function getEnvs(string $project): JsonResponse
{
try {
$envs = $this->envManager->getProjectEnvs($project);
return response()->json([
'success' => true,
'data' => $envs
]);
} catch (\Exception $e) {
return response()->json([
'success' => false,
'message' => $e->getMessage()
], 500);
}
}
/**
* 获取环境配置文件内容
*/
public function getEnvContent(string $project, string $env): JsonResponse
{
try {
$content = $this->envManager->getEnvContent($project, $env);
return response()->json([
'success' => true,
'data' => [
'content' => $content
]
]);
} catch (\Exception $e) {
return response()->json([
'success' => false,
'message' => $e->getMessage()
], 404);
}
}
/**
* 保存环境配置文件
*/
public function saveEnv(Request $request): JsonResponse
{
try {
$success = $this->envManager->saveEnv(
$request->input('project'),
$request->input('env'),
$request->input('content')
);
if ($success) {
return response()->json([
'success' => true,
'message' => '环境配置保存成功'
]);
} else {
return response()->json([
'success' => false,
'message' => '环境配置保存失败'
], 500);
}
} catch (\Exception $e) {
return response()->json([
'success' => false,
'message' => $e->getMessage()
], 500);
}
}
/**
* 应用环境配置到项目
*/
public function applyEnv(Request $request): JsonResponse
{
try {
$success = $this->envManager->applyEnv(
$request->input('project'),
$request->input('env')
);
if ($success) {
return response()->json([
'success' => true,
'message' => '环境配置应用成功'
]);
} else {
return response()->json([
'success' => false,
'message' => '环境配置应用失败'
], 500);
}
} catch (\Exception $e) {
return response()->json([
'success' => false,
'message' => $e->getMessage()
], 500);
}
}
/**
* 从项目导入环境配置
*/
public function importEnv(Request $request): JsonResponse
{
try {
$success = $this->envManager->importFromProject(
$request->input('project'),
$request->input('env')
);
if ($success) {
return response()->json([
'success' => true,
'message' => '环境配置导入成功'
]);
} else {
return response()->json([
'success' => false,
'message' => '环境配置导入失败'
], 500);
}
} catch (\Exception $e) {
return response()->json([
'success' => false,
'message' => $e->getMessage()
], 500);
}
}
/**
* 删除环境配置
*/
public function deleteEnv(string $project, string $env): JsonResponse
{
try {
$success = $this->envManager->deleteEnv($project, $env);
if ($success) {
return response()->json([
'success' => true,
'message' => '环境配置删除成功'
]);
} else {
return response()->json([
'success' => false,
'message' => '环境配置删除失败'
], 500);
}
} catch (\Exception $e) {
return response()->json([
'success' => false,
'message' => $e->getMessage()
], 500);
}
}
/**
* 获取项目当前.env文件内容
*/
public function getCurrentEnv(string $project): JsonResponse
{
try {
$content = $this->envManager->getCurrentProjectEnv($project);
if ($content === null) {
return response()->json([
'success' => false,
'message' => '项目没有.env文件'
], 404);
}
return response()->json([
'success' => true,
'data' => [
'content' => $content
]
]);
} catch (\Exception $e) {
return response()->json([
'success' => false,
'message' => $e->getMessage()
], 500);
}
}
/**
* 创建新的环境配置文件
*/
public function createEnv(Request $request): JsonResponse
{
try {
$success = $this->envManager->createNewEnv(
$request->input('project'),
$request->input('env_name')
);
if ($success) {
return response()->json([
'success' => true,
'message' => '环境配置文件创建成功'
]);
} else {
return response()->json([
'success' => false,
'message' => '环境配置文件创建失败'
], 500);
}
} catch (\Exception $e) {
return response()->json([
'success' => false,
'message' => $e->getMessage()
], 400);
}
}
}

View File

@@ -0,0 +1,33 @@
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Console\Commands\EnvCommand;
class EnvServiceProvider extends ServiceProvider
{
/**
* 注册服务
*/
public function register(): void
{
// 注册环境管理服务
$this->app->singleton(\App\Services\EnvService::class);
}
/**
* 启动服务
*/
public function boot(): void
{
// 注册Artisan命令
if ($this->app->runningInConsole()) {
$this->commands([
EnvCommand::class,
]);
}
}
}

224
app/Services/EnvService.php Normal file
View File

@@ -0,0 +1,224 @@
<?php
namespace App\Services;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use InvalidArgumentException;
use RuntimeException;
use Carbon\Carbon;
class EnvService
{
private string $projectsPath;
private string $envStoragePath;
public function __construct()
{
$this->projectsPath = '/var/www/Project';
$this->envStoragePath = storage_path('app/env');
// 确保env存储目录存在
if (!File::exists($this->envStoragePath)) {
File::makeDirectory($this->envStoragePath, 0755, true);
}
}
/**
* 获取所有项目列表
*/
public function getProjects(): array
{
if (!File::exists($this->projectsPath)) {
return [];
}
$projects = [];
$directories = File::directories($this->projectsPath);
foreach ($directories as $directory) {
$projectName = basename($directory);
$projects[] = [
'name' => $projectName,
'path' => $directory,
'has_env' => File::exists($directory . '/.env'),
'envs' => $this->getProjectEnvs($projectName)
];
}
return $projects;
}
/**
* 获取指定项目的所有环境配置
*/
public function getProjectEnvs(string $projectName): array
{
$projectEnvPath = $this->envStoragePath . '/' . $projectName;
if (!File::exists($projectEnvPath)) {
return [];
}
$envs = [];
$files = File::files($projectEnvPath);
foreach ($files as $file) {
if ($file->getExtension() === 'env') {
$envName = $file->getFilenameWithoutExtension();
$envs[] = [
'name' => $envName,
'file_path' => $file->getPathname(),
'size' => $file->getSize(),
'modified_at' => Carbon::createFromTimestamp($file->getMTime())->format('Y-m-d H:i:s')
];
}
}
return $envs;
}
/**
* 保存环境配置文件
*/
public function saveEnv(string $projectName, string $env, string $content): bool
{
$projectEnvPath = $this->envStoragePath . '/' . $projectName;
if (!File::exists($projectEnvPath)) {
File::makeDirectory($projectEnvPath, 0755, true);
}
$filePath = $projectEnvPath . '/' . $env . '.env';
return File::put($filePath, $content) !== false;
}
/**
* 获取环境配置文件内容
*/
public function getEnvContent(string $projectName, string $env): string
{
$filePath = $this->envStoragePath . '/' . $projectName . '/' . $env . '.env';
if (!File::exists($filePath)) {
throw new InvalidArgumentException("环境配置文件不存在: {$env}");
}
return File::get($filePath);
}
/**
* 应用环境配置到项目
*/
public function applyEnv(string $projectName, string $env): bool
{
$projectPath = $this->projectsPath . '/' . $projectName;
if (!File::exists($projectPath)) {
throw new InvalidArgumentException("项目不存在: {$projectName}");
}
$envContent = $this->getEnvContent($projectName, $env);
$targetEnvPath = $projectPath . '/.env';
// 备份现有的.env文件
if (File::exists($targetEnvPath)) {
$backupPath = $targetEnvPath . '.backup.' . Carbon::now()->format('Y-m-d-H-i-s');
File::copy($targetEnvPath, $backupPath);
}
return File::put($targetEnvPath, $envContent) !== false;
}
/**
* 删除环境配置文件
*/
public function deleteEnv(string $projectName, string $env): bool
{
$filePath = $this->envStoragePath . '/' . $projectName . '/' . $env . '.env';
if (!File::exists($filePath)) {
return true; // 文件不存在,视为删除成功
}
return File::delete($filePath);
}
/**
* 从项目导入当前.env文件
*/
public function importFromProject(string $projectName, string $env): bool
{
$projectEnvPath = $this->projectsPath . '/' . $projectName . '/.env';
if (!File::exists($projectEnvPath)) {
throw new InvalidArgumentException("项目 {$projectName} 没有.env文件");
}
$content = File::get($projectEnvPath);
return $this->saveEnv($projectName, $env, $content);
}
/**
* 获取项目当前.env文件内容
*/
public function getCurrentProjectEnv(string $projectName): ?string
{
$projectEnvPath = $this->projectsPath . '/' . $projectName . '/.env';
if (!File::exists($projectEnvPath)) {
return null;
}
return File::get($projectEnvPath);
}
/**
* 获取存储路径
*/
public function getStoragePath(): string
{
return $this->envStoragePath;
}
/**
* 获取项目路径
*/
public function getProjectsPath(): string
{
return $this->projectsPath;
}
/**
* 创建新的环境配置文件
*/
public function createNewEnv(string $projectName, string $envName): bool
{
$projectEnvPath = $this->envStoragePath . '/' . $projectName;
if (!File::exists($projectEnvPath)) {
File::makeDirectory($projectEnvPath, 0755, true);
}
$filePath = $projectEnvPath . '/' . $envName . '.env';
// 检查文件是否已存在
if (File::exists($filePath)) {
throw new InvalidArgumentException("环境配置文件已存在: {$envName}");
}
// 创建空的配置文件
$defaultContent = "# {$envName} 环境配置\n# 创建时间: " . Carbon::now()->format('Y-m-d H:i:s') . "\n\n";
return File::put($filePath, $defaultContent) !== false;
}
}