+.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"
+
+# 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 '/^See ChangeLog.[0-9]* for earlier/,$$d' <ChangeLog.tmp && cat $(CHANGELOG_N)) \
+ >$(CHANGELOG_N).tmp
+ rm ChangeLog.tmp
+ new_origin=$$(git log --pretty=format:%H HEAD^!) && \
+ sed 's/^\(gen_origin=\).*/\1'"$$new_origin/" \
+ < $(emacslog) > $(emacslog).tmp && chmod +x $(emacslog).tmp
+ mv $(CHANGELOG_N).tmp $(CHANGELOG_N)
+ mv $(emacslog).tmp $(emacslog)
+
+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)
+