# Makefile --- Build GNU Hyperbole directories and package distributions
#
# Author:       Bob Weiner
#
# Orig-Date:    15-Jun-94 at 03:42:38
# Last-Mod:     12-Nov-26 at 00:03:19 by Mats Lidell
#
# Copyright (C) 1994-2026  Free Software Foundation, Inc.
# See the file HY-COPY for license information.
#
# This file is part of GNU Hyperbole.

# Commentary:
#
#   **********
#   READ THIS:
#   **********
#
#   GNU Hyperbole should be installed for use via the Emacs package system;
#   see "README.md#Installation" for installation instructions and the Info
#   node, "(emacs)Packages", if you are unfamiliar with the Emacs package
#   system.
#
#   Only Hyperbole developers (those who develop the source code) and testers
#   need to use this file for building Hyperbole distributions.  Others
#   may ignore it.
#
#   **********
#
#   Before doing your first make, edit the CONFIGURABLE SECTION below.
#   Make any needed changes now and save the file.  Then select from the
#   USAGE lines immediately following.
#
#   USAGE:	For those installing GNU Hyperbole, display your options with:
#   	             make help
#
#               To build only the output formats of the Hyperbole Manual:
#		     make doc
#
#               List major build env versions:
#                   make env
#
#               Lint all Hyperbole code files:
#                   make lint
#
#               To setup Hyperbole to run directly from the latest test source
#               code, use:
#                    git clone http://git.savannah.gnu.org/r/hyperbole.git
#                    cd hyperbole
#                 Then use either:
#                    make src     - setup to run directly from .el files
#                  or
#                    make bin     - setup to build and run from .elc files
#                  or
#                    make eln     - setup to build and run from .eln natively compiled files
#
#               The Hyperbole Manual is included in the package in four forms:
#                  "man/hyperbole.info"   - GNU browsable version
#                  "man/hyperbole.html"   - Web browsable version
#                  "man/hyperbole.pdf"    - Printable version
#                  "man/hyperbole.texi"   - source form
#
#               * Developer targets
#
#		Note: Releasing to ELPA is automatic in that the
#		master branch on savannah is automatically synced
#		daily by ELPA. The ftp target is for making and
#		uploading a tar ball to ftp.gnu.org.
#
#               To release a Hyperbole Emacs package. The release
#               process uses a pre and a post step.
#
#		Pre:
#		    M-x hypb-release-update-version (Update all version strings except in Hyperbole.el)
#                   make doc
#                   make version
#                   make pkg        # Eyeball that it looks right
#		    -- Do all other preparations left for the release.
#		    -- Commit and push all updates to master
#		    make release-pre - Creates release branch, updates package version header,
#			creates a PR with the changes for review.
#
#		Post:
#		    Approve and merge the PR from the pre step.
#		    make release-post	- tags the release commit, upload tarball to ftp.gnu.org, update website
#
#		Sub targets for the release:
#		    make sync-repos	- Sync savannah and github/rswgnu repos.
#		    make git-tag-release	- Sync repos, create and push the release tag to both repos.
#		    make ftp 	- Build and upload tarball to ftp.gnu.org.
#
#		Generate the website sources and upload them:
#		    make website-local - generate web site in folder $(HYPB_WEB_REPO_LOCATION)"
#		    make website - As website-local and update live hyperbole web (cvs commit ...)
#		    make release-website - As website but act on the release tag.
#
#               To run unit tests:
#                   make all-tests                    - run all tests in a new interactive Emacs
#                   make all-tests test=<test-name>   - run all tests that match <test-name> in a new interactive emacs
#
#                   make batch-tests                  - run non-interactive tests in batch mode
#                   make batch-tests test=<test-name> - run a single test or tests matching the name in batch mode
#
#               To interactively run a docker version of Emacs with Hyperbole:
#                   make docker-run              - default to running master
#                   make docker-run version=28.2 - run Emacs V28.2
#
#               To build and test a Hyperbole with a dockerized version of Emacs:
#                   make docker                  - defaults: version=master targets='clean bin test'
#
#                   make docker version=28.2 targets='clean bin' - byte-compile Hyperbole with Emacs 28.2
#
#                   For CI/CD Emacs versions see macro DOCKER_VERSIONS below.
#
#		    make docker-batch-tests      - run all non-interactive tests in docker for all CI/CD Emacs versions
#		    make docker-all-tests        - run all tests in docker for all CI/CD Emacs versions
#
#               To update the docker image for Emacs:
#                   make docker-update           - default: version=master
#               The convenience targets docker-latest and
#               docker-run-latest updates the image if needed
#               available before running the docker job.
#
#               To clean the local elpa docker volume use:
#                   make docker-clean

#               Verify hyperbole installation using docker. The
#               different install sources are selected by the name of
#               the target.
#                   make install-<source>
#               Where source can be 'elpa', 'elpa-devel', 'tarball' (tarball from elpa-devel),
#               'straight' (git master from savannah) or 'all'.

# Code:
##########################################################################
#                         CONFIGURABLE SECTION                           #
##########################################################################

# This ver setup won't work under any make except GNU make, so set it manually.
#HYPB_VERSION = "`head -3 hversion.el | tail -1 | sed -e 's/.*|\(.*\)|.*/\1/'`"
HYPB_VERSION = 9.3.2

