Skip to content

Instantly share code, notes, and snippets.

@moshe-foreflight
Created March 15, 2024 21:51
Show Gist options
  • Save moshe-foreflight/e088530aba9d60a8f6f2a09bb4bbce6b to your computer and use it in GitHub Desktop.
Save moshe-foreflight/e088530aba9d60a8f6f2a09bb4bbce6b to your computer and use it in GitHub Desktop.
Build a compilation database from Xcodebuild.
#!/usr/bin/env bash
scheme=""
root=""
cd "${HOME}/${root}" || exit;
if [ -z "$1" ] || [ "$1" == "clean" ];
then
rm -rf /tmp/cdb # could use some other path, or uniquify the folder name, but this is easy
xcodebuild clean build -configuration Debug -scheme "$scheme" \
"OTHER_CFLAGS = \$(inherited) -gen-cdb-fragment-path /tmp/cdb" \
GCC_PRECOMPILE_PREFIX_HEADER=YES \
CLANG_ENABLE_MODULE_DEBUGGING=YES \
COMPILER_INDEX_STORE_ENABLE=NO \
RUN_CLANG_STATIC_ANALYZER=NO \
ONLY_ACTIVE_ARCH=YES \
|| echo "Failed to generate cdb." && exit;
else
echo "Using cached fragments."
fi
# If there's an arg and that arg is "clean" then pop it.
# shellcheck disable=SC2015
[ -n "$1" ] && [ "$1" != "clean" ] || shift "$1"
if [ -z "$1" ] || [ "$1" == "cat" ];
then
echo "Processing fragments..."
tmp=$(mktemp)
cat /tmp/cdb/*.json > "$tmp" || exit
sed -i '' -e '1s/^/[/' "$tmp" # insert a bracket at the beginning
sed -i '' -e '$ s/,$/\]/' "$tmp" # remove the last comma and insert a closing bracket
# Filter arguments so we can use directly with either `clang-tidy` or `clang-query`.
jq 'del(.[].arguments[] |
select(
. == ("-o", "-ivfsstatcache", "-fno-odr-hash-protocols", "-Xclang", "-mllvm", "-gmodules") ,
startswith("-clang-vendor-feature=", "--target", "-W", "-mlinker-version", "-disable-aligned-alloc-awareness") ,
endswith("sdkstatcache", ".o", "/usr/bin/clang")
))' < "$tmp" | uniq > compile_commands.json
rm "$tmp"
echo "Done."
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment