summaryrefslogtreecommitdiff
path: root/tools/makehelp.sh
blob: e6118de7c7217e99defb288b38131fe3ffe5bf19 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
#!/bin/sh
set -eu

. tools/lib.sh


usage() {
	cat <<-'EOF'
		Usage:
		  makehelp.sh < MAKEFILE
		  makehelp.sh -h
	EOF
}

help() {
	cat <<-'EOF'


		Options:
		  -h, --help    show this message


		Generate a help message from the given Makefile.

		Any target or variable commented with two "#" characters gets
		picked up.  Multi-line comments are supported:

		  VAR1 = 1
		  # a comment
		  VAR2 = 2
		  ## another comment -> this one is included in the docs
		  VAR3 = 3

		  ## with a big
		  ## comment, which is also included
		  a-target:


		Examples:

		  Generate help messages from "Makefile":

		    $ aux/makehelp.sh < Makefile


		  Generate help messages for all targets:

		    $ cat Makefile dev.mk | aux/makehelp.sh
	EOF
}


for flag in "$@"; do
	case "$flag" in
		(--)
			break
			;;
		(--help)
			usage
			help
			exit
			;;
		(*)
			;;
	esac
done

while getopts 'h' flag; do
	case "$flag" in
		(h)
			usage
			help
			exit
			;;
		(*)
			usage >&2
			exit 2
			;;
	esac
done
shift $((OPTIND - 1))


TARGETS="$(mkstemp)"
VARIABLES="$(mkstemp)"
trap 'rm -f "$TARGETS" "$VARIABLES"' EXIT

awk -vCOLUMN=15 -vTARGETS="$TARGETS" -vVARIABLES="$VARIABLES" '
function indent(n, where) {
	for (INDENT = 0; INDENT < n; INDENT++) {
		printf " " > where
	}
}

/^## / { doc[len++] = substr($0, 4) }

/^[-_a-zA-Z]+:/ && len {
	printf "\033[36m%s\033[0m", substr($1, 1, length($1) - 1) > TARGETS
	for (i = 0; i < len; i++) {
		n = COLUMN - (i == 0 ? length($1) - 1 : 0)
		indent(n, TARGETS)
		printf "%s\n", doc[i] > TARGETS
	}
	len = 0
}

/^.++=/ && len {
	printf "\033[36m%s\033[0m", $1 > VARIABLES
	for (i = 0; i < len; i++) {
		n = COLUMN - (i == 0 ? length($1) : 0)
		indent(n, VARIABLES)
		printf "%s\n", doc[i] > VARIABLES
	}
	len = 0
}'



indent() {
	sed 's|^|  |'
}

cat <<-EOF
	Usage:

	  make [VARIABLE=value...] [target...]


	Targets:

	$(indent < "$TARGETS")


	Variables:

	$(indent < "$VARIABLES")


	Examples:

	  Build "all", the default target:

	    $ make


	  Test and install, with \$(DESTDIR) set to "tmp/":

	    $ make DESTDIR=tmp check install
EOF