summaryrefslogtreecommitdiffstats
path: root/git-buildmsg/git-buildmsg.in
blob: 4ba0b703f8b300dd1188bfba83b36d5cb2c42844 (plain)
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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
#!/bin/sh
# Generate some basic info on source code version to be included in program.
#
# Copyright (c) 2006-2007 Luc Verhaegen <libv@skynet.be>
# Copyright (C) 2007 Hans Ulrich Niedermann <hun@n-dimensional.de>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
# THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
# The author thanks the nice people on #git for the assistance!
#
# Simple testing of this script:
#   env SED="/sbin/busybox sed" \
#   /sbin/busybox sh git-buildmsg --example > moo.c \
#     && gcc -Wall -Wextra -Wno-unused -o moo moo.c \
#     && ./moo
#   (bash and other seds should also do)
#
# Note:
#   A man page for this script does NOT make sense. It is supposed to be
#   copied into and shipped with other peoples' source trees.
#
# Ideas:
#  * Output for languages other than C (Erlang, Python, Perl, sh, ...)
#  * Recognize difference between being built from "non-git" sources and
#    a dist tarball generated from git rev XYZ.

# The caller may have found these programs for us
SED="${SED-sed}"

# Initialize
GIT_DIR=".git"
working_dir="$(pwd)"

# Who am I?
self="$(basename "$0")"

# Default settings
ifndef_symbol="GIT_BUILDMSG_H"
outfile="-"
print_example=false
srcdir="$(pwd)"
error_if_no_git=false

# Help messages
USAGE="[<option>...]"
LONG_USAGE="\
  -h --help             Print this help message.
  -V --version          Print version number.

  -x --example          Print complete example program.
  -o --output FILENAME  Set output file name.
  -s --srcdir DIRNAME   Set source tree dir name.

  -e --error-if-no-git  Abort with exitcode!=0 if git worktree not found."

# Parse command line parameter, affecting defaults
while [ "x$1" != "x" ]
do
    case "$1" in
        -x|--example)
            print_example=:
            ;;
        -o|--output)
            if shift; then
                outfile="$1"
                [ "x$outfile" = "x-" ] || \
                    ifndef_symbol=`basename "$outfile" | $SED 's|\.|_|g; s|[^A-Za-z0-9_]||g' | tr a-z A-Z`
            else
                echo "$self: Fatal: \"$1\" option requires parameter." >&2
                exit 1
            fi
            ;;
        -V|--version)
	    echo "$self (@PACKAGE_NAME@) @PACKAGE_VERSION@"
	    exit
	    ;;
        -h|--help)
            echo "Usage: ${self} $USAGE"
	    [ -n "$LONG_USAGE" ] && echo "$LONG_USAGE"
            exit
            ;;
	-s|--srcdir)
	    if shift; then
		srcdir="$1"
		[ -d "$srcdir" ] || {
		    echo "$self: Fatal: \"$1\" not a directory." >&2
		    exit 1
		}
	    else
		echo "$self: Fatal: \"$1\" option requires directory parameter."
		exit 1
	    fi
	    ;;
	-e|--error-if-no-git)
	    error_if_no_git=:
	    ;;
        *)
            echo "$self: Fatal: Invalid command line paramenter: \"$1\"" >&2
            exit 1
            ;;
    esac
    shift
done

# If not printing to stdout, redirect stdout to output file
outfile_exists=false
rename_new_output=false
if [ "x$outfile" = "x-" ]
then
    : # keep using stdout
else
    if [ -e "$outfile" ]; then
	outfile_exists=:
    fi
    exec 1> "${outfile}.new"
fi

# Done with creating output files, so we can change to source dir
cd "$srcdir"

# Detect git tools (should work with old and new git versions)
git_found=yes
for git_tool in git-symbolic-ref git-rev-parse git-diff-files git-diff-index
do
    [ x`which $git_tool 2>/dev/null` = "x" ] && { git_found=no; break; }
done

# Determine data about git tree
is_git_worktree=no
if [ "x$git_found" = "xyes" ]; then
    if [ -e "$GIT_DIR/index" ]; then
	is_git_worktree="yes"

        # Commit ID
        git_commitid=`git-rev-parse HEAD | $SED -n 's/^\(.\{8\}\).*/\1/p'` || \
	    { echo "Error running git-rev-parse HEAD" >&2; exit 1; }

        # Branch
        git_branch=`git-symbolic-ref HEAD | $SED -n 's|^refs/heads/||p'` || \
	    { echo "Error running git-symbolic-ref HEAD" >&2; exit 1; }

        # Any uncommitted changes we should know about?
        # Or technically: Are the working tree or index dirty?
	git_dirty_tree=yes
        if git-diff-files --quiet && git-diff-index --cached --quiet HEAD; then
	    git_dirty_tree=no
        fi
    fi