# Emacs executable used to byte-compile .el files into .elc's.
# To override which executable is used from the commandline, do something like this:
#  make EMACS=/Applications/Emacs28-nativecomp.app/Contents/MacOS/Emacs bin
EMACS = \emacs

# Site-specific Emacs Lisp libraries to load before byte-compiling any files
# from this package.  Typically the only reason to set this is to get Emacs
# to include the directory of this package into its load-path variable, which
# determines where it will find Lisp library files to load.  This is now
# handled automatically by Hyperbole for most modern versions of Emacs.
#
# You must include the .el or .elc file suffix on each library name and each
# must be preceded by the `-l' command-line flag.  If the directory in which
# the library is stored will not be in your Emacs load-path when Emacs
# attempts to load the library, you must include the full pathname to the
# library.  Here is an example setting.
#
# SITE_PRELOADS = -l ~/.emacs -l set-load-path.el
#
SITE_PRELOADS =

# Command used to build the .info version of the user manual.
TEXICMD = texi2any --error-limit=0
# Ensure punctuation generated by $(TEXICMD) is ascii, not unicode (requires texi2any 7.0 or above).
TEXI2INFO = $(TEXICMD) --no-split -c ASCII_PUNCTUATION=1
# Command used to build the .html version of the user manual.
# TEXI2HTML = id-texi2html -html_only -number -split_chapter # InfoDock-specific command
# TEXI2HTML = $(TEXICMD) --html --split=chapter # Chapter splitting doesn't seem to work in 6.0
# TEXI2HTML = $(TEXICMD) --html --no-split --css-include="hyperbole.css"
TEXI2HTML = $(TEXICMD) --html --no-split -c ASCII_PUNCTUATION=1 \
	--css-include="texinfo-7.css" --css-include="copy-btn.css"

# Command used to build the .pdf version of the user manual.
TEXI2PDF = $(TEXICMD) --pdf --no-split -c ASCII_PUNCTUATION=1

# Where to find the parent tree of the Hyperbole source directory.
id_dir = $(HOME)/sw-dev/emacs
# Where to find the .texi source of the user manual.
man_dir := $(shell pwd)/man
# Where to install the Hyperbole mouse key help file
data_dir = $(id_dir)/id-etc
# Where to install the Info version of the user manual.
info_dir = $(id_dir)/id-info
# Where to install the HTML version of the user manual.
html_dir = $(id_dir)/id-html

# Shell used to process this Makefile.  Bourne shell syntax is required.
SHELL = /bin/sh

# Shell commands you may want to change for your particular system.
CP = \cp -p
ETAGS = \etags
# With gnupload the option --dry-run can be used for testing the upload.
GNUFTP = \gnupload --to ftp.gnu.org:hyperbole --replace
GZIP = \gzip -c
INSTALLER = \install -m 644 -c
MKDIR = \mkdir -p
RM = \rm -f
TAR = \tar
ZIP = \zip -qry
CVS = \cvs
TOUCH = \touch

# Directory in which to create new package distributions of Hyperbole.
pkg_parent = /tmp
pkg_hyperbole = $(pkg_parent)/hyperbole-$(HYPB_VERSION)

# Temp file to use to build .elc files.
ELISP_TO_COMPILE = $(pkg_parent)/elc-${USER}

# Path to dir where the web repository is located i.e. hypb:web-repo-location
HYPB_WEB_REPO_LOCATION = ../hyweb/hyperbole/

# CI/CD Emacs versions for local docker based tests
DOCKER_VERSIONS=28.2 29.4 30.2 31.1 master

##########################################################################
#                     NO CHANGES REQUIRED BELOW HERE.                    #
##########################################################################

# Verbosity macros - Prefer short messages for each command. Uncomment
# for seeing the full command.
HYPB_GEN     = @$(info $.  GEN      $@)
HYPB_ELC     = @$(info $.  ELC      $@)
HYPB_ELC_ELN = @$(info $.  ELC+ELN  $@)
HYPB_at      = @

# Libraries that must be pre-loaded before trying to byte-compile anything.
PRELOADS = $(SITE_PRELOADS) -l ./hload-path.el -l ./hversion.el -l ./hyperbole.el

# Compile in batch mode.  Load site-lisp/site-start.el, which may set load-path.
# Show complete expression; do not abbreviate any exprs in batch logs with ...
BATCHFLAGS = --batch --quick --eval "(setq backtrace-line-length 0)"

VERSIONFLAGS = --eval "(message \"  emacs-version = %s\n  system-configuration = %s\n  emacs = %s%s\n  load-path = %s\" emacs-version system-configuration invocation-directory invocation-name load-path)"

EMACS_BATCH=$(EMACS) $(BATCHFLAGS) $(PRELOADS)
EMACS_PLAIN_BATCH=$(EMACS) $(BATCHFLAGS)

# Directories other than the current directory in which to find files.
# This doesn't seem to work in all versions of make, so we also add kotl/
# explicitly to those files which need it.
VPATH = kotl man

