Add merging changes from .env.example to .env file

This commit is contained in:
DariusIII
2025-05-14 10:08:36 +02:00
parent 1dd0ac9e7a
commit 68ae34e33e
+76
View File
@@ -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');
}