xref: /freebsd/sys/contrib/openzfs/scripts/make_gitrev.sh (revision 61145dc2b94f12f6a47344fb9aac702321880e43)
1#!/bin/sh
2# SPDX-License-Identifier: CDDL-1.0
3
4#
5# CDDL HEADER START
6#
7# This file and its contents are supplied under the terms of the
8# Common Development and Distribution License ("CDDL"), version 1.0.
9# You may only use this file in accordance with the terms of version
10# 1.0 of the CDDL.
11#
12# A full copy of the text of the CDDL should have accompanied this
13# source.  A copy of the CDDL is also available via the Internet at
14# http://www.illumos.org/license/CDDL.
15#
16# CDDL HEADER END
17#
18
19# Copyright (c) 2018 by Delphix. All rights reserved.
20# Copyright (c) 2018 by Matthew Thode. All rights reserved.
21
22#
23# Generate zfs_gitrev.h.  Note that we need to do this for every
24# invocation of `make`, including for incremental builds.  Therefore we
25# can't use a zfs_gitrev.h.in file which would be processed only when
26# `configure` is run.
27#
28
29set -eu
30
31dist=no
32distdir=.
33while getopts D: flag
34do
35	case $flag in
36		\?) echo "Usage: $0 [-D distdir] [file]" >&2; exit 1;;
37		D)  dist=yes; distdir=${OPTARG};;
38		*)  ;;
39	esac
40done
41shift $((OPTIND - 1))
42
43top_srcdir="$(dirname "$0")/.."
44GITREV="${1:-include/zfs_gitrev.h}"
45
46# GITREV should be a relative path (relative to top_builddir or distdir)
47case "${GITREV}" in
48	/*) echo "Error: ${GITREV} should be a relative path" >&2
49	    exit 1;;
50	*) ;;
51esac
52
53ZFS_GITREV=$({ cd "${top_srcdir}" &&
54	git describe --always --long --dirty 2>/dev/null; } || :)
55
56if [ -z "${ZFS_GITREV}" ]
57then
58	# If the source directory is not a git repository, check if the file
59	# already exists (in the source)
60	if [ -f "${top_srcdir}/${GITREV}" ]
61	then
62		ZFS_GITREV=$(sed -n \
63			'1s/^#define[[:blank:]]ZFS_META_GITREV "\([^"]*\)"$/\1/p' \
64			"${top_srcdir}/${GITREV}")
65	fi
66elif [ "${dist}" = yes ]
67then
68	# Append -dist when creating distributed sources from a git repository
69	ZFS_GITREV="${ZFS_GITREV}-dist"
70fi
71ZFS_GITREV=${ZFS_GITREV:-unknown}
72
73GITREVTMP="${GITREV}~"
74printf '#define\tZFS_META_GITREV "%s"\n' "${ZFS_GITREV}" >"${GITREVTMP}"
75GITREV="${distdir}/${GITREV}"
76if cmp -s "${GITREV}" "${GITREVTMP}"
77then
78	rm -f "${GITREVTMP}"
79else
80	mv -f "${GITREVTMP}" "${GITREV}"
81fi
82