+.PHONY: ChangeLog change-history change-history-commit change-history-nocommit
+.PHONY: master-branch-is-current unchanged-history-files
+
+CHANGELOG = ChangeLog
+emacslog = build-aux/gitlog-to-emacslog
+# The ChangeLog history files are called ChangeLog.1, ChangeLog.2, ...,
+# ChangeLog.$(CHANGELOG_HISTORY_INDEX_MAX). $(CHANGELOG_N) stands for
+# the newest (highest-numbered) ChangeLog history file.
+CHANGELOG_HISTORY_INDEX_MAX = 2
+CHANGELOG_N = ChangeLog.$(CHANGELOG_HISTORY_INDEX_MAX)
+
+# Convert git commit log to ChangeLog file. make-dist uses this.
+# I guess this is PHONY so it always updates?
+ChangeLog:
+ $(AM_V_GEN)cd $(srcdir) && \
+ ./$(emacslog) -o $(CHANGELOG) -n $(CHANGELOG_HISTORY_INDEX_MAX)
+
+# Check that we are in a good state for changing history.
+master-branch-is-current:
+ git branch | grep -q '^\* master$$'
+unchanged-history-files:
+ x=$$(git diff-files --name-only $(CHANGELOG_N) $(emacslog)) && \
+ test -z "$$x"
+
+# Regular expression that matches the newest commit covered by a ChangeLog.
+new_commit_regexp = ^commit [0123456789abcdef]* (inclusive)
+
+# Copy newer commit messages to the start of the ChangeLog history file,
+# and consider them to be older.
+change-history-nocommit: master-branch-is-current unchanged-history-files
+ -rm -f ChangeLog.tmp
+ $(MAKE) ChangeLog CHANGELOG=ChangeLog.tmp
+ sed '/^This file records repository revisions/,$$d' \
+ ChangeLog.tmp >$(CHANGELOG_N).tmp
+ new_commit_line=`grep '$(new_commit_regexp)' ChangeLog.tmp` && \
+ sed 's/$(new_commit_regexp).*/'"$$new_commit_line/" \
+ $(CHANGELOG_N) >>$(CHANGELOG_N).tmp
+ rm ChangeLog.tmp
+ mv $(CHANGELOG_N).tmp $(CHANGELOG_N)
+
+change-history: change-history-nocommit
+ $(MAKE) $@-commit
+
+# If 'make change-history' fails because the newest ChangeLog history
+# file contains invalid text, fix the file by hand and then run
+# 'make change-history-commit'.
+change-history-commit:
+ git commit -m'; make $@' $(CHANGELOG_N) $(emacslog)
+