fi

# Write program header
cat<<EOF
/*
 * Basic versioning gathered from the git repository.
 * Automatically generated by ${self}.
 */

#ifndef ${ifndef_symbol}
#define ${ifndef_symbol} 1

/* whether this header file is from a dist tarball */
#undef GIT_IS_DIST

EOF

# Write git specific defines
if [ "x$git_found" = "xno" ]; then
    echo "/* git is not installed */"
    echo "#undef GIT_IS_GIT_WORKTREE"
elif [ "x$is_git_worktree" = "xno" ]; then
    echo "/* This is not a git repository */"
    echo "#undef GIT_IS_GIT_WORKTREE"
else
    echo "/* This is a git repository */"
    echo "#define GIT_IS_GIT_WORKTREE 1"
    echo ""
    if [ "x$is_git_worktree" = "xyes" ]; then
	echo "/* Git ID of last commit */"
	echo "#define GIT_COMMIT_ID \"${git_commitid}..\""
	echo ""

	echo "/* Branch this tree is on */"
	echo "#define GIT_BRANCH \"$git_branch\""
	echo ""

	if [ "x$git_dirty_tree" = "xyes" ]; then
	    echo "/* Commit ID uniquely defines the state of this code */"
	    echo "#undef GIT_DIRTY_WORKTREE"
	else
	    echo "/* Local changes might be breaking things */"
	    echo "#define GIT_DIRTY_WORKTREE 1"
	fi
    else
	echo "/* Git ID of last commit */"
	echo "#undef GIT_COMMIT_ID"
	echo ""
	echo "/* Branch this tree is on */"
	echo "#undef GIT_BRANCH"
    fi
fi

# Define a few immediately useful message strings
cat<<EOF

/* Define GIT_MESSAGE such that
 *    printf("%s: built from %s", argv[0], GIT_MESSAGE);
 * forms a proper sentence.
 */

#ifdef GIT_IS_DIST
# define GIT_DIST_MSG "dist of "
# define GIT_DIST_MSG_2 " (possibly modified)"
#else
# define GIT_DIST_MSG ""
# define GIT_DIST_MSG_2 ""
#endif

#ifdef GIT_IS_GIT_WORKTREE

# ifdef GIT_DIRTY_WORKTREE
#  define GIT_CHANGE_MSG " + changes"
# else
#  define GIT_CHANGE_MSG ""
# endif /* GIT_DIRTY_WORKTREE */

# define GIT_MESSAGE \\
        GIT_DIST_MSG \\
        "git branch " GIT_BRANCH ", " \\
        "commit " GIT_COMMIT_ID GIT_CHANGE_MSG GIT_DIST_MSG_2

#else
# define GIT_MESSAGE GIT_DIST_MSG "non-git sources" GIT_DIST_MSG_2
#endif /* GIT_IS_GIT_WORKTREE */

#endif /* ${ifndef_symbol} */
EOF

# Example program
if "$print_example"
then
    cat<<EOF

/* example program demonstrating the use of ${self} output */
#include <stdio.h>
#include <string.h>

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

int main(int argc, char *argv[])
{
    const char *const idx = strrchr(argv[0], '/');
    const char *const prog = (idx)?(idx+1):(argv[0]);
#ifdef PACKAGE_VERSION
    printf("%s: version %s, built from %s\n", prog, PACKAGE_VERSION, GIT_MESSAGE);
#elif defined(GIT_USED)
    printf("%s: built from %s\n", prog, GIT_MESSAGE);
#endif
    return 0;
}
EOF
fi

# Change back to working dir for the remaining output file manipulations.
cd "$working_dir"

# If necessary, overwrite outdated output file with new one
if [ "x$outfile" != "x-" ]
then
    if [ -f "$outfile" ]; then
        if cmp "$outfile" "$outfile.new" > /dev/null; then
            echo "$self: Output is unchanged, keeping $outfile" >&2
            rm -f "$outfile.new"
        else
            echo "$self: Output has changed, updating $outfile" >&2
            mv -f "$outfile.new" "$outfile"
        fi
    else
        echo "$self: Output is new file, creating $outfile" >&2
        mv -f "$outfile.new" "$outfile"
    fi
fi

if "$error_if_no_git" && [ "x$is_git_worktree" = "xno" ]; then
    echo "$self: No git worktree found. Aborting with error, as requested." >&2
    exit 2
fi

# THE END.