EL_COMPILE = hact.el hactypes.el hargs.el hbdata.el hbmap.el hbut.el \
	     hgnus.el hhist.el hib-debbugs.el hib-doc-id.el hib-kbd.el \
	     hib-social.el hibtypes.el \
	     hinit.el hload-path.el hmail.el hmh.el hmoccur.el hmouse-info.el \
	     hmouse-drv.el hmouse-key.el hmouse-mod.el hmouse-sh.el hmouse-tag.el \
	     hpath.el hproperty.el hrmail.el hsettings.el hsmail.el hsys-consult.el \
             hsys-denote.el hsys-ert.el hsys-flymake.el hsys-activities.el \
             hsys-org.el hsys-org-roam.el hsys-www.el hsys-xref.el hsys-youtube.el htz.el \
	     hycontrol.el hui-jmenu.el hui-menu.el hui-mini.el hui-mouse.el hui-select.el \
	     hui-treemacs.el hui-window.el hui.el hvar.el hversion.el hynote.el hypb.el hyperbole.el \
	     hyrolo-demo.el hyrolo-logic.el hyrolo-menu.el hyrolo.el hywconfig.el hywiki.el \
             hasht.el set.el hypb-ert.el hui-dired-sidebar.el hypb-maintenance.el \
             hui-register.el hypb-release.el

EL_SRC = $(EL_COMPILE)

EL_KOTL = kotl/kexport.el kotl/kfile.el kotl/kfill.el kotl/kimport.el kotl/klabel.el \
	  kotl/klink.el kotl/kmenu.el kotl/kotl-mode.el kotl/kotl-orgtbl.el \
          kotl/kcell.el kotl/kproperty.el kotl/kview.el kotl/kvspec.el

ELC_COMPILE = $(EL_COMPILE:.el=.elc)

ELC_KOTL = $(EL_KOTL:.el=.elc)

HY-TALK  = HY-TALK/.hypb HY-TALK/HYPB HY-TALK/HY-TALK.org HY-TALK/HYPERAMP.org \
	   HY-TALK/HYPERORG.org HY-TALK/HYPERBOLEQA.kotl

