Skip to content

Instantly share code, notes, and snippets.

@akien-mga
Last active March 4, 2026 13:51
Show Gist options
  • Select an option

  • Save akien-mga/c8138a5bb6154d692d475c5f14d025cf to your computer and use it in GitHub Desktop.

Select an option

Save akien-mga/c8138a5bb6154d692d475c5f14d025cf to your computer and use it in GitHub Desktop.
Add explicit include for a pattern
#!/bin/bash
# Tested on Fedora 43, assumes bash, GNU sed, GNU grep and rigrep available.
if [ -z "$1" -o -z "$2" ]; then
echo "Usage: $0 <pattern> <include> [<ext>]"
exit
fi
pattern="$1"
include="$2"
ext="${3:-cpp}"
rg -g"*.$ext" "$pattern" -l > /tmp/cpp-matches-pattern.txt
for file in $(cat /tmp/cpp-matches-pattern.txt); do
if [[ "$file" == "${include/h/$ext}" ]]; then continue; fi
header=${file/$ext/h}
has_header=false
if [[ "$ext" != "h" && -e $header ]]; then
has_header=true
fi
found_in_cpp=false
found_in_header=false
if grep -qE "(#include|#import) \"$include\"" $file; then
found_in_cpp=true
fi
if $has_header && grep -qE "(#include|#import) \"$include\"" $header; then
found_in_header=true
fi
if [[ $found_in_cpp == false && $found_in_header == false ]]; then
echo "### ADDING MISSING EXPLICIT INCLUDE IN $file ###"
# Look for optimal location to insert the header in the right "block".
if grep -q "#include \"core/" $file; then
echo "> Adding after existing 'core/' include."
sed -i $file -e "0,/#include \"core\//{
/#include \"core\//a\
#include \"$include\"
}"
elif $has_header; then
echo "> Adding after associated header."
header_basename=$(basename $header)
target_line=$header_basename
compat_basename=$(basename $header .h).compat.inc
if grep -q "$compat_basename" $file; then
target_line=$compat_basename
fi
sed -i $file -e "/\"$target_line\"/{
n
a\
#include \"$include\"
}"
elif grep -q "#include " $file; then
echo "> Adding after first include."
# No "main" header, insert after first include.
sed -i $file -e "0,/#include /{
/#include /a\
#include \"$include\"
}"
else # Just include after copyright header, fix manually.
echo "> Adding after copyright header."
sed -i $file -e "32a #include \"$include\""
fi
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment