Last active
July 16, 2023 13:38
-
-
Save slarwise/3c9b75d6b9d646e112c0258ab5029244 to your computer and use it in GitHub Desktop.
Compare two directories containing yaml files, e.g. two kubernetes environments for an app
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Compare two directories containing yaml files recursively | |
# Dependencies: | |
# 1. [delta](https://github.com/dandavison/delta) | |
# Inputs: | |
# $1: First directory | |
# $2: Second directory | |
TMP_DIR=$(mktemp -d) | |
trap 'rm -rf "$TMP_DIR"' EXIT | |
# Output differences | |
PAIRS=$(diff -qr $1 $2 | grep '^Files' \ | |
| cut -f2,4 -d ' ' \ | |
| tr "\t" " ") | |
echo "$PAIRS" | while read line; do | |
FIRST_FILE="$(echo "$line" | cut -f1 -d ' ')" | |
SECOND_FILE="$(echo "$line" | cut -f2 -d ' ')" | |
# Sort keys and store them as temporary files | |
# The only reason to store them as temporary files is to get a useful file | |
# name header when diffing with delta. | |
FIRST_TMP_FILE="$TMP_DIR"/"$FIRST_FILE" | |
SECOND_TMP_FILE="$TMP_DIR"/"$SECOND_FILE" | |
mkdir -p "$(dirname $FIRST_TMP_FILE)" | |
mkdir -p "$(dirname $SECOND_TMP_FILE)" | |
yq --prettyPrint 'sort_keys(..)' "$FIRST_FILE" > "$FIRST_TMP_FILE" | |
yq --prettyPrint 'sort_keys(..)' "$SECOND_FILE" > "$SECOND_TMP_FILE" | |
# This is hacky, I couldn't get "s,$TMP_DIR,," to work, for some reason it | |
# did nothing. | |
TMP_DIRNAME_LEN=${#TMP_DIR} | |
STRIP_TMP_DIR_PATTERN="s/.{$TMP_DIRNAME_LEN}//" | |
delta \ | |
--file-transformation "$STRIP_TMP_DIR_PATTERN" \ | |
"$FIRST_TMP_FILE" "$SECOND_TMP_FILE" | |
done | |
echo | |
# Output files that are missing in one directory | |
diff -qr $1 $2 | grep '^Only in' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A simple version is just to do
What this script adds is sorting the keys so that the order doesn't matter, prettyprinting so indentation style doesn't matter, and using delta for a nicer output.