Skip to content

Instantly share code, notes, and snippets.

@rndD
Created February 21, 2024 11:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rndD/00ccb20285d1e15c901a25cec6e34b4b to your computer and use it in GitHub Desktop.
Save rndD/00ccb20285d1e15c901a25cec6e34b4b to your computer and use it in GitHub Desktop.
makefile help
#!/bin/bash
# This script displays help information for the Makefile.
# Usage: ./makefile-help.sh Makefile
# Based on https://medium.com/@vildmedpap/make-your-makefile-user-friendly-create-a-custom-make-help-target-88c9ef130879
# Set colors for output
color_off='\033[0m'
example_color='\033[32m'
target_color='\033[36m'
variable_color='\033[93m'
grey='\033[90m'
# https://stackoverflow.com/a/35663407
# two_columns $tabstop $title_color $title $description [$default_color $default]
function two_columns() {
tabstop=$1
cols=$(tput cols)
firstline=0
while read -r line; do
if [[ "${firstline}" -eq 0 ]]; then
header="$3"
firstline=1
else
header=" "
fi
printf " %b%-${tabstop-5}s%b%s\n" "$2" "${header}" "$color_off" "${line}"
done <<< "$(fold -w$((cols-$tabstop-2)) -s <<< $4)"
if [ $5 ]; then
printf "%*c %b( default: %b)%b\n" "$tabstop" " " "$5" "$6" "$color_off"
fi
}
# Main function to display help information
help() {
# Display usage information
echo "Usage:"
printf " make %b[target]%b %b[variables]%b\n\n" "$target_color" "$color_off" "$variable_color" "$color_off"
# Display targets information
_help_targets "$1"
# Display variables information
_help_variables "$1"
# Display examples
_help_examples "$1"
}
# Function to display targets information
_help_targets() {
local pattern
pattern='^[a-zA-Z0-9_-]+:\s.*?##.*$'
echo "Target(s):"
grep -E "$pattern" "$1" | sort | while read -r line; do
target=${line%%:*}
description=${line#*## }
two_columns 25 "$target_color" "$target" "$description"
done
echo ""
}
# Function to display variables information
_help_variables() {
local pattern
pattern='^[a-zA-Z0-9_-]+\s*[:?!+]?=.*?##.*$'
echo "Variable(s):"
grep -E "$pattern" "$1" | while read -r line; do
variable=${line%% *}
default=${line#*= }
default=${default%%##*}
description=${line##*## }
two_columns 25 "$variable_color" "$variable" "$description" "$grey" "$default"
done
echo ""
}
# Function to display examples
_help_examples() {
local pattern
pattern='^.EXAMPLE\s*:=?\s*(.+)\s*##.*$'
echo "Example(s):"
grep -E "$pattern" "$1" | while read -r line; do
example_cmd="$(printf "%s" "$line" | sed -E "s/${pattern}/\1/")"
description=${line#*## }
printf " %b%s%b\n" "$example_color" "$example_cmd" "$color_off"
two_columns 2 "$color_off" "" "$description"
done
}
# Call main function
help "$1"
# Return exit code indicating success
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment