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