HYPERBOLE_FILES = dir info html $(EL_SRC) $(EL_KOTL) \
	$(HY-TALK) .mailmap ChangeLog COPYING Makefile HY-ABOUT \
        HY-CONCEPTS.kotl HY-NEWS.org HY-WHY.kotl $(wildcard hywiki/*.org) \
        DEMO DEMO-ROLO.otl FAST-DEMO MANIFEST README.in.md TAGS _hypb \
        .hypb hyrolo.py smart-clib-sym topwin.py hyperbole-banner.png \
	.dir-locals.el \
	$(man_dir)/hkey-help.txt $(man_dir)/hyperbole.texi $(man_dir)/hyperbole.css \
        $(man_dir)/texinfo-7.css

TEST_ERT_FILES = $(wildcard test/*tests.el) $(wildcard test/hy-test-*.el)

EL_TAGS = $(EL_SRC) $(EL_KOTL) $(TEST_ERT_FILES)

.SUFFIXES:            # Delete the default suffixes
.SUFFIXES: .el .elc   # Define the list of file suffixes to match to rules

.PHONY: help
help:
	@echo "Use the Emacs Package Manager to build and install the latest release of GNU Hyperbole."
	@echo "For help with Emacs packages, see the GNU Emacs Info Manual section, \"(emacs)Packages\"."
	@echo "See \"$(shell pwd)/README.md#Installation\" for detailed installation instructions,"
	@echo "including how to install Hyperbole pre-releases from the git repo tip."
	@echo ""

	@echo "To setup Hyperbole to run directly from the latest test source code, use:"
	@echo "     git clone http://git.savannah.gnu.org/r/hyperbole.git"
	@echo "     cd hyperbole"
	@echo "  Then use either:"
	@echo "     make src     - setup to run directly from .el files"
	@echo "   or"
	@echo "     make bin     - setup to build and run from .elc files"
	@echo ""

	@echo "For Hyperbole maintainers only:"
	@echo "  To run unit tests:"
	@echo "     make all-tests          - run all tests with Emacs under a window system"
	@echo "     make batch-tests        - run non-interactive tests with Emacs in batch mode"
	@echo "  Using docker and the macro DOCKER_VERSIONS for selected Emacs versions to test against"
	@echo "     make docker-all-tests   - run all tests"
	@echo "     make docker-batch-tests - run non-interactive tests"
	@echo "  To run test coverage analysis:"
	@echo "     make coverage file=<file> test=<testspec>"
	@echo "  To run lint on all sources"
	@echo "     make lint"
	@echo "  To check if a file is missings the copyright statement"
	@echo "     make check-copyright"
	@echo "  To selectively run make targets in docker:"
	@echo "     make docker version=<emacs-version> targets=<make targets>"
	@echo "  To verify hyperbole installation using different sources:"
	@echo "     make install-<source>"
	@echo "     where <source> can be 'elpa', 'elpa-devel', 'tarball', ..."
	@echo "  To build documentation formats only:"
	@echo "     make doc"
	@echo "  To generate and upload the public Hyperbole website:"
	@echo "     make website"
	@echo "  Help targets used when making a release:"
	@echo "     make release-pre"
	@echo "     make release-post"
	@echo ""

	@echo "The Hyperbole Manual is included in the package in four forms:"
	@echo "    man/hyperbole.info    - GNU browsable version"
	@echo "    man/hyperbole.html    - Web browsable version"
	@echo "    man/hyperbole.pdf     - Printable version"
	@echo "    man/hyperbole.texi    - source form"
	@echo ""

.PHONY: all
all: help

.PHONY: echo env
echo: env
env:
	@echo "Emacs: $(shell which ${EMACS})"
	@echo "Version: $(shell ${EMACS} --version)"
	@echo "TERM: $(TERM)"
	@echo "DISPLAY: $(DISPLAY)"

.PHONY: emacs-environment
emacs-environment:
	@$(EMACS_PLAIN_BATCH) $(VERSIONFLAGS)

.PHONY: install
install: elc install-info install-html $(data_dir)/hkey-help.txt

.PHONY: install-info
install-info: $(info_dir)/hyperbole.info
$(info_dir)/hyperbole.info: $(man_dir)/hyperbole.info
	$(MKDIR) $(info_dir)/im; \
	  cd $(man_dir); $(INSTALLER) hyperbole.info* $(info_dir); \
	  $(INSTALLER) im/*.{png,eps} $(info_dir)/im

.PHONY: install-html
install-html: $(html_dir)/hyperbole.html
$(html_dir)/hyperbole.html: $(man_dir)/hyperbole.html $(man_dir)/hyperbole.css $(man_dir)/texinfo-7.css
	$(MKDIR) $(html_dir)/im; \
	  cd $(man_dir); $(INSTALLER) hyperbole.html* hyperbole.css texinfo-7.css $(html_dir); \
	  $(INSTALLER) im/*.{png,eps} $(html_dir)/im

$(data_dir)/hkey-help.txt: $(man_dir)/hkey-help.txt
	$(INSTALLER) hkey-help.txt $(data_dir)

# Setup to run Hyperbole from .el source files
.PHONY: src
src: autoloads tags

# Byte compile files but apply a filter for either including or
# removing warnings.  See variable {C-hv byte-compile-warnings RET}
# for list of warnings that can be controlled.  Default is set to 'all
# from emacs versions that define `byte-compile--emacs-build-warning-types'.
#
# Example for getting warnings for obsolete functions and variables
#   HYPB_WARNINGS="obsolete" make bin
# Example for surpressing the obsolete warnings
#   HYPB_WARNINGS="not obsolete" make bin
ifeq ($(origin HYPB_WARNINGS), undefined)
HYPB_BIN_WARN = --eval "(setq-default byte-compile-warnings (if (boundp 'byte-compile--emacs-build-warning-types) 'all t))"
else ifeq ($(origin HYPB_WARNINGS), environment)
HYPB_BIN_WARN = --eval "(setq-default byte-compile-warnings '(${HYPB_WARNINGS}))"
endif

curr_dir = $(shell pwd)
ifeq ($(HYPB_NATIVE_COMP),yes)
HYPB_BYTE_COMP_INFO = $(HYPB_ELC_ELN)
HYPB_BYTE_COMP_FUNC = batch-byte+native-compile
HYPB_BYTE_COMP_ELN_LOAD_PATH = --eval "(add-to-list			\
	'native-comp-eln-load-path (expand-file-name \"eln-cache\"	\
	user-emacs-directory) t))"
else
HYPB_BYTE_COMP_INFO = $(HYPB_ELC)
HYPB_BYTE_COMP_FUNC = batch-byte-compile
endif
%.elc: %.el
	$(HYPB_BYTE_COMP_INFO)$(EMACS) --batch --quick \
	--eval "(setq load-prefer-newer t)" \
	$(HYPB_BYTE_COMP_ELN_LOAD_PATH) \
	--eval "(progn (add-to-list 'load-path \"$(curr_dir)\") (add-to-list 'load-path \"$(curr_dir)/kotl\"))" \
	-l bytecomp ${HYPB_BIN_WARN} \
	-f $(HYPB_BYTE_COMP_FUNC) $<

.PHONY: new-bin
new-bin: $(ELC_KOTL) $(ELC_COMPILE)

.PHONY: remove-elc
remove-elc:
	$(HYPB_at)$(RM) *.elc kotl/*.elc

# Remove and then rebuild all byte-compiled .elc files, even those .elc files
# which do not yet exist, plus build TAGS file.
.PHONY: bin
bin: remove-elc src new-bin

# Native compilation (Requires Emacs built with native compilation support.)
.PHONY: eln
eln:
	HYPB_NATIVE_COMP=yes $(MAKE) new-bin

.PHONY: tags
tags: TAGS
TAGS: $(EL_TAGS)
	$(HYPB_GEN)$(ETAGS) --regex='{lisp}/(ert-deftest[ \t]+\([^ \t\n\r\f()]+\)/' $(EL_TAGS)

.PHONY: clean
clean:
	$(HYPB_at)$(RM) hyperbole-autoloads.el kotl/kotl-autoloads.el $(ELC_COMPILE) $(ELC_KOTL) TAGS test/*.elc

.PHONY: version
version:
	@echo ""
	@fgrep -L $(HYPB_VERSION) Makefile HY-ABOUT HY-NEWS.org README.in.md hversion.el man/hyperbole.texi > WRONG-VERSIONS
	@# If any file(s) have wrong version number, print them and exit with code 1
	@if [ -s WRONG-VERSIONS ]; then \
	  echo "The following files do not have the proper Hyperbole version number, $(HYPB_VERSION):"; \
	  cat WRONG-VERSIONS; rm -f WRONG-VERSIONS; exit 1; \
	fi
	@rm -f WRONG-VERSIONS
	@echo ""

# Build the README.md, README.md.html and Info, HTML and Postscript versions of the user manual
.PHONY: doc
doc: version README.md manual

# Convenience targets for regenerating the docs
DOC_SUFFIXES = log aux cp cpz fn fns ky toc vr vrs info pdf html
.PHONY: doc-clean doc-regenerate
doc-clean:
	$(RM) $(foreach suf,$(DOC_SUFFIXES),$(man_dir)/hyperbole.$(suf))
	$(RM) README.md README.md.html

doc-regenerate: doc-clean doc

# Build the Info, HTML and Postscript versions of the user manual
.PHONY: manual
manual: info html pdf man/use-package

TEXINFO_SRC = $(man_dir)/hyperbole.texi $(man_dir)/hkey-help.txt $(man_dir)/im/*.png

.PHONY: info
info: $(man_dir)/hyperbole.info
$(man_dir)/hyperbole.info: $(TEXINFO_SRC)
	cd $(man_dir) && $(TEXI2INFO) hyperbole.texi && (sed -e 's/texi2any/makeinfo/' hyperbole.info > h.info && mv h.info hyperbole.info)

.PHONY: pdf
pdf: $(man_dir)/hyperbole.pdf
$(man_dir)/hyperbole.pdf: $(TEXINFO_SRC)
	cd $(man_dir) && $(TEXI2PDF) hyperbole.texi

.PHONY: html
html: $(man_dir)/hyperbole.html pdf
$(man_dir)/hyperbole.html: $(TEXINFO_SRC) $(man_dir)/hyperbole.css $(man_dir)/texinfo-7.css
	cd ${man_dir} && $(TEXI2HTML) hyperbole.texi

# The `md_toc' table-of-contents generator program is available from:
#   https://github.com/frnmst/md-toc
#
# `pandoc' is available from:
#    https://github.com/jgm/pandoc
README.md README.md.html: README.in.md man/use-package Makefile
	# Generate README.md
	cp -p README.in.md README.md && md_toc -p -m [TOC] github README.md \
	  && sed -i -e "s+^\[TOC\]++g" \
                    -e "s+[ \t]*\[man/use-package\](man/use-package)+cat man/use-package+e" README.md
	# Generate README.md.html
	cp -p README.in.md README.in.html
	sed -i -e "s+^\[TOC\]++g" \
               -e "s+[ \t]*\[man/use-package\](man/use-package)+cat man/use-package+e" README.in.html
	pandoc --standalone --embed-resources \
	  -V pagetitle="README.md" \
	  --from=gfm-tex_math_dollars --to=html+gfm_auto_identifiers \
	  --css=man/copy-btn.css --include-after-body=man/copy-btn.html \
	  -o README.md.html README.in.html
	rm README.in.html

# website maintenance: "https://www.gnu.org/software/hyperbole/"
define confirm
	@echo "═══════════════════════════════════════"
	@echo "  WARNING: $(1)"
	@echo "═══════════════════════════════════════"
	@read -r -p "Are you sure? Write '$(2)' to continue: " answer; \
	[ "$$answer" = "$(2)" ] || { echo "Aborted."; exit 1; }
endef

# Locally update Hyperbole website
.PHONY: website-local
website-local:
	$(EMACS_BATCH) --debug -l hypb-maintenance --eval '(let ((hypb:web-repo-location "$(HYPB_WEB_REPO_LOCATION)")) (hypb:web-repo-update))'

# Push to public Hyperbole website
.PHONY: website
website: website-local
	$(call confirm,Deploys to website!,YES)
	cd $(HYPB_WEB_REPO_LOCATION) && $(CVS) commit -m "Hyperbole release $(HYPB_VERSION)"
	@echo "Website for Hyperbole $(HYPB_VERSION) is updated."

# Checkout the release version of Hyperbole and use that to update the
# webpage.
.PHONY: release-website
release-website:
	git checkout hyperbole-$(HYPB_VERSION)
	$(MAKE) website

# Update Version header in package file hyperbole.el, commit and push
# the change and prepare a PR with the update.
.PHONY: release-pre
release-pre:
	git fetch github_origin
	git switch -c release_$(HYPB_VERSION) --no-track github_origin/master
	$(EMACS_BATCH) -l hypb-release \
	  --eval '(hypb-release-update-hyperbole-version-header "$(HYPB_VERSION)")'
	$(MAKE) version
	git add hyperbole.el
	git commit -m "Release Hyperbole $(HYPB_VERSION)"
	git push github_origin HEAD
	gh pr create \
          --repo rswgnu/hyperbole \
          --base master \
          --head release_$(HYPB_VERSION) \
          --title "Hyperbole Release $(HYPB_VERSION)" \
          --body ""

# After PR has been merged: Sync the repos, tag the release, create
# and upload the tarball to ftp.gnu.org and update the website.
.PHONY: release-post
release-post: git-tag-release ftp release-website

.PHONY: git-tag-release
git-tag-release: sync-repos
	$(call confirm,Set git tag to hyperbole-$(HYPB_VERSION) on Savannah and GitHub!,YES)
	git tag -a hyperbole-$(HYPB_VERSION) github_origin/master -m "Hyperbole release $(HYPB_VERSION)"
	git push origin hyperbole-$(HYPB_VERSION)
	git push github_origin hyperbole-$(HYPB_VERSION)
	@echo "Hyperbole $(HYPB_VERSION) is tagged as hyperbole-$(HYPB_VERSION)."

define RELEASE_PRE_CHECK
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!! Have you remembered to do all of this ???                           !!!
!!!                                                                     !!!
!!! M-x hypb-release-update-version                                     !!!
!!! make doc                                                            !!!
!!! make version                                                        !!!
!!! make pkg        => !!! Eyeball that it looks right !!!              !!!
!!! -- Done all other preparations you kan think of that is left        !!!
!!!    relevant for this release?                                       !!!
!!!                                                                     !!!
!!! (AND FINALLY, MOST IMPORTANT)                                       !!!
!!! Committed, pushed and merged all above updates to github_master ??? !!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
endef
export RELEASE_PRE_CHECK

.PHONY: release-pre-check
release-pre-check:
	@printf '%s\n' "$$RELEASE_PRE_CHECK"
	$(call confirm,All preparations done?,YES)

.PHONY: release
release:
	$(MAKE) release-pre-check
	$(MAKE) release-pre
	$(call confirm,...Wait for PR to be built and approved. Ready?,YES)
	gh pr merge --squash
	$(MAKE) release-post

.PHONY: sync-repos
sync-repos:
	git fetch github_origin
	git push origin github_origin/master:refs/heads/master

# Send compressed tarball for uploading to GNU ftp site; this must be
# done from the directory containing the tarball to upload.
.PHONY: ftp
ftp: $(pkg_parent)/hyperbole-$(HYPB_VERSION).tar.gz
	$(call confirm,Uploads release to ftp.gnu.org!,YES)
	cd $(pkg_parent) && $(GNUFTP) hyperbole-$(HYPB_VERSION).tar.gz
	@echo "Hyperbole $(HYPB_VERSION) uploaded to ftp.gnu.org."

# Autoloads
.PHONY: autoloads
autoloads: kotl/kotl-autoloads.el hyperbole-autoloads.el

hyperbole-autoloads.el: $(EL_COMPILE)
	$(HYPB_GEN)$(EMACS_BATCH) --debug --eval "(let ((autoload-file (expand-file-name \"hyperbole-autoloads.el\")) (backup-inhibited t) (find-file-hooks)) (hload-path--make-directory-autoloads \".\" autoload-file)))"
	$(HYPB_at)$(TOUCH) $@

kotl/kotl-autoloads.el: $(EL_KOTL)
	$(HYPB_GEN)$(EMACS_BATCH) --debug --eval "(let ((autoload-file (expand-file-name \"kotl/kotl-autoloads.el\")) (backup-inhibited t) (find-file-hooks)) (hload-path--make-directory-autoloads \"kotl/\" autoload-file))"
	$(HYPB_at)$(TOUCH) $@

# Used for ftp uploads. Pick tagged release files, make autoloads and
# put together as a compressed tarball.
$(pkg_parent)/hyperbole-$(HYPB_VERSION).tar.gz:
	$(RM) -fr $(pkg_hyperbole)
	git archive --format=tar --prefix=hyperbole-$(HYPB_VERSION)/ hyperbole-$(HYPB_VERSION) \
	  | (cd $(pkg_parent) && tar xf -)
	cd $(pkg_hyperbole) && \
	  $(MAKE) autoloads && \
	  chmod 755 topwin.py && \
	  COPYFILE_DISABLE=1 $(TAR) -C $(pkg_parent) -clzf $(pkg_hyperbole).tar.gz hyperbole-$(HYPB_VERSION)

# Create a tarball based on local files. Pick version controlled
# files, make autoloads and put together as a compressed tarball.
.PHONY: pkg
pkg: $(pkg_parent)/hyperbole-local.tar.gz

$(pkg_parent)/hyperbole-local.tar.gz: $(HYPERBOLE_FILES)
	$(RM) -fr $(pkg_parent)/hyperbole-local
	mkdir -p $(pkg_parent)/hyperbole-local
	git ls-files -z | xargs -0 cp --parents -t $(pkg_parent)/hyperbole-local
	cd $(pkg_parent)/hyperbole-local && \
	  $(MAKE) autoloads && \
	  chmod 755 topwin.py && \
	  COPYFILE_DISABLE=1 $(TAR) -C $(pkg_parent) -clzf $(pkg_parent)/hyperbole-local.tar.gz hyperbole-local

.PHONY: pkgclean packageclean
pkgclean: packageclean
packageclean:
	if [ -d $(pkg_hyperbole) ]; then \
	  $(RM) -r $(pkg_hyperbole); \
	fi
	$(RM) $(pkg_parent)/hyperbole-$(HYPB_VERSION).*
	if [ -d $(pkg_parent)/hyperbole-local ]; then \
	  $(RM) -r $(pkg_parent)/hyperbole-local; \
	fi
	$(RM) $(pkg_parent)/hyperbole-local.tar.gz

# ERT test
.PHONY: tests test batch-tests
batch-tests: test
tests: test
test: test-ert

# enable-local-variables setting needed so local variables set in files like
# FAST-DEMO are automatically obeyed without prompting when testing.
LET_VARIABLES = (auto-save-default) (enable-local-variables :all)
LOAD_TEST_ERT_FILES=$(patsubst %,(load-file \"%\"),${TEST_ERT_FILES})

# Run make test test=<ert-test-selector> to limit batch test to
# tests specified by the selector. See "(ert)test selectors"
ifeq ($(origin test), command line)
HYPB_ERT_BATCH = (ert-run-tests-batch-and-exit \"${test}\")
HYPB_ERT_INTERACTIVE = (ert-run-tests-interactively \"${test}\")
else
HYPB_ERT_BATCH = (ert-run-tests-batch-and-exit)
HYPB_ERT_INTERACTIVE = (ert-run-tests-interactively t)
endif
ifeq ($(origin failure), command line)
HYPB_ERT_FAILURE = (setq hy-test-run-failing-flag ${failure})
endif

# For full backtrace run make test FULL_BT=<anything or even empty>
ifeq ($(origin FULL_BT), command line)
HYPB_ERT_BATCH_BT = (ert-batch-backtrace-line-length t) (backtrace-line-length nil)
else
HYPB_ERT_BATCH_BT = (ert-batch-backtrace-line-length 256) (backtrace-line-length 5000)
endif

# Run non-interactive tests in batch mode
.PHONY: test-ert
test-ert:
	@echo "# Tests: $(TEST_ERT_FILES)"
	$(EMACS_BATCH) --eval "(load-file \"test/hy-test-dependencies.el\")" \
	--eval "(let ((auto-save-default) (ert-batch-print-level 10) \
	              (ert-batch-print-length nil) \
	              $(HYPB_ERT_BATCH_BT) (ert-batch-backtrace-right-margin 2048)) \
	           $(LOAD_TEST_ERT_FILES) $(HYPB_ERT_FAILURE) $(HYPB_ERT_BATCH))"
	$(MAKE) verify-clean-test-run

# Verify that temporary files and directories are cleaned after a test run.
.PHONY: verify-clean-test-run
verify-clean-test-run:
	@if [ -n "$$(find /tmp -name 'hywiki*' -print -quit 2>/dev/null)" ]; then \
	  echo "hywiki test folders not removed!"; \
	  exit 1; \
	fi

# Run all tests by starting an Emacs that runs the tests interactively in windowed mode.
.PHONY: all-tests test-all
all-tests: test-all
test-all:
	@echo "# Tests: $(TEST_ERT_FILES)"
ifeq ($(TERM), dumb)
ifneq (,$(findstring .apple.,$(DISPLAY)))
        # Found, on MacOS
	TERM=xterm-256color $(EMACS) --quick $(PRELOADS) --eval "(load-file \"test/hy-test-dependencies.el\")" --eval "(let ($(LET_VARIABLES)) $(LOAD_TEST_ERT_FILES) $(HYPB_ERT_FAILURE) $(HYPB_ERT_INTERACTIVE))"
else
        # Not found, set TERM so tests will at least run within parent Emacs session
	TERM=vt100 $(EMACS) --quick $(PRELOADS) --eval "(load-file \"test/hy-test-dependencies.el\")" --eval "(let ($(LET_VARIABLES)) $(LOAD_TEST_ERT_FILES) $(HYPB_ERT_FAILURE) $(HYPB_ERT_INTERACTIVE))"
endif
else
        # Typical case, run emacs normally
	$(EMACS) --quick $(PRELOADS) --eval "(load-file \"test/hy-test-dependencies.el\")" --eval "(let ($(LET_VARIABLES)) $(LOAD_TEST_ERT_FILES) $(HYPB_ERT_FAILURE) $(HYPB_ERT_INTERACTIVE))"
endif

.PHONY: test-all-output
test-all-output:
	@output=$(shell mktemp); \
	$(EMACS) --quick $(PRELOADS) --eval "(load-file \"test/hy-test-dependencies.el\")" --eval "(let ($(LET_VARIABLES) (ert-quiet t)) $(LOAD_TEST_ERT_FILES) (ert-run-tests-batch t) (with-current-buffer \"*Messages*\" (append-to-file (point-min) (point-max) \"$$output\")) (kill-emacs))"; \
	sed -n -E '/^Ran [0123456789]+ tests/,/^make:/p' $$output; \
	rm $$output

# Target to be used in docker
.PHONY: internal-docker-all-tests-ert-output
internal-docker-all-tests-ert-output:
	@$(EMACS) --quick $(PRELOADS) --eval "(load-file \"test/hy-test-dependencies.el\")" --eval "(let ($(LET_VARIABLES) (ert-quiet t)) $(LOAD_TEST_ERT_FILES) (ert t) (with-current-buffer \"*ert*\" (write-region (point-min) (point-max) \"/hypb-tmp/ERT-OUTPUT-ERT\")) (kill-emacs))"

.PHONY: docker-all-tests
docker-all-tests:
	@total_summary=$(shell mktemp); \
	for i in $(DOCKER_VERSIONS); do printf "=== Emacs $$i ===\n" | tee -a $$total_summary; \
		make docker version=$$i targets='clean internal-docker-all-tests-ert-output'; \
		cat /tmp/ERT-OUTPUT-ERT | tee -a $$total_summary; \
	done; \
	printf "\n\n=== Summary ===\n"; cat $$total_summary; \
	rm $$total_summary

.PHONY: docker-batch-tests
docker-batch-tests:
	@total_summary=$(shell mktemp); build_summary=$(shell mktemp); \
	for i in $(DOCKER_VERSIONS); do printf "=== Emacs $$i ===\n" | tee -a $$total_summary; \
		make docker version=$$i targets='clean test' | tee $$build_summary; \
		sed -n -E '/^Ran [0123456789]+ tests/,/^make:/p' $$build_summary | head -n-1 | tee -a $$total_summary; \
	done; \
	printf "\n\n=== Summary ===\n"; cat $$total_summary; \
	rm $$total_summary $$build_summary

# Hyperbole install tests - Verify that hyperbole can be installed
# using different sources. See folder "install-test"
install-targets :=				\
	install-elpa				\
	install-elpa-devel			\
	install-melpa-snapshots			\
	install-melpa-releases			\
	install-tarball				\
	install-straight			\
	install-elpaca
.PHONY: install-all $(install-targets)
install-all: $(install-targets)
$(install-targets):
	@echo "Install Hyperbole using $@"
	cd ./install-test/ && \
	        docker run \
	          --mount type=bind,source=$$(pwd)/,target=/hypb-install \
	          --mount type=bind,source=$$(pwd)/../man/use-package,target=/tmp/use-package.el \
	          -it --rm silex/emacs:${DOCKER_VERSION} \
	        bash -c "cd /hypb-install && ./install-test.sh $(subst install-,,$@) ${debug}"

.PHONY: lint
lint:
	$(EMACS_BATCH) \
	--eval "(setq package-lint-main-file \"hyperbole.el\")" \
	--eval "(load-file \"test/hy-test-dependencies.el\")" \
	--eval "(add-to-list 'package-archives '(\"melpa\" . \"https://melpa.org/packages/\"))" \
	--eval "(hy-test-ensure-package-installed 'package-lint)" \
	-l package-lint.el -f package-lint-batch-and-exit \
	$(EL_KOTL) $(EL_SRC)

# Docker versions of Emacs for interactive running and test execution

# Specify version and targets to run
ifeq ($(origin targets), command line)
DOCKER_TARGETS = ${targets}
else
DOCKER_TARGETS = clean bin test
endif
ifeq ($(origin version), command line)
DOCKER_VERSION = ${version}-ci
else
DOCKER_VERSION = master-ci
endif

.PHONY: recompile-docker-elpa
recompile-docker-elpa:
	$(EMACS_BATCH) --eval "(byte-recompile-directory \"/root/.emacs.d/elpa\" 0 'force)"

.PHONY: docker-latest
docker-latest: docker-update
	$(MAKE) docker

.PHONY: docker
docker:
	docker run --mount type=volume,src=elpa-local,dst=/root/.emacs.d/elpa \
	-v $$(pwd):/hypb -v /tmp:/hypb-tmp -it --rm silex/emacs:${DOCKER_VERSION} \
	bash -c "cp -a /hypb /hyperbole && find /hyperbole -name '*.elc' -delete && make -C hyperbole recompile-docker-elpa ${DOCKER_TARGETS}"

.PHONY: docker-run-latest
docker-run-latest: docker-update
	$(MAKE) docker-run

.PHONY: docker-run
docker-run:
	docker run --mount type=volume,src=elpa-local,dst=/root/.emacs.d/elpa \
	-v $$(pwd):/hypb -v /tmp:/hypb-tmp -it --rm silex/emacs:${DOCKER_VERSION}

# Update the docker image for the specified version of Emacs
.PHONY: docker-update
docker-update:
	docker pull silex/emacs:${DOCKER_VERSION}

# Target for running emacs in the container with hyperbole loaded.
# Example: make docker version=29.4 targets="clean bin run-emacs"
.PHONY: run-emacs
run-emacs:
	emacs --eval "(progn (add-to-list 'load-path \"/hyperbole\") (require 'hyperbole) (hyperbole-mode 1))"

# Similar target for starting bash in the container. Useful for
# manually doing things before starting Emacs but having Hyperbole
# available in /hyperbole through the docker target.
.PHONY: run-bash
run-bash:
	bash

.PHONY: docker-clean
docker-clean:
	docker volume rm elpa-local || true

# Run with coverage. Run tests given by testspec and monitor the
# coverage for the specified file.
#
# Usage:
#    make coverage file=<file> test=<testspec>

# Specify file to inspect for coverage while running tests given by testspec
COVERAGE_FILE = ${file}
ifeq ($(origin test), command line)
COVERAGE_TESTSPEC = ${test}
else
COVERAGE_TESTSPEC = t
endif
.PHONY: coverage
coverage:
	$(EMACS) --quick $(PRELOADS) --eval "(setq enable-local-variables :all)" \
	--eval "(load-file \"test/hy-test-dependencies.el\")" \
	--eval "(load-file \"test/hy-test-coverage.el\")" \
	--eval "(hy-test-coverage-file \"${file}\" \"${COVERAGE_TESTSPEC}\")"

# List files missing copyright headers.  ELPA fails builds where
# .el-files does not contain the proper copyright.  The SPDX header
# might not be checked for but we check for that here as well anyway.
.PHONY: check-copyright
check-copyright:
	@missing="$$( \
	  { \
	    git grep -L 'Copyright.*Free Software Foundation' -- '*.el' ':(exclude)**.dir-locals.el'; \
	    git grep -L 'SPDX-License-Identifier: GPL-3.0-or-later' -- '*.el' ':(exclude)**.dir-locals.el' ; \
	  } | sort -u \
	)"; \
	if test -n "$$missing" ; then \
	  echo "Files missing copyright statement:"; \
	  echo "$$missing"; \
	  exit 1; \
	fi
