Skip to content

Instantly share code, notes, and snippets.

@justinTM
Last active June 2, 2022 20:58
Show Gist options
  • Save justinTM/b856c285f04fa5bdb5d0fec739c60d9e to your computer and use it in GitHub Desktop.
Save justinTM/b856c285f04fa5bdb5d0fec739c60d9e to your computer and use it in GitHub Desktop.
Format cortextool diff output as Markdown diff code section
#!/bin/bash
# this script will:
# 1. read in file argument 1, $DIFF_FILE_IN
# 2. format text to Markdown diff code section
# 3. write out file argument 2, $DIFF_FILE_OUT
# https://gitlab.com/gitlab-org/gitlab/-/issues/15582
set -e
DIFF_START='```diff\n'
DIFF_HEADER="The following rule changes will be applied upon successful rules sync,\
based on rules files changes in this commit:\n"
DIFF_END='\n```'
DIFF_WRAPPER="${DIFF_HEADER}${DIFF_START}%s${DIFF_END}"
# check input file variable, use $DIFF_FILE_IN from ./gitlab-ci.yml by default
DIFF_FILE_IN="${1:-$DIFF_FILE_IN}"
if [ -z "$DIFF_FILE_IN" ]; then
echo "Error: input variable 1 'DIFF_FILE_IN' is not defined."
exit 1
elif test -f "${DIFF_FILE_IN}"; then
# print diff to pipeline
echo
echo
echo "rules diff below"
cat "${DIFF_FILE_IN}"
echo
echo
else
echo "Error: Input file \"${DIFF_FILE_IN}\" does not exist."
exit 1
fi
# check input variable 2, use $DIFF_FILE_OUT from ./gitlab-ci.yml by default
DIFF_FILE_OUT="${2:-$DIFF_FILE_OUT}"
if [ -z "$DIFF_FILE_OUT" ]; then
echo "Error: input variable 2 'DIFF_FILE_OUT' is not defined."
exit 1
fi
# remove all occurences of unwanted characters from diff text
DIFF_OLD=$(cat -v ${DIFF_FILE_IN}) # read in file with "show-all" characters flag
DIFF_OLD=`echo -e "${DIFF_OLD//'[0m'/}"` # remove all SGR ASCII reset codes '[0m'
DIFF_OLD=`echo -e "${DIFF_OLD//'$'/}"` # remove all newline characters '$'
DIFF_OLD=`echo -e "${DIFF_OLD//'^['/}"` # remove all escape characters '^['
DIFF_OLD=`echo -e "${DIFF_OLD//'+'/}"` # remove all '+'
DIFF_OLD=`echo -e "${DIFF_OLD//'-'/}"` # remove all '-'
# replace sgr color codes with characters, eg. '[32m' with '+'
declare -A MAP_SGR_TO_CHAR=( ['[32m']='+' ['[31m']='-' ['[33m']='~' )
while read -r line; do # loop each line in $diff variable
# check line for each color code
for sgr_code in "${!MAP_SGR_TO_CHAR[@]}"; do
# if found, replace with new character from associative array
if [[ $line == *"$sgr_code"* ]]; then
new_char="${MAP_SGR_TO_CHAR[$sgr_code]}"
printf -v line '%s' "${new_char}${line/sgr_code/}"
fi
done
DIFF_NEW+=`echo -e "$line\n"` # append markdown newline ' '
done <<< "${DIFF_OLD}"
# wrap with markdown diff code section formatting ticks
printf -v DIFF_NEW "${DIFF_WRAPPER}" "${DIFF_NEW}"
echo -e "${DIFF_NEW}" > "${DIFF_FILE_OUT}" # write new diff file
# print diff to pipeline
echo
echo
echo "Markdown-formatted diff below"
cat "${DIFF_FILE_OUT}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment