@@ -13,13 +13,14 @@ set -euo pipefail
1313
1414# ==============================================================================
1515
16- # Command line prameters
16+ # Command line parameters
1717new_only=${new_only:- false}
1818changes_only=${changes_only:- false}
1919
2020# Set variables
2121TEMPLATE_REPO_DIR=" nhs-notify-repository-template"
2222IGNORE_FILE=" scripts/config/.repository-template-sync-ignore"
23+ MERGE_FILE=" scripts/config/.repository-template-sync-merge"
2324
2425# Check if the template directory exists
2526if [ ! -d " ${TEMPLATE_REPO_DIR} " ]; then
@@ -34,11 +35,21 @@ if [ ! -f "${IGNORE_FILE}" ]; then
3435 echo " # Files and Folders in the template repository to disregard" >> ${IGNORE_FILE}
3536fi
3637
38+ # Check if the .template-merge file exists, create an empty one if not
39+ if [ ! -f " ${MERGE_FILE} " ]; then
40+ echo " # Files and folders to merge when syncing ${TEMPLATE_REPO_DIR} back in to this repository" > ${MERGE_FILE}
41+ fi
42+
3743# Read the .template-ignore file into an array
3844while IFS= read -r line || [ -n " $line " ]; do
3945 IGNORED_PATHS+=(" $line " )
4046done < " $IGNORE_FILE "
4147
48+ # Read the .template-merge file into an array
49+ while IFS= read -r line || [ -n " $line " ]; do
50+ MERGED_PATHS+=(" $line " )
51+ done < " $MERGE_FILE "
52+
4253# Check if a file is ignored.
4354is_ignored () {
4455 local file=${1}
@@ -56,6 +67,17 @@ is_ignored() {
5667 return 1
5768}
5869
70+ is_merge () {
71+ local file=${1}
72+
73+ for merged in " ${MERGED_PATHS[@]} " ; do
74+ if [[ -n " $merged " && " $file " =~ $merged ]]; then
75+ return 0
76+ fi
77+ done
78+ return 1
79+ }
80+
5981# Navigate to the template directory
6082cd " ${TEMPLATE_REPO_DIR} " || exit
6183FILES_ADDED=()
@@ -84,9 +106,24 @@ while IFS= read -r -d '' file; do
84106 # If the file exists, check if it's different
85107 if [ " $new_only " == false ]; then
86108 if ! diff -q " $file " " $target_path " > /dev/null 2>&1 ; then
87- echo " Merging changes from $relative_path "
88- FILES_WITH_CHANGES+=(" ${relative_path} " )
89- cp " $file " " $target_path "
109+ if is_merge " $relative_path " ; then
110+ echo " Merging changes from $relative_path "
111+ cp " $target_path " " ${target_path} .bak"
112+ if git merge-file " $target_path " /dev/null " $file " --union; then
113+ if ! cmp -s " $target_path " " ${target_path} .bak" ; then
114+ FILES_WITH_CHANGES+=(" ${relative_path} " )
115+ fi
116+ else
117+ echo " Merge failed for $relative_path , rolling back."
118+ mv " ${target_path} .bak" " $target_path "
119+ diff3 " $target_path " /dev/null " $file "
120+ fi
121+ rm -f " ${target_path} .bak"
122+ else
123+ echo " Copying changes from $relative_path "
124+ cp " $file " " $target_path "
125+ FILES_WITH_CHANGES+=(" ${relative_path} " )
126+ fi
90127 fi
91128 fi
92129 fi
0 commit comments