From 68ae34e33e693025d9aa86deb7a1ac31d3b5daef Mon Sep 17 00:00:00 2001 From: DariusIII Date: Wed, 14 May 2025 10:08:36 +0200 Subject: [PATCH] Add merging changes from .env.example to .env file --- app/Console/Commands/UpdateNNTmux.php | 76 +++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) diff --git a/app/Console/Commands/UpdateNNTmux.php b/app/Console/Commands/UpdateNNTmux.php index 043e78286..9e231b3a4 100644 --- a/app/Console/Commands/UpdateNNTmux.php +++ b/app/Console/Commands/UpdateNNTmux.php @@ -86,6 +86,82 @@ class UpdateNNTmux extends Command ); } + // Merge changes from .env.example into .env + $this->info('Merging changes from .env.example into .env...'); + + try { + // Read both files + $envExampleContent = file_get_contents(base_path('.env.example')); + $envContent = file_get_contents(base_path('.env')); + + if ($envExampleContent === false || $envContent === false) { + throw new \Exception('Could not read .env or .env.example files'); + } + + // Parse files into key-value pairs + $envExampleVars = []; + foreach (preg_split("/\r\n|\n|\r/", $envExampleContent) as $line) { + $line = trim($line); + if (empty($line) || strpos($line, '#') === 0) { + continue; + } + + if (preg_match('/^([^=]+)=(.*)$/', $line, $matches)) { + $key = trim($matches[1]); + $value = $matches[2]; // Keep the original value with potential = signs + $envExampleVars[$key] = $value; + } + } + + $envVars = []; + foreach (preg_split("/\r\n|\n|\r/", $envContent) as $line) { + $line = trim($line); + if (empty($line) || strpos($line, '#') === 0) { + continue; + } + + if (preg_match('/^([^=]+)=(.*)$/', $line, $matches)) { + $key = trim($matches[1]); + $value = $matches[2]; + $envVars[$key] = $value; + } + } + + // Find keys in .env.example that are not in .env + $missingKeys = array_diff_key($envExampleVars, $envVars); + + if (empty($missingKeys)) { + $this->info('No new keys found in .env.example to merge into .env'); + return; + } + + // Add missing keys to .env file + $newEnvContent = $envContent; + if (substr($newEnvContent, -1) !== "\n") { + $newEnvContent .= "\n"; + } + $newEnvContent .= "\n# New settings added from .env.example\n"; + + foreach ($missingKeys as $key => $value) { + $newEnvContent .= "$key=$value\n"; + } + + // Write updated content back to .env + if (file_put_contents(base_path('.env'), $newEnvContent)) { + $this->info('Successfully merged ' . count($missingKeys) . ' new keys from .env.example into .env'); + $this->line('The following keys were added:'); + foreach ($missingKeys as $key => $value) { + $this->line(" $key=$value"); + } + } else { + throw new \Exception('Failed to write changes to .env file'); + } + + } catch (\Exception $e) { + $this->error('Failed to merge changes: ' . $e->getMessage()); + $this->info('There are changes in .env.example that need to be added manually to .env'); + } + if ($maintenance === true) { $this->call('up'); }