Skip to content

Instantly share code, notes, and snippets.

@dzogrim
Last active November 20, 2024 19:28
Show Gist options
  • Save dzogrim/cf6d44b41b08f059d08ccfcfbaef5cdf to your computer and use it in GitHub Desktop.
Save dzogrim/cf6d44b41b08f059d08ccfcfbaef5cdf to your computer and use it in GitHub Desktop.
Ensures a specific line stays uncommented in a finalizeSystems block in default.nix
#!/usr/bin/env bash
# This script processes a default.nix file to ensure a specific configuration
# line provided as an argument remains uncommented within a block starting with
# `finalizeSystems [` and ending with `]`, while commenting out other lines
# in the block, and keeps a backup of the original file.
# VERSION=2024-11-20
# Check for the argument
if [ $# -ne 1 ]; then
echo "Usage: $0 <path-to-config-to-keep-uncommented>"
exit 1
fi
TARGET_FILE="default.nix"
TARGET_LINE="$1"
# Ensure the file in the argument exists
if [ ! -f "$TARGET_LINE" ]; then
echo "Error: File '$TARGET_LINE' does not exist. Are you in the right repository?"
exit 1
fi
# Backup the original file
cp "$TARGET_FILE" "$TARGET_FILE.bak"
# Process the file
awk -v target="$TARGET_LINE" '
/^[ \t]*finalizeSystems[ \t]*\[/ {
in_block = 1;
print;
next
}
/^[ \t]*\]/ && in_block {
in_block = 0;
if (!line_found) {
print " " target; # Add the target line if not found
}
print;
next
}
in_block {
if ($0 ~ target) {
line_found = 1;
print $0; # Keep the target line uncommented
} else if (/^[ \t]*#/) {
print; # Keep already commented lines
} else {
print "#" $0; # Comment all other lines
}
next
}
{ print } # Print lines outside the block unchanged
' "$TARGET_FILE.bak" > "$TARGET_FILE"
echo "Processed. Original file backed up as $TARGET_FILE.bak"
echo "You may proceed to the next step: 'build'."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment