Skip to content

Instantly share code, notes, and snippets.

@chx
Last active September 30, 2024 01:05
Show Gist options
  • Save chx/883175e72180421681322d3c7a3e62e7 to your computer and use it in GitHub Desktop.
Save chx/883175e72180421681322d3c7a3e62e7 to your computer and use it in GitHub Desktop.
Keep comments on the top of Drupal config export files
diff --git a/core/lib/Drupal/Core/Config/FileStorage.php b/core/lib/Drupal/Core/Config/FileStorage.php
index fe202a3e0e..b0c27a32bb 100644
--- a/core/lib/Drupal/Core/Config/FileStorage.php
+++ b/core/lib/Drupal/Core/Config/FileStorage.php
@@ -147,7 +147,8 @@ public function write($name, array $data) {
}
$target = $this->getFilePath($name);
- $status = @file_put_contents($target, $encoded_data);
+ $prefix = @file_get_contents('/tmp/cexprepend' . substr($target, strlen($this->directory)));
+ $status = @file_put_contents($target, $prefix . $encoded_data);
if ($status === FALSE) {
// Try to make sure the directory exists and try writing again.
$this->ensureStorage();
diff --git a/drush/Commands/pre_config_export/PreConfigExportHook.php b/drush/Commands/pre_config_export/PreConfigExportHook.php
new file mode 100644
index 0000000000..c740b9db6a
--- /dev/null
+++ b/drush/Commands/pre_config_export/PreConfigExportHook.php
@@ -0,0 +1,21 @@
+<?php
+
+namespace Drush\Commands\pre_config_export;
+
+use Drupal\Core\Site\Settings;
+use Drush\Commands\DrushCommands;
+
+/**
+ * Pre config export hook file.
+ */
+class PreConfigExportHook extends DrushCommands {
+
+ /**
+ * @hook pre-command-event config:export
+ */
+ public function onPreConfigExport() {
+ $directory = realpath(Settings::get('config_sync_directory'));
+ system(sprintf('../scripts/pre_config_export.sh "%s"', $directory));
+ }
+
+}
diff --git a/scripts/pre_config_export.sh b/scripts/pre_config_export.sh
new file mode 100755
index 0000000000..c51de1ea11
--- /dev/null
+++ b/scripts/pre_config_export.sh
@@ -0,0 +1,6 @@
+#!/bin/sh
+rm -rf /tmp/cexprepend
+mkdir /tmp/cexprepend
+cd "$1"
+find . -type d -exec mkdir -p /tmp/cexprepend/{} \;
+find . -type f -exec awk 'FNR==1 { close(out); out = "/tmp/cexprepend/" FILENAME; } /^#/ { print >out }' {} +
@chx
Copy link
Author

chx commented Sep 29, 2024

The idea is to grab the comments from the current config export using the awk script from https://stackoverflow.com/a/79034808/308851 and then put those back during config export. (This works with busybox, doesn't require any GNU tools.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment