1 # Since we rely on paths relative to the Makefile location, abort if make isn't being run from there.
2 $(if $(findstring /,$(MAKEFILE_LIST)),$(error Please only invoke this makefile from the directory it resides in))
3 # Run all shell commands with bash.
5 # Add the local npm packages' bin folder to the PATH, so that `make` can find them even when invoked directly (not via npm).
6 # !! Note that this extended path only takes effect in (a) recipe commands that are (b) true shell commands (not optimized away) - when in doubt, simply append ';'
7 # !! To also use the extended path in $(shell ...) function calls, use $(shell PATH="$(PATH)" ...),
8 export PATH := $(PWD)/node_modules/.bin:$(PATH)
9 # Sanity check: git repo must exist.
10 $(if $(shell [[ -d .git ]] && echo ok),,$(error No git repo found in current dir. Please at least initialize one with 'git init'))
11 # Sanity check: make sure dev dependencies (and npm) are installed - skip this check only for certain generic targets (':' is the pseudo target used by the `list` target's recipe.)
12 $(if $(or $(shell [[ '$(MAKECMDGOALS)' =~ list|: ]] && echo ok), $(shell [[ -d ./node_modules/semver ]] && echo 'ok')),,$(error Did you forget to run `npm install` after cloning the repo (Node.js must be installed)? At least one of the required dev dependencies not found))
13 # Determine the editor to use for modal editing. Use the same as for git, if configured; otherwise $EDITOR, then fall back to vi (which may be vim).
14 EDITOR := $(shell git config --global --get core.editor || echo "$${EDITOR:-vi}")
16 # Default target (by virtue of being the first non '.'-prefixed target in the file).
17 .PHONY: _no-target-specified
19 $(error Please specify the target to make - `make list` shows targets. Alternatively, use `npm test` to run the default tests; `npm run` shows all commands)
21 # Lists all targets defined in this makefile.
24 @$(MAKE) -pRrn -f $(lastword $(MAKEFILE_LIST)) : 2>/dev/null | awk -v RS= -F: '/^# File/,/^# Finished Make data base/ {if ($$1 !~ "^[#.]") {print $$1}}' | grep -Ev -e '^[^[:alnum:]]' -e '^$@$$' | sort
26 # Open this package's online repository URL (typically, on GitHub) in the default browser.
27 # Note: Currently only supports OSX and Debian-based platforms.
30 @exe=; url=`json -f package.json repository.url` || exit; \
31 [[ `uname` == 'Darwin' ]] && exe='open'; \
32 [[ -n `command -v xdg-open` ]] && exe='xdg-open'; \
33 [[ -n $$exe ]] || { echo "Don't know how to open $$url in the default browser on this platform." >&2; exit 1; }; \
36 # Open this package's page in the npm registry.
37 # Note: Currently only supports OSX and Debian-based platforms.
40 @exe=; [[ `json -f package.json private` == 'true' ]] && { echo "This package is marked private (not for publication in the npm registry)." >&2; exit 1; }; \
41 url="https://www.npmjs.com/package/`json -f package.json name`" || exit; \
42 [[ `uname` == 'Darwin' ]] && exe='open'; \
43 [[ -n `command -v xdg-open` ]] && exe='xdg-open'; \
44 [[ -n $$exe ]] || { echo "Don't know how to open $$url in the default browser on this platform." >&2; exit 1; }; \
48 # To optionally skip tests in the context of target 'release', for instance, invoke with NOTEST=1; e.g.: make release NOTEST=1
51 @echo Note: Skipping tests, as requested. >&2
53 @if [[ -n $$(json -f package.json main) ]]; then tap ./test; else urchin ./test; fi
56 # Commits (with prompt for message) and pushes to the branch of the same name in remote repo 'origin', tags included.
58 push: _need-clean-ws-or-no-untracked-files
59 @[[ -z $$(git status --porcelain || echo no) ]] && echo "-- (Nothing to commit.)" || { git commit || exit; echo "-- Committed."; }; \
60 targetBranch=`git symbolic-ref --short HEAD` || exit; \
61 git push origin "$$targetBranch" || exit; \
62 git push origin "$$targetBranch" --tags || exit; \
66 # Reports the current version number - both from package.json and as defined by the latest git tag
67 # Implementation note: simply uses 'version' as a prerequisite, which queries $(MAKECMDGOALS) to adjust its behavior based on the caller.
71 # Increments the package's version number:
72 # Unless called via 'make verinfo', the workspace must be clean or at least have no untracked files.
73 # If VER is *not* specified in the environment:
74 # Reports the current version number - both from package.json and as defined by the latest git tag.
75 # If 'make version' was called directly, then prompts to change the version number.
76 # If called via 'make release', only prompts to change the version number if the git tag version number is the same as the package's.
77 # VER is set to the value entered and processing continues below.
78 # If VER *is* specified or continuing from above:
79 # Validates the new version number:
80 # If an increment specifier was given, increments from the latest package.json version number (as the version numbers stored in source files are assumed to be in sync with package.json).
81 # Implementation note: semver, as of v4.3.6, does not validate increment specifiers and simply defaults to 'patch' in case of an valid specifier; thus, we roll our own validation here.
82 # An increment specifier starting with 'pre' increments [to] a prerelease version number. By default, this simply appends or increments '-<num>', whereas '--preid <id>' can be used
83 # to append '-<id><num>' instead; however, we don't expose that, at least for now, though the user may specify an explicit, full pre-release version number.
84 # We use tag 'pre' with npm publish --tag, so as to have the latest prerelease be installable with <pkg>@pre, analogous to the (implicit) 'latest' tag that tracks production releases.
85 # An explicitly specified version number must be *higher* than the current one; pass variable FORCE=1 to override this in exceptional situations.
86 # Updates the version number in package.json and in source files in ./bin and ./lib.
89 @[[ '$(MAKECMDGOALS)' == *verinfo* ]] && infoOnly=1 || infoOnly=0; \
90 gitTagVer=`git describe --abbrev=0 --match 'v[0-9]*.[0-9]*.[0-9]*' 2>/dev/null || echo '(none)'` || exit; gitTagVer=$${gitTagVer#v}; \
91 pkgVer=`json -f package.json version` || exit; \
92 if [[ -z $$VER ]]; then \
93 printf 'CURRENT version:\n\t%s (package.json)\n\t%s (git tag)\n' "$$pkgVer" "$$gitTagVer"; \
94 (( infoOnly )) && exit; \
95 [[ $$pkgVer != "$$gitTagVer" && $$pkgVer != '0.0.0' ]] && { alreadyBumped=1 || alreadyBumped=0; }; \
96 if [[ '$(MAKECMDGOALS)' == 'release' && $$alreadyBumped -eq 1 ]]; then \
97 printf "=== `[[ $$pkgVer == *-* ]] && printf 'PRE-'`RELEASING:\n\t%s -> **%s** \n===\n" "$$gitTagVer" "$$pkgVer"; \
98 read -p '(Y)es or (c)hange (y/c/N)?: ' -re response && [[ "$$response" == [yYcC] ]] || { echo 'Aborted.' >&2; exit 2; }; \
99 [[ $$response =~ [yY] ]] && exit 0; \
102 if [[ '$(MAKECMDGOALS)' == 'version' || $$alreadyBumped -eq 0 ]]; then \
104 echo "Enter new version number in full or as one of: 'patch', 'minor', 'major', optionally prefixed with 'pre', or 'prerelease'."; \
105 echo "(Alternatively, pass a value from the command line with 'VER=<new-ver>'.)"; \
106 read -p "NEW VERSION number (just Enter to abort)?: " -re VER && { [[ -z $$VER ]] && echo 'Aborted.' >&2 && exit 2; }; \
111 if printf "$$newVer" | grep -q '^[0-9]'; then \
112 semver "$$newVer" >/dev/null || { echo "Invalid semver version number specified: $$VER" >&2; exit 2; }; \
113 [[ "$(FORCE)" != '1' ]] && { semver -r "> $$oldVer" "$$newVer" >/dev/null || { echo "Invalid version number specified: $$VER - must be HIGHER than $$oldVer. To force this change, use FORCE=1 on the command line." >&2; exit 2; }; } \
115 [[ $$newVer =~ ^(patch|minor|major|prepatch|preminor|premajor|prerelease)$$ ]] && newVer=`semver -i "$$newVer" "$$oldVer"` || { echo "Invalid version-increment specifier: $$VER" >&2; exit 2; } \
117 printf "=== About to BUMP VERSION:\n\t$$oldVer -> **$$newVer**\n===\nProceed (y/N)?: " && read -re response && [[ "$$response" = [yY] ]] || { echo 'Aborted.' >&2; exit 2; }; \
118 for dir in ./bin ./lib; do [[ -d $$dir ]] && { replace --quiet --recursive "v$${oldVer//./\\.}" "v$${newVer}" "$$dir" || exit; }; done; \
119 [[ `json -f package.json version` == "$$newVer" ]] || { npm version $$newVer --no-git-tag-version >/dev/null && printf $$'\e[0;33m%s\e[0m\n' 'package.json' || exit; }; \
120 [[ $$gitTagVer == '(none)' ]] && newVerMdSnippet="**v$$newVer**" || newVerMdSnippet="**[v$$newVer](`json -f package.json repository.url | sed 's/.git$$//'`/compare/v$$gitTagVer...v$$newVer)**"; \
121 grep -Eq "\bv$${newVer//./\.}[^[:digit:]-]" CHANGELOG.md || { { sed -n '1,/^<!--/p' CHANGELOG.md && printf %s $$'\n* '"$$newVerMdSnippet"$$' ('"`date +'%Y-%m-%d'`"$$'):\n * ???\n' && sed -n '1,/^<!--/d; p' CHANGELOG.md; } > CHANGELOG.tmp.md && mv CHANGELOG.tmp.md CHANGELOG.md; }; \
122 printf -- "-- Version bumped to v$$newVer in source files and package.json (only just-now updated files were printed above, if any).\n Describe changes in CHANGELOG.md ('make release' will prompt for it).\n To update the read-me file, run 'make update-readme' (also happens during 'make release').\n"
124 # make release [VER=<newVerSpec>] [NOTEST=1]
125 # Increments the version number, runs tests, then commits and tags, pushes to origin, prompts to publish to the npm-registry; NOTEST=1 skips tests.
126 # VER=<newVerSpec> is mandatory, unless the version number in package.json is ahead of the latest Git version tag.
128 release: _need-origin _need-npm-credentials _need-master-branch _need-clean-ws-or-no-untracked-files version test
129 @newVer=`json -f package.json version` || exit; [[ $$newVer == *-* ]] && isPreRelease=1 || isPreRelease=0; \
130 echo '-- Opening changelog...'; \
131 $(EDITOR) CHANGELOG.md; \
132 { grep -Eq "\bv$${newVer//./\.}[^[:digit:]-]" CHANGELOG.md && ! grep -E '(^|[[:blank:]])\?\?\?([[:blank:]]|$$)' CHANGELOG.md; } || { echo "ABORTED: No changelog entries provided for new version v$$newVer." >&2; exit 2; }; \
133 commitMsg="v$$newVer"$$'\n'"`sed -n '/\*\*'"v$$newVer"'\*\*/,/^\* /p' CHANGELOG.md | sed '1d;$$d'`"; \
134 echo "-- Updating README.md..."; \
135 $(MAKE) -f $(lastword $(MAKEFILE_LIST)) update-license-year update-readme || exit; \
136 echo '-- Opening README.md for final inspection...'; \
137 $(EDITOR) README.md; \
138 grep -E '(^|[[:blank:]])\?\?\?([[:blank:]]|$$)' README.md && { echo "ABORTED: README.md still contains '???', the placeholder for missing information." >&2; exit 2; }; \
139 read -re -p "Ready to COMMIT, TAG, PUSH$$([[ `json -f package.json private` != 'true' ]] && echo ", and PUBLISH (prompted for separately)") (y/N)?: " response && [[ "$$response" =~ [yY] ]] || { echo 'Aborted.' >&2; exit 2; }; \
140 echo '-- Committing...'; \
141 git add --update . || exit; \
142 [[ -z $$(git status --porcelain || echo no) ]] && echo "-- (Nothing to commit.)" || { git commit -m "$$commitMsg" || exit; echo "-- v$$newVer committed."; }; \
143 git tag -f -a -m "$$commitMsg" "v$$newVer" || exit; { git tag -f "`(( isPreRelease )) && printf 'pre' || printf 'stable'`" || exit; }; \
144 echo "-- Tag v$$newVer created."; \
145 git push origin master || exit; git push -f origin master --tags; \
146 echo "-- v$$newVer pushed to origin."; \
147 if [[ `json -f package.json private` != 'true' ]]; then \
148 latestPreReleaseTag='pre'; \
149 printf "=== About to PUBLISH TO npm REGISTRY as `(( isPreRelease )) && printf 'PRE-RELEASE' || printf 'LATEST'` version:\n\t**`json -f package.json name`@$$newVer**\n===\nType 'publish' to proceed; anything else to abort: " && read -er response; \
150 [[ "$$response" == 'publish' ]] || { echo 'Aborted. Run `npm publish` on demand.' >&2; exit 2; }; \
151 { (( isPreRelease )) && npm publish --tag "$$latestPreReleaseTag" || npm publish; } || exit; \
152 echo "-- Published to npm`(( isPreRelease )) && printf " and tagged with '$$latestPreReleaseTag' to mark the latest pre-release"`."; \
154 echo "-- (Package marked as private; not publishing to npm registry.)"; \
158 # Updates README.md as follows:
159 # - Replaces the '## Usage' chapter with the command-line help output by this package's CLI, if applicable.
160 # - Replaces the '### License' chapter with the contents of LICENSE.md
161 # - Replaces the '### npm Dependencies' chapter with the current list of dependencies.
162 # - Replaces the '## Changelog' chapter with the contents of CHANGELOG.md
163 # - Finally, places an auto-generated TOC at the top, if configured.
164 .PHONY: update-readme
165 update-readme: _update-readme-usage _update-readme-license _update-readme-dependencies _update-readme-changelog update-toc
166 @[[ '$(MAKECMDGOALS)' == 'update-readme' ]] && grep -E '(^|[[:blank:]])\?\?\?([[:blank:]]|$$)' README.md && echo "WARNING: README.md still contains '???', the placeholder for missing information." >&2; \
167 echo "-- README.md updated."
169 # Updates the TOC in README.md - there is *generally* no need to call this *directly*, because the TOC is updated as part of the 'release' target.
170 # However, when *toggling* the inclusion of a TOC, this target is called *directly* to:
171 # - insert a TOC after just having turned inclusion ON
172 # - remove an existing TOC after just having turned inclusion OFF
173 # !! Note that a \n is prepended to the title to work around a npmjs.com rendering bug: without it, doctoc's comments would directly abut the title, which unexepctedly disables Markdown rendering (as of 31 May 2015).
176 @if [[ "`json -f package.json net_same2u.make_pkg.tocOn`" == 'true' ]]; then \
177 doctoc --title $$'\n'"`json -f package.json net_same2u.make_pkg.tocTitle`" README.md >/dev/null || exit; \
178 [[ '$(MAKECMDGOALS)' == 'update-toc' ]] && echo "TOC in README.md updated." || :; \
179 elif [[ '$(MAKECMDGOALS)' == 'update-toc' ]]; then \
180 replace --count --multiline=false '<!-- START doctoc.[^>]*-->[\s\S]*?<!-- END doctoc[^>]*-->\n*' '' README.md | grep -Fq ' (1)' && \
181 echo "TOC removed from README.md." || \
182 echo "WARNING: Tried to remove TOC from README.md, but found none." >&2; \
187 @isOn=$$([[ "`json -f package.json net_same2u.make_pkg.tocOn`" == 'true' ]] && printf 1 || printf 0); \
188 nowState=`(( isOn )) && printf 'ON' || printf 'OFF'`; otherState=`(( isOn )) && printf 'OFF' || printf 'ON'`; \
189 echo "Inclusion of an auto-updating TOC for README.md is currently $$nowState."; \
190 read -re -p "Turn it $$otherState (y/N)?: " response && [[ "$$response" =~ [yY] ]] || { exit 0; }; \
191 json -I -f package.json -e 'this.net_same2u || (this.net_same2u = {}); this.net_same2u.make_pkg || (this.net_same2u.make_pkg = {}); this.net_same2u.make_pkg.tocOn = '`(( isOn )) && printf 'false' || printf 'true'`'; this.net_same2u.make_pkg.tocTitle || (this.net_same2u.make_pkg.tocTitle = "**Contents**")'; \
192 $(MAKE) -f $(lastword $(MAKEFILE_LIST)) update-toc || exit
195 # Updates LICENSE.md if the stated calendar year (e.g., '2015') / the end point in a calendar-year range (e.g., '2014-2015')
196 # lies in the past; E.g., if the current calendary year is 2016, the first example is updated to '2015-2016', and the second
197 # one to '2014-2016'.
198 .PHONY: update-license-year
200 @f='LICENSE.md'; thisYear=`date +%Y`; yearRange=`sed -n 's/.*(c) \([0-9]\{4\}\)\(-[0-9]\{4\}\)\{0,1\}.*/\1\2/p' "$$f"`; \
201 [[ -n $$yearRange ]] || { echo "Failed to extract calendar year(s) from '$$f'." >&2; exit 1; }; laterYear=$${yearRange#*-}; \
202 if (( laterYear < thisYear )); then \
203 replace -s '(\(c\) )([0-9]{4})(-[0-9]{4})?' '$$1$$2-'"$$thisYear" "$$f" || exit; \
204 echo "NOTE: '$$f' updated to reflect current calendar year, $$thisYear."; \
205 elif [[ '$(MAKECMDGOALS)' == 'update-license-year' ]]; then \
206 echo "('$$f' calendar year(s) are up-to-date: $$yearRange)"; \
209 # --------- Aux. targets
211 # If applicable, replaces the usage read-me chapter with the current CLI help output,
212 # enclosed in a fenced codeblock and preceded by '$ <cmd> --help'.
213 # Replacement is attempted if the project at hand has a (at least one) CLI, as defined in the 'bin' key in package.json.
214 # is an *object* that has (at least 1) property (rather than containing a string-scalar value that implies the package name as the CLI name).
215 # - If 'bin' has *multiple* properties, the *1st* is the one whose usage info is to be used.
216 # To change this, modify CLI_HELP_CMD in the shell command below.
217 .PHONY: _update-readme-usage
218 # The arguments to pass to the CLI to have it output its help.
219 CLI_HELP_ARGS:= --help
220 # Note that the recipe exits right away if no CLIs are found in 'package.json'.
221 # TO DISABLE THIS RULE, REMOVE ALL OF ITS RECIPE LINES.
222 _update-readme-usage:
223 @read -r cliName cliPath < <(json -f package.json bin | json -Ma key value | head -n 1) || exit 0; \
224 CLI_HELP_CMD=( "$$cliPath" $(CLI_HELP_ARGS) ); \
225 CLI_HELP_CMD_DISPLAY=( "$${CLI_HELP_CMD[@]}" ); CLI_HELP_CMD_DISPLAY[0]="$$cliName"; \
226 newText="$${CLI_HELP_CMD_DISPLAY[@]}"$$'\n\n'"$$( "$${CLI_HELP_CMD[@]}" )" || { echo "Failed to update read-me chapter: usage: invoking CLI help failed: $${CLI_HELP_CMD[@]}" >&2; exit 1; }; \
227 newText="$${newText//\$$/$$\$$}"; \
228 newText="$${newText//~/\~}"; \
229 replace --count --quiet --multiline=false '(\n)(<!-- DO NOT EDIT .*usage.*?-->\n\s*?\n```nohighlight\n\$$ )[\s\S]*?(\n```\n|$$)' '$$1$$2'"$$newText"'$$3' README.md | grep -Fq ' (1)' || { echo "Failed to update read-me chapter: usage." >&2; exit 1; }
230 # !! REGRETTABLY, the ``` sequences in the line above break syntax coloring for the rest of the file in Sublime Text 3 - ?? unclear, how to work around that.
232 # - Replaces the '## License' chapter with the contents of LICENSE.md
233 .PHONY: _update-readme-license
234 # TO DISABLE THIS RULE, REMOVE ALL OF ITS RECIPE LINES.
235 _update-readme-license:
236 @newText=$$'\n'"$$(< LICENSE.md)"$$'\n'; \
237 newText="$${newText//\$$/$$\$$}"; \
238 replace --count --quiet --multiline=false '(^|\n)(#+ License\n)[\s\S]*?(\n([ \t]*<!-- .*? -->\s*?\n)?#|$$)' '$$1$$2'"$$newText"'$$3' README.md | grep -Fq ' (1)' || { echo "Failed to update read-me chapter: license." >&2; exit 1; }
240 # - Replaces the dependencies chapter with the current list of dependencies.
241 .PHONY: _update-readme-dependencies
242 # A regex that matches the chapter heading to replace in README.md; watch for unintentional trailing whitespace. '#' must be represented as '\#'.
243 README_HEADING_DEPENDENCIES := \#+ npm dependencies
244 # TO DISABLE THIS RULE, REMOVE ALL OF ITS RECIPE LINES.
245 _update-readme-dependencies:
247 keys=( dependencies peerDependencies devDependencies optionalDependencies ); \
248 qualifiers=( '' '(P)' '(D)' '(O)'); \
250 for key in "$${keys[@]}"; do \
251 json -f ./package.json $$key | json -ka | { \
252 while read -r pn; do \
253 hp=$$(json -f "./node_modules/$$pn/package.json" homepage); \
254 echo "* [$$pn$${qualifiers[i]:+ $${qualifiers[i]}}]($$hp)"; \
259 [[ -n $$newText ]] || { echo "Failed to determine npm dependencies." >&2; exit 1; }; \
260 newText="$${newText//\$$/$$\$$}"; \
261 replace --count --quiet --multiline=false '(^|\n)($(README_HEADING_DEPENDENCIES)\n)[\s\S]*?(\n([ \t]*<!-- .*? -->\s*?\n)?#|$$)' '$$1$$2'"$$newText"'$$3' README.md | grep -Fq ' (1)' || { echo "Failed to update read-me chapter: npm dependencies." >&2; exit 1; }
263 # - Replaces the changelog chapter with the contents of CHANGELOG.md
264 .PHONY: _update-readme-changelog
265 # A regex that matches the chapter heading to replace in README.md; watch for unintentional trailing whitespace. '#' must be represented as '\#'.
266 README_HEADING_CHANGELOG := \#+ Changelog
267 # TO DISABLE THIS RULE, REMOVE ALL OF ITS RECIPE LINES.
268 _update-readme-changelog:
269 @newText=$$'\n'"$$(tail -n +3 CHANGELOG.md)"$$'\n'; \
270 newText="$${newText//\$$/$$\$$}"; \
271 replace --count --quiet --multiline=false '(^|\n)($(README_HEADING_CHANGELOG)\n)[\s\S]*?(\n([ \t]*<!-- .*? -->\s*?\n)?#|$$)' '$$1$$2'"$$newText"'$$3' README.md | grep -Fq ' (1)' || { echo "Failed to update read-me chapter: changelog." >&2; exit 1; }
273 .PHONY: _need-master-branch
275 @[[ `git symbolic-ref --short HEAD` == 'master' ]] || { echo 'Please release from the master branch only.' >&2; exit 2; }
277 # Ensures that the git workspace is clean or contains no untracked files - any tracked files are implicitly added to the index.
278 .PHONY: _need-clean-ws-or-no-untracked-files
279 _need-clean-ws-or-no-untracked-files:
280 @git add --update . || exit
281 @[[ -z $$(git status --porcelain | awk -F'\0' '$$2 != " " { print $$2 }') ]] || { echo "Workspace must either be clean or contain no untracked files; please add untracked files to the index first (e.g., \`git add .\`) or delete them." >&2; exit 2; }
283 # Ensure that a remote git repo named 'origin' is defined.
286 @git remote | grep -Fqx 'origin' || { echo "ERROR: Remote git repo 'origin' must be defined." >&2; exit 2; }
288 # Unless the package is marked private, ensure that npm credentials have been saved.
289 .PHONY: _need-npm-credentials
290 _need-npm-credentials:
291 @[[ `json -f package.json private` == 'true' ]] && exit 0; \
292 grep -Eq '^//registry.npmjs.org/:_password' ~/.npmrc || { echo "ERROR: npm-registry credentials not found. Please log in with 'npm login' in order to enable publishing." >&2; exit 2; }; \