Skip to content

Instantly share code, notes, and snippets.

@kykyi
Last active July 26, 2023 08:55
Show Gist options
  • Save kykyi/6facaf791b664f6a4c671aa871d324a9 to your computer and use it in GitHub Desktop.
Save kykyi/6facaf791b664f6a4c671aa871d324a9 to your computer and use it in GitHub Desktop.
Print all commands available in a Makefile
#!/bin/bash
# inspired by https://github.com/ctran/annotate_models
# Check if argument is provided
if [[ -z "$1" ]]; then
echo "Please provide the path to a Makefile."
exit 1
fi
makefilePath=$1
makefileDir=$(dirname "$makefilePath")
makefileBaseName=$(basename "$makefilePath")
# Change to the directory of the Makefile
cd "$makefileDir" || exit
# Run 'make help', remove color codes and save output
output=$(make help | sed 's/\x1b\[[0-9;]*m//g')
# Create a temporary file
tempFile=$(mktemp)
# Append the output of 'make help' to the top of the temporary file
# Here, we are handling multiline output correctly
echo "# The following commands are available in this Makefile" >> "$tempFile"
echo "# Note: commands must have a ## comment to be visible!" >> "$tempFile"
echo "#" >> "$tempFile"
echo "$output" | while IFS= read -r line
do
echo "# $line"
done >> "$tempFile"
echo "#" >> "$tempFile"
# Delete all lines starting with '#' from the original Makefile
sed -i '' '/^#/d' "$makefileBaseName"
# Append the contents of the original Makefile to the temporary file
cat "$makefileBaseName" >> "$tempFile"
# Replace the original Makefile with the new, annotated one
mv "$tempFile" "$makefileBaseName"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment