erlang.mk 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563
  1. # Copyright (c) 2013-2015, Loïc Hoguin <essen@ninenines.eu>
  2. #
  3. # Permission to use, copy, modify, and/or distribute this software for any
  4. # purpose with or without fee is hereby granted, provided that the above
  5. # copyright notice and this permission notice appear in all copies.
  6. #
  7. # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  8. # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  9. # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  10. # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  11. # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  12. # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  13. # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  14. .PHONY: all app deps search rel docs install-docs check tests clean distclean help erlang-mk
  15. ERLANG_MK_FILENAME := $(realpath $(lastword $(MAKEFILE_LIST)))
  16. ERLANG_MK_VERSION = 2.0.0-pre.1-38-gbd6e006-dirty
  17. # Core configuration.
  18. PROJECT ?= $(notdir $(CURDIR))
  19. PROJECT := $(strip $(PROJECT))
  20. PROJECT_VERSION ?= rolling
  21. # Verbosity.
  22. V ?= 0
  23. verbose_0 = @
  24. verbose = $(verbose_$(V))
  25. gen_verbose_0 = @echo " GEN " $@;
  26. gen_verbose = $(gen_verbose_$(V))
  27. # Temporary files directory.
  28. ERLANG_MK_TMP ?= $(CURDIR)/.erlang.mk
  29. export ERLANG_MK_TMP
  30. # "erl" command.
  31. ERL = erl +A0 -noinput -boot start_clean
  32. # Platform detection.
  33. ifeq ($(PLATFORM),)
  34. UNAME_S := $(shell uname -s)
  35. ifeq ($(UNAME_S),Linux)
  36. PLATFORM = linux
  37. else ifeq ($(UNAME_S),Darwin)
  38. PLATFORM = darwin
  39. else ifeq ($(UNAME_S),SunOS)
  40. PLATFORM = solaris
  41. else ifeq ($(UNAME_S),GNU)
  42. PLATFORM = gnu
  43. else ifeq ($(UNAME_S),FreeBSD)
  44. PLATFORM = freebsd
  45. else ifeq ($(UNAME_S),NetBSD)
  46. PLATFORM = netbsd
  47. else ifeq ($(UNAME_S),OpenBSD)
  48. PLATFORM = openbsd
  49. else ifeq ($(UNAME_S),DragonFly)
  50. PLATFORM = dragonfly
  51. else ifeq ($(shell uname -o),Msys)
  52. PLATFORM = msys2
  53. else
  54. $(error Unable to detect platform. Please open a ticket with the output of uname -a.)
  55. endif
  56. export PLATFORM
  57. endif
  58. # Core targets.
  59. .NOTPARALLEL:
  60. all:: deps app rel
  61. # Noop to avoid a Make warning when there's nothing to do.
  62. rel::
  63. $(verbose) echo -n
  64. check:: clean app tests
  65. clean:: clean-crashdump
  66. clean-crashdump:
  67. ifneq ($(wildcard erl_crash.dump),)
  68. $(gen_verbose) rm -f erl_crash.dump
  69. endif
  70. distclean:: clean distclean-tmp
  71. distclean-tmp:
  72. $(gen_verbose) rm -rf $(ERLANG_MK_TMP)
  73. help::
  74. $(verbose) printf "%s\n" \
  75. "erlang.mk (version $(ERLANG_MK_VERSION)) is distributed under the terms of the ISC License." \
  76. "Copyright (c) 2013-2015 Loïc Hoguin <essen@ninenines.eu>" \
  77. "" \
  78. "Usage: [V=1] $(MAKE) [target]..." \
  79. "" \
  80. "Core targets:" \
  81. " all Run deps, app and rel targets in that order" \
  82. " app Compile the project" \
  83. " deps Fetch dependencies (if needed) and compile them" \
  84. " search q=... Search for a package in the built-in index" \
  85. " rel Build a release for this project, if applicable" \
  86. " docs Build the documentation for this project" \
  87. " install-docs Install the man pages for this project" \
  88. " check Compile and run all tests and analysis for this project" \
  89. " tests Run the tests for this project" \
  90. " clean Delete temporary and output files from most targets" \
  91. " distclean Delete all temporary and output files" \
  92. " help Display this help and exit" \
  93. " erlang-mk Update erlang.mk to the latest version"
  94. # Core functions.
  95. empty :=
  96. space := $(empty) $(empty)
  97. tab := $(empty) $(empty)
  98. comma := ,
  99. define newline
  100. endef
  101. define comma_list
  102. $(subst $(space),$(comma),$(strip $(1)))
  103. endef
  104. # Adding erlang.mk to make Erlang scripts who call init:get_plain_arguments() happy.
  105. define erlang
  106. $(ERL) $(2) -pz $(ERLANG_MK_TMP)/rebar/ebin -eval "$(subst $(newline),,$(subst ",\",$(1)))" -- erlang.mk
  107. endef
  108. ifeq ($(PLATFORM),msys2)
  109. core_native_path = $(subst \,\\\\,$(shell cygpath -w $1))
  110. else
  111. core_native_path = $1
  112. endif
  113. ifeq ($(shell which wget 2>/dev/null | wc -l), 1)
  114. define core_http_get
  115. wget --no-check-certificate -O $(1) $(2)|| rm $(1)
  116. endef
  117. else
  118. define core_http_get.erl
  119. ssl:start(),
  120. inets:start(),
  121. case httpc:request(get, {"$(2)", []}, [{autoredirect, true}], []) of
  122. {ok, {{_, 200, _}, _, Body}} ->
  123. case file:write_file("$(1)", Body) of
  124. ok -> ok;
  125. {error, R1} -> halt(R1)
  126. end;
  127. {error, R2} ->
  128. halt(R2)
  129. end,
  130. halt(0).
  131. endef
  132. define core_http_get
  133. $(call erlang,$(call core_http_get.erl,$(call core_native_path,$1),$2))
  134. endef
  135. endif
  136. core_eq = $(and $(findstring $(1),$(2)),$(findstring $(2),$(1)))
  137. core_find = $(if $(wildcard $1),$(shell find $(1:%/=%) -type f -name $(subst *,\*,$2)))
  138. core_lc = $(subst A,a,$(subst B,b,$(subst C,c,$(subst D,d,$(subst E,e,$(subst F,f,$(subst G,g,$(subst H,h,$(subst I,i,$(subst J,j,$(subst K,k,$(subst L,l,$(subst M,m,$(subst N,n,$(subst O,o,$(subst P,p,$(subst Q,q,$(subst R,r,$(subst S,s,$(subst T,t,$(subst U,u,$(subst V,v,$(subst W,w,$(subst X,x,$(subst Y,y,$(subst Z,z,$(1)))))))))))))))))))))))))))
  139. core_ls = $(filter-out $(1),$(shell echo $(1)))
  140. # @todo Use a solution that does not require using perl.
  141. core_relpath = $(shell perl -e 'use File::Spec; print File::Spec->abs2rel(@ARGV) . "\n"' $1 $2)
  142. # Automated update.
  143. ERLANG_MK_REPO ?= https://github.com/ninenines/erlang.mk
  144. ERLANG_MK_COMMIT ?=
  145. ERLANG_MK_BUILD_CONFIG ?= build.config
  146. ERLANG_MK_BUILD_DIR ?= .erlang.mk.build
  147. erlang-mk:
  148. git clone $(ERLANG_MK_REPO) $(ERLANG_MK_BUILD_DIR)
  149. if [ -f $(ERLANG_MK_BUILD_CONFIG) ]; then cp $(ERLANG_MK_BUILD_CONFIG) $(ERLANG_MK_BUILD_DIR)/build.config; fi
  150. cd $(ERLANG_MK_BUILD_DIR) && $(if $(ERLANG_MK_COMMIT),git checkout $(ERLANG_MK_COMMIT) &&) $(MAKE)
  151. cp $(ERLANG_MK_BUILD_DIR)/erlang.mk ./erlang.mk
  152. rm -rf $(ERLANG_MK_BUILD_DIR)
  153. # The erlang.mk package index is bundled in the default erlang.mk build.
  154. # Search for the string "copyright" to skip to the rest of the code.
  155. # Copyright (c) 2013-2015, Loïc Hoguin <essen@ninenines.eu>
  156. # This file is part of erlang.mk and subject to the terms of the ISC License.
  157. .PHONY: distclean-deps
  158. # Configuration.
  159. ifdef OTP_DEPS
  160. $(warning The variable OTP_DEPS is deprecated in favor of LOCAL_DEPS.)
  161. endif
  162. IGNORE_DEPS ?=
  163. export IGNORE_DEPS
  164. APPS_DIR ?= $(CURDIR)/apps
  165. export APPS_DIR
  166. DEPS_DIR ?= $(CURDIR)/deps
  167. export DEPS_DIR
  168. REBAR_DEPS_DIR = $(DEPS_DIR)
  169. export REBAR_DEPS_DIR
  170. dep_name = $(if $(dep_$(1)),$(1),$(if $(pkg_$(1)_name),$(pkg_$(1)_name),$(1)))
  171. dep_repo = $(patsubst git://github.com/%,https://github.com/%, \
  172. $(if $(dep_$(1)),$(word 2,$(dep_$(1))),$(pkg_$(1)_repo)))
  173. dep_commit = $(if $(dep_$(1)_commit),$(dep_$(1)_commit),$(if $(dep_$(1)),$(word 3,$(dep_$(1))),$(pkg_$(1)_commit)))
  174. ALL_APPS_DIRS = $(if $(wildcard $(APPS_DIR)/),$(filter-out $(APPS_DIR),$(shell find $(APPS_DIR) -maxdepth 1 -type d)))
  175. ALL_DEPS_DIRS = $(addprefix $(DEPS_DIR)/,$(foreach dep,$(filter-out $(IGNORE_DEPS),$(BUILD_DEPS) $(DEPS)),$(call dep_name,$(dep))))
  176. ifeq ($(filter $(APPS_DIR) $(DEPS_DIR),$(subst :, ,$(ERL_LIBS))),)
  177. ifeq ($(ERL_LIBS),)
  178. ERL_LIBS = $(APPS_DIR):$(DEPS_DIR)
  179. else
  180. ERL_LIBS := $(ERL_LIBS):$(APPS_DIR):$(DEPS_DIR)
  181. endif
  182. endif
  183. export ERL_LIBS
  184. export NO_AUTOPATCH
  185. # Verbosity.
  186. dep_verbose_0 = @echo " DEP " $(1);
  187. dep_verbose = $(dep_verbose_$(V))
  188. # Core targets.
  189. ifneq ($(SKIP_DEPS),)
  190. deps::
  191. else
  192. deps:: $(ALL_DEPS_DIRS)
  193. ifndef IS_APP
  194. $(verbose) for dep in $(ALL_APPS_DIRS) ; do \
  195. $(MAKE) -C $$dep IS_APP=1 || exit $$?; \
  196. done
  197. endif
  198. ifneq ($(IS_DEP),1)
  199. $(verbose) rm -f $(ERLANG_MK_TMP)/deps.log
  200. endif
  201. $(verbose) mkdir -p $(ERLANG_MK_TMP)
  202. $(verbose) for dep in $(ALL_DEPS_DIRS) ; do \
  203. if grep -qs ^$$dep$$ $(ERLANG_MK_TMP)/deps.log; then \
  204. echo -n; \
  205. else \
  206. echo $$dep >> $(ERLANG_MK_TMP)/deps.log; \
  207. if [ -f $$dep/GNUmakefile ] || [ -f $$dep/makefile ] || [ -f $$dep/Makefile ]; then \
  208. $(MAKE) -C $$dep IS_DEP=1 || exit $$?; \
  209. else \
  210. echo "Error: No Makefile to build dependency $$dep."; \
  211. exit 2; \
  212. fi \
  213. fi \
  214. done
  215. endif
  216. # Deps related targets.
  217. # @todo rename GNUmakefile and makefile into Makefile first, if they exist
  218. # While Makefile file could be GNUmakefile or makefile,
  219. # in practice only Makefile is needed so far.
  220. define dep_autopatch
  221. if [ -f $(DEPS_DIR)/$(1)/Makefile ]; then \
  222. if [ 0 != `grep -c "include ../\w*\.mk" $(DEPS_DIR)/$(1)/Makefile` ]; then \
  223. $(call dep_autopatch2,$(1)); \
  224. elif [ 0 != `grep -ci rebar $(DEPS_DIR)/$(1)/Makefile` ]; then \
  225. $(call dep_autopatch2,$(1)); \
  226. elif [ -n "`find $(DEPS_DIR)/$(1)/ -type f -name \*.mk -not -name erlang.mk -exec grep -i rebar '{}' \;`" ]; then \
  227. $(call dep_autopatch2,$(1)); \
  228. else \
  229. if [ -f $(DEPS_DIR)/$(1)/erlang.mk ]; then \
  230. $(call erlang,$(call dep_autopatch_appsrc.erl,$(1))); \
  231. $(call dep_autopatch_erlang_mk,$(1)); \
  232. else \
  233. $(call erlang,$(call dep_autopatch_app.erl,$(1))); \
  234. fi \
  235. fi \
  236. else \
  237. if [ ! -d $(DEPS_DIR)/$(1)/src/ ]; then \
  238. $(call dep_autopatch_noop,$(1)); \
  239. else \
  240. $(call dep_autopatch2,$(1)); \
  241. fi \
  242. fi
  243. endef
  244. define dep_autopatch2
  245. $(call erlang,$(call dep_autopatch_appsrc.erl,$(1))); \
  246. if [ -f $(DEPS_DIR)/$(1)/rebar.config -o -f $(DEPS_DIR)/$(1)/rebar.config.script ]; then \
  247. $(call dep_autopatch_fetch_rebar); \
  248. $(call dep_autopatch_rebar,$(1)); \
  249. else \
  250. $(call dep_autopatch_gen,$(1)); \
  251. fi
  252. endef
  253. define dep_autopatch_noop
  254. printf "noop:\n" > $(DEPS_DIR)/$(1)/Makefile
  255. endef
  256. # Overwrite erlang.mk with the current file by default.
  257. ifeq ($(NO_AUTOPATCH_ERLANG_MK),)
  258. define dep_autopatch_erlang_mk
  259. echo "include $(call core_relpath,$(dir $(ERLANG_MK_FILENAME)),$(DEPS_DIR)/app)/erlang.mk" \
  260. > $(DEPS_DIR)/$1/erlang.mk
  261. endef
  262. else
  263. define dep_autopatch_erlang_mk
  264. echo -n
  265. endef
  266. endif
  267. define dep_autopatch_gen
  268. printf "%s\n" \
  269. "ERLC_OPTS = +debug_info" \
  270. "include ../../erlang.mk" > $(DEPS_DIR)/$(1)/Makefile
  271. endef
  272. define dep_autopatch_fetch_rebar
  273. mkdir -p $(ERLANG_MK_TMP); \
  274. if [ ! -d $(ERLANG_MK_TMP)/rebar ]; then \
  275. git clone -q -n -- https://github.com/rebar/rebar $(ERLANG_MK_TMP)/rebar; \
  276. cd $(ERLANG_MK_TMP)/rebar; \
  277. git checkout -q 791db716b5a3a7671e0b351f95ddf24b848ee173; \
  278. $(MAKE); \
  279. cd -; \
  280. fi
  281. endef
  282. define dep_autopatch_rebar
  283. if [ -f $(DEPS_DIR)/$(1)/Makefile ]; then \
  284. mv $(DEPS_DIR)/$(1)/Makefile $(DEPS_DIR)/$(1)/Makefile.orig.mk; \
  285. fi; \
  286. $(call erlang,$(call dep_autopatch_rebar.erl,$(1))); \
  287. rm -f $(DEPS_DIR)/$(1)/ebin/$(1).app
  288. endef
  289. define dep_autopatch_rebar.erl
  290. application:load(rebar),
  291. application:set_env(rebar, log_level, debug),
  292. Conf1 = case file:consult("$(call core_native_path,$(DEPS_DIR)/$1/rebar.config)") of
  293. {ok, Conf0} -> Conf0;
  294. _ -> []
  295. end,
  296. {Conf, OsEnv} = fun() ->
  297. case filelib:is_file("$(call core_native_path,$(DEPS_DIR)/$1/rebar.config.script)") of
  298. false -> {Conf1, []};
  299. true ->
  300. Bindings0 = erl_eval:new_bindings(),
  301. Bindings1 = erl_eval:add_binding('CONFIG', Conf1, Bindings0),
  302. Bindings = erl_eval:add_binding('SCRIPT', "$(call core_native_path,$(DEPS_DIR)/$1/rebar.config.script)", Bindings1),
  303. Before = os:getenv(),
  304. {ok, Conf2} = file:script("$(call core_native_path,$(DEPS_DIR)/$1/rebar.config.script)", Bindings),
  305. {Conf2, lists:foldl(fun(E, Acc) -> lists:delete(E, Acc) end, os:getenv(), Before)}
  306. end
  307. end(),
  308. Write = fun (Text) ->
  309. file:write_file("$(call core_native_path,$(DEPS_DIR)/$1/Makefile)", Text, [append])
  310. end,
  311. Escape = fun (Text) ->
  312. re:replace(Text, "\\\\$$$$", "\$$$$$$$$", [global, {return, list}])
  313. end,
  314. Write("IGNORE_DEPS += edown eper eunit_formatters meck node_package "
  315. "rebar_lock_deps_plugin rebar_vsn_plugin reltool_util\n"),
  316. Write("C_SRC_DIR = /path/do/not/exist\n"),
  317. Write("C_SRC_TYPE = rebar\n"),
  318. Write("DRV_CFLAGS = -fPIC\nexport DRV_CFLAGS\n"),
  319. Write(["ERLANG_ARCH = ", rebar_utils:wordsize(), "\nexport ERLANG_ARCH\n"]),
  320. fun() ->
  321. Write("ERLC_OPTS = +debug_info\nexport ERLC_OPTS\n"),
  322. case lists:keyfind(erl_opts, 1, Conf) of
  323. false -> ok;
  324. {_, ErlOpts} ->
  325. lists:foreach(fun
  326. ({d, D}) ->
  327. Write("ERLC_OPTS += -D" ++ atom_to_list(D) ++ "=1\n");
  328. ({i, I}) ->
  329. Write(["ERLC_OPTS += -I ", I, "\n"]);
  330. ({platform_define, Regex, D}) ->
  331. case rebar_utils:is_arch(Regex) of
  332. true -> Write("ERLC_OPTS += -D" ++ atom_to_list(D) ++ "=1\n");
  333. false -> ok
  334. end;
  335. ({parse_transform, PT}) ->
  336. Write("ERLC_OPTS += +'{parse_transform, " ++ atom_to_list(PT) ++ "}'\n");
  337. (_) -> ok
  338. end, ErlOpts)
  339. end,
  340. Write("\n")
  341. end(),
  342. fun() ->
  343. File = case lists:keyfind(deps, 1, Conf) of
  344. false -> [];
  345. {_, Deps} ->
  346. [begin case case Dep of
  347. {N, S} when is_atom(N), is_list(S) -> {N, {hex, S}};
  348. {N, S} when is_tuple(S) -> {N, S};
  349. {N, _, S} -> {N, S};
  350. {N, _, S, _} -> {N, S};
  351. _ -> false
  352. end of
  353. false -> ok;
  354. {Name, Source} ->
  355. {Method, Repo, Commit} = case Source of
  356. {hex, V} -> {hex, V, undefined};
  357. {git, R} -> {git, R, master};
  358. {M, R, {branch, C}} -> {M, R, C};
  359. {M, R, {ref, C}} -> {M, R, C};
  360. {M, R, {tag, C}} -> {M, R, C};
  361. {M, R, C} -> {M, R, C}
  362. end,
  363. Write(io_lib:format("DEPS += ~s\ndep_~s = ~s ~s ~s~n", [Name, Name, Method, Repo, Commit]))
  364. end end || Dep <- Deps]
  365. end
  366. end(),
  367. fun() ->
  368. case lists:keyfind(erl_first_files, 1, Conf) of
  369. false -> ok;
  370. {_, Files} ->
  371. Names = [[" ", case lists:reverse(F) of
  372. "lre." ++ Elif -> lists:reverse(Elif);
  373. Elif -> lists:reverse(Elif)
  374. end] || "src/" ++ F <- Files],
  375. Write(io_lib:format("COMPILE_FIRST +=~s\n", [Names]))
  376. end
  377. end(),
  378. FindFirst = fun(F, Fd) ->
  379. case io:parse_erl_form(Fd, undefined) of
  380. {ok, {attribute, _, compile, {parse_transform, PT}}, _} ->
  381. [PT, F(F, Fd)];
  382. {ok, {attribute, _, compile, CompileOpts}, _} when is_list(CompileOpts) ->
  383. case proplists:get_value(parse_transform, CompileOpts) of
  384. undefined -> [F(F, Fd)];
  385. PT -> [PT, F(F, Fd)]
  386. end;
  387. {ok, {attribute, _, include, Hrl}, _} ->
  388. case file:open("$(call core_native_path,$(DEPS_DIR)/$1/include/)" ++ Hrl, [read]) of
  389. {ok, HrlFd} -> [F(F, HrlFd), F(F, Fd)];
  390. _ ->
  391. case file:open("$(call core_native_path,$(DEPS_DIR)/$1/src/)" ++ Hrl, [read]) of
  392. {ok, HrlFd} -> [F(F, HrlFd), F(F, Fd)];
  393. _ -> [F(F, Fd)]
  394. end
  395. end;
  396. {ok, {attribute, _, include_lib, "$(1)/include/" ++ Hrl}, _} ->
  397. {ok, HrlFd} = file:open("$(call core_native_path,$(DEPS_DIR)/$1/include/)" ++ Hrl, [read]),
  398. [F(F, HrlFd), F(F, Fd)];
  399. {ok, {attribute, _, include_lib, Hrl}, _} ->
  400. case file:open("$(call core_native_path,$(DEPS_DIR)/$1/include/)" ++ Hrl, [read]) of
  401. {ok, HrlFd} -> [F(F, HrlFd), F(F, Fd)];
  402. _ -> [F(F, Fd)]
  403. end;
  404. {ok, {attribute, _, import, {Imp, _}}, _} ->
  405. case file:open("$(call core_native_path,$(DEPS_DIR)/$1/src/)" ++ atom_to_list(Imp) ++ ".erl", [read]) of
  406. {ok, ImpFd} -> [Imp, F(F, ImpFd), F(F, Fd)];
  407. _ -> [F(F, Fd)]
  408. end;
  409. {eof, _} ->
  410. file:close(Fd),
  411. [];
  412. _ ->
  413. F(F, Fd)
  414. end
  415. end,
  416. fun() ->
  417. ErlFiles = filelib:wildcard("$(call core_native_path,$(DEPS_DIR)/$1/src/)*.erl"),
  418. First0 = lists:usort(lists:flatten([begin
  419. {ok, Fd} = file:open(F, [read]),
  420. FindFirst(FindFirst, Fd)
  421. end || F <- ErlFiles])),
  422. First = lists:flatten([begin
  423. {ok, Fd} = file:open("$(call core_native_path,$(DEPS_DIR)/$1/src/)" ++ atom_to_list(M) ++ ".erl", [read]),
  424. FindFirst(FindFirst, Fd)
  425. end || M <- First0, lists:member("$(call core_native_path,$(DEPS_DIR)/$1/src/)" ++ atom_to_list(M) ++ ".erl", ErlFiles)]) ++ First0,
  426. Write(["COMPILE_FIRST +=", [[" ", atom_to_list(M)] || M <- First,
  427. lists:member("$(call core_native_path,$(DEPS_DIR)/$1/src/)" ++ atom_to_list(M) ++ ".erl", ErlFiles)], "\n"])
  428. end(),
  429. Write("\n\nrebar_dep: preprocess pre-deps deps pre-app app\n"),
  430. Write("\npreprocess::\n"),
  431. Write("\npre-deps::\n"),
  432. Write("\npre-app::\n"),
  433. PatchHook = fun(Cmd) ->
  434. case Cmd of
  435. "make -C" ++ Cmd1 -> "$$$$\(MAKE) -C" ++ Escape(Cmd1);
  436. "gmake -C" ++ Cmd1 -> "$$$$\(MAKE) -C" ++ Escape(Cmd1);
  437. "make " ++ Cmd1 -> "$$$$\(MAKE) -f Makefile.orig.mk " ++ Escape(Cmd1);
  438. "gmake " ++ Cmd1 -> "$$$$\(MAKE) -f Makefile.orig.mk " ++ Escape(Cmd1);
  439. _ -> Escape(Cmd)
  440. end
  441. end,
  442. fun() ->
  443. case lists:keyfind(pre_hooks, 1, Conf) of
  444. false -> ok;
  445. {_, Hooks} ->
  446. [case H of
  447. {'get-deps', Cmd} ->
  448. Write("\npre-deps::\n\t" ++ PatchHook(Cmd) ++ "\n");
  449. {compile, Cmd} ->
  450. Write("\npre-app::\n\tCC=$$$$\(CC) " ++ PatchHook(Cmd) ++ "\n");
  451. {Regex, compile, Cmd} ->
  452. case rebar_utils:is_arch(Regex) of
  453. true -> Write("\npre-app::\n\tCC=$$$$\(CC) " ++ PatchHook(Cmd) ++ "\n");
  454. false -> ok
  455. end;
  456. _ -> ok
  457. end || H <- Hooks]
  458. end
  459. end(),
  460. ShellToMk = fun(V) ->
  461. re:replace(re:replace(V, "(\\\\$$$$)(\\\\w*)", "\\\\1(\\\\2)", [global]),
  462. "-Werror\\\\b", "", [{return, list}, global])
  463. end,
  464. PortSpecs = fun() ->
  465. case lists:keyfind(port_specs, 1, Conf) of
  466. false ->
  467. case filelib:is_dir("$(call core_native_path,$(DEPS_DIR)/$1/c_src)") of
  468. false -> [];
  469. true ->
  470. [{"priv/" ++ proplists:get_value(so_name, Conf, "$(1)_drv.so"),
  471. proplists:get_value(port_sources, Conf, ["c_src/*.c"]), []}]
  472. end;
  473. {_, Specs} ->
  474. lists:flatten([case S of
  475. {Output, Input} -> {ShellToMk(Output), Input, []};
  476. {Regex, Output, Input} ->
  477. case rebar_utils:is_arch(Regex) of
  478. true -> {ShellToMk(Output), Input, []};
  479. false -> []
  480. end;
  481. {Regex, Output, Input, [{env, Env}]} ->
  482. case rebar_utils:is_arch(Regex) of
  483. true -> {ShellToMk(Output), Input, Env};
  484. false -> []
  485. end
  486. end || S <- Specs])
  487. end
  488. end(),
  489. PortSpecWrite = fun (Text) ->
  490. file:write_file("$(call core_native_path,$(DEPS_DIR)/$1/c_src/Makefile.erlang.mk)", Text, [append])
  491. end,
  492. case PortSpecs of
  493. [] -> ok;
  494. _ ->
  495. Write("\npre-app::\n\t$$$$\(MAKE) -f c_src/Makefile.erlang.mk\n"),
  496. PortSpecWrite(io_lib:format("ERL_CFLAGS = -finline-functions -Wall -fPIC -I ~s/erts-~s/include -I ~s\n",
  497. [code:root_dir(), erlang:system_info(version), code:lib_dir(erl_interface, include)])),
  498. PortSpecWrite(io_lib:format("ERL_LDFLAGS = -L ~s -lerl_interface -lei\n",
  499. [code:lib_dir(erl_interface, lib)])),
  500. [PortSpecWrite(["\n", E, "\n"]) || E <- OsEnv],
  501. FilterEnv = fun(Env) ->
  502. lists:flatten([case E of
  503. {_, _} -> E;
  504. {Regex, K, V} ->
  505. case rebar_utils:is_arch(Regex) of
  506. true -> {K, V};
  507. false -> []
  508. end
  509. end || E <- Env])
  510. end,
  511. MergeEnv = fun(Env) ->
  512. lists:foldl(fun ({K, V}, Acc) ->
  513. case lists:keyfind(K, 1, Acc) of
  514. false -> [{K, rebar_utils:expand_env_variable(V, K, "")}|Acc];
  515. {_, V0} -> [{K, rebar_utils:expand_env_variable(V, K, V0)}|Acc]
  516. end
  517. end, [], Env)
  518. end,
  519. PortEnv = case lists:keyfind(port_env, 1, Conf) of
  520. false -> [];
  521. {_, PortEnv0} -> FilterEnv(PortEnv0)
  522. end,
  523. PortSpec = fun ({Output, Input0, Env}) ->
  524. filelib:ensure_dir("$(call core_native_path,$(DEPS_DIR)/$1/)" ++ Output),
  525. Input = [[" ", I] || I <- Input0],
  526. PortSpecWrite([
  527. [["\n", K, " = ", ShellToMk(V)] || {K, V} <- lists:reverse(MergeEnv(PortEnv))],
  528. case $(PLATFORM) of
  529. darwin -> "\n\nLDFLAGS += -flat_namespace -undefined suppress";
  530. _ -> ""
  531. end,
  532. "\n\nall:: ", Output, "\n\n",
  533. "%.o: %.c\n\t$$$$\(CC) -c -o $$$$\@ $$$$\< $$$$\(CFLAGS) $$$$\(ERL_CFLAGS) $$$$\(DRV_CFLAGS) $$$$\(EXE_CFLAGS)\n\n",
  534. "%.o: %.C\n\t$$$$\(CXX) -c -o $$$$\@ $$$$\< $$$$\(CXXFLAGS) $$$$\(ERL_CFLAGS) $$$$\(DRV_CFLAGS) $$$$\(EXE_CFLAGS)\n\n",
  535. "%.o: %.cc\n\t$$$$\(CXX) -c -o $$$$\@ $$$$\< $$$$\(CXXFLAGS) $$$$\(ERL_CFLAGS) $$$$\(DRV_CFLAGS) $$$$\(EXE_CFLAGS)\n\n",
  536. "%.o: %.cpp\n\t$$$$\(CXX) -c -o $$$$\@ $$$$\< $$$$\(CXXFLAGS) $$$$\(ERL_CFLAGS) $$$$\(DRV_CFLAGS) $$$$\(EXE_CFLAGS)\n\n",
  537. [[Output, ": ", K, " = ", ShellToMk(V), "\n"] || {K, V} <- lists:reverse(MergeEnv(FilterEnv(Env)))],
  538. Output, ": $$$$\(foreach ext,.c .C .cc .cpp,",
  539. "$$$$\(patsubst %$$$$\(ext),%.o,$$$$\(filter %$$$$\(ext),$$$$\(wildcard", Input, "))))\n",
  540. "\t$$$$\(CC) -o $$$$\@ $$$$\? $$$$\(LDFLAGS) $$$$\(ERL_LDFLAGS) $$$$\(DRV_LDFLAGS) $$$$\(EXE_LDFLAGS)",
  541. case filename:extension(Output) of
  542. [] -> "\n";
  543. _ -> " -shared\n"
  544. end])
  545. end,
  546. [PortSpec(S) || S <- PortSpecs]
  547. end,
  548. Write("\ninclude $(call core_relpath,$(dir $(ERLANG_MK_FILENAME)),$(DEPS_DIR)/app)/erlang.mk"),
  549. RunPlugin = fun(Plugin, Step) ->
  550. case erlang:function_exported(Plugin, Step, 2) of
  551. false -> ok;
  552. true ->
  553. c:cd("$(call core_native_path,$(DEPS_DIR)/$1/)"),
  554. Ret = Plugin:Step({config, "", Conf, dict:new(), dict:new(), dict:new(),
  555. dict:store(base_dir, "", dict:new())}, undefined),
  556. io:format("rebar plugin ~p step ~p ret ~p~n", [Plugin, Step, Ret])
  557. end
  558. end,
  559. fun() ->
  560. case lists:keyfind(plugins, 1, Conf) of
  561. false -> ok;
  562. {_, Plugins} ->
  563. [begin
  564. case lists:keyfind(deps, 1, Conf) of
  565. false -> ok;
  566. {_, Deps} ->
  567. case lists:keyfind(P, 1, Deps) of
  568. false -> ok;
  569. _ ->
  570. Path = "$(call core_native_path,$(DEPS_DIR)/)" ++ atom_to_list(P),
  571. io:format("~s", [os:cmd("$(MAKE) -C $(call core_native_path,$(DEPS_DIR)/$1) " ++ Path)]),
  572. io:format("~s", [os:cmd("$(MAKE) -C " ++ Path ++ " IS_DEP=1")]),
  573. code:add_patha(Path ++ "/ebin")
  574. end
  575. end
  576. end || P <- Plugins],
  577. [case code:load_file(P) of
  578. {module, P} -> ok;
  579. _ ->
  580. case lists:keyfind(plugin_dir, 1, Conf) of
  581. false -> ok;
  582. {_, PluginsDir} ->
  583. ErlFile = "$(call core_native_path,$(DEPS_DIR)/$1/)" ++ PluginsDir ++ "/" ++ atom_to_list(P) ++ ".erl",
  584. {ok, P, Bin} = compile:file(ErlFile, [binary]),
  585. {module, P} = code:load_binary(P, ErlFile, Bin)
  586. end
  587. end || P <- Plugins],
  588. [RunPlugin(P, preprocess) || P <- Plugins],
  589. [RunPlugin(P, pre_compile) || P <- Plugins],
  590. [RunPlugin(P, compile) || P <- Plugins]
  591. end
  592. end(),
  593. halt()
  594. endef
  595. define dep_autopatch_app.erl
  596. UpdateModules = fun(App) ->
  597. case filelib:is_regular(App) of
  598. false -> ok;
  599. true ->
  600. {ok, [{application, '$(1)', L0}]} = file:consult(App),
  601. Mods = filelib:fold_files("$(call core_native_path,$(DEPS_DIR)/$1/src)", "\\\\.erl$$$$", true,
  602. fun (F, Acc) -> [list_to_atom(filename:rootname(filename:basename(F)))|Acc] end, []),
  603. L = lists:keystore(modules, 1, L0, {modules, Mods}),
  604. ok = file:write_file(App, io_lib:format("~p.~n", [{application, '$(1)', L}]))
  605. end
  606. end,
  607. UpdateModules("$(call core_native_path,$(DEPS_DIR)/$1/ebin/$1.app)"),
  608. halt()
  609. endef
  610. define dep_autopatch_appsrc.erl
  611. AppSrcOut = "$(call core_native_path,$(DEPS_DIR)/$1/src/$1.app.src)",
  612. AppSrcIn = case filelib:is_regular(AppSrcOut) of false -> "$(call core_native_path,$(DEPS_DIR)/$1/ebin/$1.app)"; true -> AppSrcOut end,
  613. case filelib:is_regular(AppSrcIn) of
  614. false -> ok;
  615. true ->
  616. {ok, [{application, $(1), L0}]} = file:consult(AppSrcIn),
  617. L1 = lists:keystore(modules, 1, L0, {modules, []}),
  618. L2 = case lists:keyfind(vsn, 1, L1) of {_, git} -> lists:keyreplace(vsn, 1, L1, {vsn, "git"}); _ -> L1 end,
  619. L3 = case lists:keyfind(registered, 1, L2) of false -> [{registered, []}|L2]; _ -> L2 end,
  620. ok = file:write_file(AppSrcOut, io_lib:format("~p.~n", [{application, $(1), L3}])),
  621. case AppSrcOut of AppSrcIn -> ok; _ -> ok = file:delete(AppSrcIn) end
  622. end,
  623. halt()
  624. endef
  625. define dep_fetch_git
  626. git clone -q -n -- $(call dep_repo,$(1)) $(DEPS_DIR)/$(call dep_name,$(1)); \
  627. cd $(DEPS_DIR)/$(call dep_name,$(1)) && git checkout -q $(call dep_commit,$(1));
  628. endef
  629. define dep_fetch_git-submodule
  630. git submodule update --init -- $(DEPS_DIR)/$1;
  631. endef
  632. define dep_fetch_hg
  633. hg clone -q -U $(call dep_repo,$(1)) $(DEPS_DIR)/$(call dep_name,$(1)); \
  634. cd $(DEPS_DIR)/$(call dep_name,$(1)) && hg update -q $(call dep_commit,$(1));
  635. endef
  636. define dep_fetch_svn
  637. svn checkout -q $(call dep_repo,$(1)) $(DEPS_DIR)/$(call dep_name,$(1));
  638. endef
  639. define dep_fetch_cp
  640. cp -R $(call dep_repo,$(1)) $(DEPS_DIR)/$(call dep_name,$(1));
  641. endef
  642. define dep_fetch_hex.erl
  643. ssl:start(),
  644. inets:start(),
  645. {ok, {{_, 200, _}, _, Body}} = httpc:request(get,
  646. {"https://s3.amazonaws.com/s3.hex.pm/tarballs/$(1)-$(2).tar", []},
  647. [], [{body_format, binary}]),
  648. {ok, Files} = erl_tar:extract({binary, Body}, [memory]),
  649. {_, Source} = lists:keyfind("contents.tar.gz", 1, Files),
  650. ok = erl_tar:extract({binary, Source}, [{cwd, "$(call core_native_path,$(DEPS_DIR)/$1)"}, compressed]),
  651. halt()
  652. endef
  653. # Hex only has a package version. No need to look in the Erlang.mk packages.
  654. define dep_fetch_hex
  655. $(call erlang,$(call dep_fetch_hex.erl,$(1),$(strip $(word 2,$(dep_$(1))))));
  656. endef
  657. define dep_fetch_fail
  658. echo "Error: Unknown or invalid dependency: $(1)." >&2; \
  659. exit 78;
  660. endef
  661. # Kept for compatibility purposes with older Erlang.mk configuration.
  662. define dep_fetch_legacy
  663. $(warning WARNING: '$(1)' dependency configuration uses deprecated format.) \
  664. git clone -q -n -- $(word 1,$(dep_$(1))) $(DEPS_DIR)/$(1); \
  665. cd $(DEPS_DIR)/$(1) && git checkout -q $(if $(word 2,$(dep_$(1))),$(word 2,$(dep_$(1))),master);
  666. endef
  667. define dep_fetch
  668. $(if $(dep_$(1)), \
  669. $(if $(dep_fetch_$(word 1,$(dep_$(1)))), \
  670. $(word 1,$(dep_$(1))), \
  671. $(if $(IS_DEP),legacy,fail)), \
  672. $(if $(filter $(1),$(PACKAGES)), \
  673. $(pkg_$(1)_fetch), \
  674. fail))
  675. endef
  676. define dep_target
  677. $(DEPS_DIR)/$(call dep_name,$1):
  678. $(eval DEP_NAME := $(call dep_name,$1))
  679. $(eval DEP_STR := $(if $(filter-out $1,$(DEP_NAME)),$1,"$1 ($(DEP_NAME))"))
  680. $(verbose) if test -d $(APPS_DIR)/$(DEP_NAME); then \
  681. echo "Error: Dependency" $(DEP_STR) "conflicts with application found in $(APPS_DIR)/$(DEP_NAME)."; \
  682. exit 17; \
  683. fi
  684. $(verbose) mkdir -p $(DEPS_DIR)
  685. $(dep_verbose) $(call dep_fetch_$(strip $(call dep_fetch,$1)),$1)
  686. $(verbose) if [ -f $(DEPS_DIR)/$(DEP_NAME)/configure.ac -o -f $(DEPS_DIR)/$(DEP_NAME)/configure.in ]; then \
  687. echo " AUTO " $(DEP_STR); \
  688. cd $(DEPS_DIR)/$(DEP_NAME) && autoreconf -Wall -vif -I m4; \
  689. fi
  690. - $(verbose) if [ -f $(DEPS_DIR)/$(DEP_NAME)/configure ]; then \
  691. echo " CONF " $(DEP_STR); \
  692. cd $(DEPS_DIR)/$(DEP_NAME) && ./configure; \
  693. fi
  694. ifeq ($(filter $(1),$(NO_AUTOPATCH)),)
  695. $(verbose) if [ "$(1)" = "amqp_client" -a "$(RABBITMQ_CLIENT_PATCH)" ]; then \
  696. if [ ! -d $(DEPS_DIR)/rabbitmq-codegen ]; then \
  697. echo " PATCH Downloading rabbitmq-codegen"; \
  698. git clone https://github.com/rabbitmq/rabbitmq-codegen.git $(DEPS_DIR)/rabbitmq-codegen; \
  699. fi; \
  700. if [ ! -d $(DEPS_DIR)/rabbitmq-server ]; then \
  701. echo " PATCH Downloading rabbitmq-server"; \
  702. git clone https://github.com/rabbitmq/rabbitmq-server.git $(DEPS_DIR)/rabbitmq-server; \
  703. fi; \
  704. ln -s $(DEPS_DIR)/amqp_client/deps/rabbit_common-0.0.0 $(DEPS_DIR)/rabbit_common; \
  705. elif [ "$(1)" = "rabbit" -a "$(RABBITMQ_SERVER_PATCH)" ]; then \
  706. if [ ! -d $(DEPS_DIR)/rabbitmq-codegen ]; then \
  707. echo " PATCH Downloading rabbitmq-codegen"; \
  708. git clone https://github.com/rabbitmq/rabbitmq-codegen.git $(DEPS_DIR)/rabbitmq-codegen; \
  709. fi \
  710. else \
  711. $(call dep_autopatch,$(DEP_NAME)) \
  712. fi
  713. endif
  714. endef
  715. $(foreach dep,$(BUILD_DEPS) $(DEPS),$(eval $(call dep_target,$(dep))))
  716. ifndef IS_APP
  717. clean:: clean-apps
  718. clean-apps:
  719. $(verbose) for dep in $(ALL_APPS_DIRS) ; do \
  720. $(MAKE) -C $$dep clean IS_APP=1 || exit $$?; \
  721. done
  722. distclean:: distclean-apps
  723. distclean-apps:
  724. $(verbose) for dep in $(ALL_APPS_DIRS) ; do \
  725. $(MAKE) -C $$dep distclean IS_APP=1 || exit $$?; \
  726. done
  727. endif
  728. ifndef SKIP_DEPS
  729. distclean:: distclean-deps
  730. distclean-deps:
  731. $(gen_verbose) rm -rf $(DEPS_DIR)
  732. endif
  733. # External plugins.
  734. DEP_PLUGINS ?=
  735. define core_dep_plugin
  736. -include $(DEPS_DIR)/$(1)
  737. $(DEPS_DIR)/$(1): $(DEPS_DIR)/$(2) ;
  738. endef
  739. $(foreach p,$(DEP_PLUGINS),\
  740. $(eval $(if $(findstring /,$p),\
  741. $(call core_dep_plugin,$p,$(firstword $(subst /, ,$p))),\
  742. $(call core_dep_plugin,$p/plugins.mk,$p))))
  743. # Copyright (c) 2015, Loïc Hoguin <essen@ninenines.eu>
  744. # This file is part of erlang.mk and subject to the terms of the ISC License.
  745. # Verbosity.
  746. proto_verbose_0 = @echo " PROTO " $(filter %.proto,$(?F));
  747. proto_verbose = $(proto_verbose_$(V))
  748. # Core targets.
  749. define compile_proto
  750. $(verbose) mkdir -p ebin/ include/
  751. $(proto_verbose) $(call erlang,$(call compile_proto.erl,$(1)))
  752. $(proto_verbose) erlc +debug_info -o ebin/ ebin/*.erl
  753. $(verbose) rm ebin/*.erl
  754. endef
  755. define compile_proto.erl
  756. [begin
  757. Dir = filename:dirname(filename:dirname(F)),
  758. protobuffs_compile:generate_source(F,
  759. [{output_include_dir, Dir ++ "/include"},
  760. {output_src_dir, Dir ++ "/ebin"}])
  761. end || F <- string:tokens("$(1)", " ")],
  762. halt().
  763. endef
  764. ifneq ($(wildcard src/),)
  765. ebin/$(PROJECT).app:: $(sort $(call core_find,src/,*.proto))
  766. $(if $(strip $?),$(call compile_proto,$?))
  767. endif
  768. # Copyright (c) 2013-2015, Loïc Hoguin <essen@ninenines.eu>
  769. # This file is part of erlang.mk and subject to the terms of the ISC License.
  770. .PHONY: clean-app
  771. # Configuration.
  772. ERLC_OPTS ?= -Werror +debug_info +warn_export_vars +warn_shadow_vars \
  773. +warn_obsolete_guard # +bin_opt_info +warn_export_all +warn_missing_spec
  774. COMPILE_FIRST ?=
  775. COMPILE_FIRST_PATHS = $(addprefix src/,$(addsuffix .erl,$(COMPILE_FIRST)))
  776. ERLC_EXCLUDE ?=
  777. ERLC_EXCLUDE_PATHS = $(addprefix src/,$(addsuffix .erl,$(ERLC_EXCLUDE)))
  778. ERLC_MIB_OPTS ?=
  779. COMPILE_MIB_FIRST ?=
  780. COMPILE_MIB_FIRST_PATHS = $(addprefix mibs/,$(addsuffix .mib,$(COMPILE_MIB_FIRST)))
  781. # Verbosity.
  782. app_verbose_0 = @echo " APP " $(PROJECT);
  783. app_verbose = $(app_verbose_$(V))
  784. appsrc_verbose_0 = @echo " APP " $(PROJECT).app.src;
  785. appsrc_verbose = $(appsrc_verbose_$(V))
  786. makedep_verbose_0 = @echo " DEPEND" $(PROJECT).d;
  787. makedep_verbose = $(makedep_verbose_$(V))
  788. erlc_verbose_0 = @echo " ERLC " $(filter-out $(patsubst %,%.erl,$(ERLC_EXCLUDE)),\
  789. $(filter %.erl %.core,$(?F)));
  790. erlc_verbose = $(erlc_verbose_$(V))
  791. xyrl_verbose_0 = @echo " XYRL " $(filter %.xrl %.yrl,$(?F));
  792. xyrl_verbose = $(xyrl_verbose_$(V))
  793. asn1_verbose_0 = @echo " ASN1 " $(filter %.asn1,$(?F));
  794. asn1_verbose = $(asn1_verbose_$(V))
  795. mib_verbose_0 = @echo " MIB " $(filter %.bin %.mib,$(?F));
  796. mib_verbose = $(mib_verbose_$(V))
  797. ifneq ($(wildcard src/),)
  798. # Targets.
  799. ifeq ($(wildcard ebin/test),)
  800. app:: $(PROJECT).d
  801. $(verbose) $(MAKE) --no-print-directory app-build
  802. else
  803. app:: clean $(PROJECT).d
  804. $(verbose) $(MAKE) --no-print-directory app-build
  805. endif
  806. ifeq ($(wildcard src/$(PROJECT)_app.erl),)
  807. define app_file
  808. {application, $(PROJECT), [
  809. {description, "$(PROJECT_DESCRIPTION)"},
  810. {vsn, "$(PROJECT_VERSION)"},$(if $(IS_DEP),
  811. {id$(comma)$(space)"$(1)"}$(comma))
  812. {modules, [$(call comma_list,$(2))]},
  813. {registered, []},
  814. {applications, [$(call comma_list,kernel stdlib $(OTP_DEPS) $(LOCAL_DEPS) $(DEPS))]}
  815. ]}.
  816. endef
  817. else
  818. define app_file
  819. {application, $(PROJECT), [
  820. {description, "$(PROJECT_DESCRIPTION)"},
  821. {vsn, "$(PROJECT_VERSION)"},$(if $(IS_DEP),
  822. {id$(comma)$(space)"$(1)"}$(comma))
  823. {modules, [$(call comma_list,$(2))]},
  824. {registered, [$(call comma_list,$(PROJECT)_sup $(PROJECT_REGISTERED))]},
  825. {applications, [$(call comma_list,kernel stdlib $(OTP_DEPS) $(LOCAL_DEPS) $(DEPS))]},
  826. {mod, {$(PROJECT)_app, []}}
  827. ]}.
  828. endef
  829. endif
  830. app-build: ebin/$(PROJECT).app
  831. $(verbose) echo -n
  832. # Source files.
  833. ERL_FILES = $(sort $(call core_find,src/,*.erl))
  834. CORE_FILES = $(sort $(call core_find,src/,*.core))
  835. # ASN.1 files.
  836. ifneq ($(wildcard asn1/),)
  837. ASN1_FILES = $(sort $(call core_find,asn1/,*.asn1))
  838. ERL_FILES += $(addprefix src/,$(patsubst %.asn1,%.erl,$(notdir $(ASN1_FILES))))
  839. define compile_asn1
  840. $(verbose) mkdir -p include/
  841. $(asn1_verbose) erlc -v -I include/ -o asn1/ +noobj $(1)
  842. $(verbose) mv asn1/*.erl src/
  843. $(verbose) mv asn1/*.hrl include/
  844. $(verbose) mv asn1/*.asn1db include/
  845. endef
  846. $(PROJECT).d:: $(ASN1_FILES)
  847. $(if $(strip $?),$(call compile_asn1,$?))
  848. endif
  849. # SNMP MIB files.
  850. ifneq ($(wildcard mibs/),)
  851. MIB_FILES = $(sort $(call core_find,mibs/,*.mib))
  852. $(PROJECT).d:: $(COMPILE_MIB_FIRST_PATHS) $(MIB_FILES)
  853. $(verbose) mkdir -p include/ priv/mibs/
  854. $(mib_verbose) erlc -v $(ERLC_MIB_OPTS) -o priv/mibs/ -I priv/mibs/ $?
  855. $(mib_verbose) erlc -o include/ -- $(addprefix priv/mibs/,$(patsubst %.mib,%.bin,$(notdir $?)))
  856. endif
  857. # Leex and Yecc files.
  858. XRL_FILES = $(sort $(call core_find,src/,*.xrl))
  859. XRL_ERL_FILES = $(addprefix src/,$(patsubst %.xrl,%.erl,$(notdir $(XRL_FILES))))
  860. ERL_FILES += $(XRL_ERL_FILES)
  861. YRL_FILES = $(sort $(call core_find,src/,*.yrl))
  862. YRL_ERL_FILES = $(addprefix src/,$(patsubst %.yrl,%.erl,$(notdir $(YRL_FILES))))
  863. ERL_FILES += $(YRL_ERL_FILES)
  864. $(PROJECT).d:: $(XRL_FILES) $(YRL_FILES)
  865. $(if $(strip $?),$(xyrl_verbose) erlc -v -o src/ $?)
  866. # Erlang and Core Erlang files.
  867. define makedep.erl
  868. ErlFiles = lists:usort(string:tokens("$(ERL_FILES)", " ")),
  869. Modules = [{filename:basename(F, ".erl"), F} || F <- ErlFiles],
  870. Add = fun (Dep, Acc) ->
  871. case lists:keyfind(atom_to_list(Dep), 1, Modules) of
  872. {_, DepFile} -> [DepFile|Acc];
  873. false -> Acc
  874. end
  875. end,
  876. AddHd = fun (Dep, Acc) ->
  877. case {Dep, lists:keymember(Dep, 2, Modules)} of
  878. {"src/" ++ _, false} -> [Dep|Acc];
  879. {"include/" ++ _, false} -> [Dep|Acc];
  880. _ -> Acc
  881. end
  882. end,
  883. CompileFirst = fun (Deps) ->
  884. First0 = [case filename:extension(D) of
  885. ".erl" -> filename:basename(D, ".erl");
  886. _ -> []
  887. end || D <- Deps],
  888. case lists:usort(First0) of
  889. [] -> [];
  890. [[]] -> [];
  891. First -> ["COMPILE_FIRST +=", [[" ", F] || F <- First], "\n"]
  892. end
  893. end,
  894. Depend = [begin
  895. case epp:parse_file(F, ["include/"], []) of
  896. {ok, Forms} ->
  897. Deps = lists:usort(lists:foldl(fun
  898. ({attribute, _, behavior, Dep}, Acc) -> Add(Dep, Acc);
  899. ({attribute, _, behaviour, Dep}, Acc) -> Add(Dep, Acc);
  900. ({attribute, _, compile, {parse_transform, Dep}}, Acc) -> Add(Dep, Acc);
  901. ({attribute, _, file, {Dep, _}}, Acc) -> AddHd(Dep, Acc);
  902. (_, Acc) -> Acc
  903. end, [], Forms)),
  904. case Deps of
  905. [] -> "";
  906. _ -> [F, "::", [[" ", D] || D <- Deps], "; @touch \$$@\n", CompileFirst(Deps)]
  907. end;
  908. {error, enoent} ->
  909. []
  910. end
  911. end || F <- ErlFiles],
  912. ok = file:write_file("$(1)", Depend),
  913. halt()
  914. endef
  915. ifeq ($(if $(NO_MAKEDEP),$(wildcard $(PROJECT).d),),)
  916. $(PROJECT).d:: $(ERL_FILES) $(call core_find,include/,*.hrl)
  917. $(makedep_verbose) $(call erlang,$(call makedep.erl,$@))
  918. endif
  919. # Rebuild everything when the Makefile changes.
  920. $(ERL_FILES) $(CORE_FILES) $(ASN1_FILES) $(MIB_FILES) $(XRL_FILES) $(YRL_FILES):: $(MAKEFILE_LIST)
  921. @touch $@
  922. -include $(PROJECT).d
  923. ebin/$(PROJECT).app:: ebin/
  924. ebin/:
  925. $(verbose) mkdir -p ebin/
  926. define compile_erl
  927. $(erlc_verbose) erlc -v $(if $(IS_DEP),$(filter-out -Werror,$(ERLC_OPTS)),$(ERLC_OPTS)) -o ebin/ \
  928. -pa ebin/ -I include/ $(filter-out $(ERLC_EXCLUDE_PATHS),$(COMPILE_FIRST_PATHS) $(1))
  929. endef
  930. ebin/$(PROJECT).app:: $(ERL_FILES) $(CORE_FILES) $(wildcard src/$(PROJECT).app.src)
  931. $(eval FILES_TO_COMPILE := $(filter-out src/$(PROJECT).app.src,$?))
  932. $(if $(strip $(FILES_TO_COMPILE)),$(call compile_erl,$(FILES_TO_COMPILE)))
  933. $(eval GITDESCRIBE := $(shell git describe --dirty --abbrev=7 --tags --always --first-parent 2>/dev/null || true))
  934. $(eval MODULES := $(patsubst %,'%',$(sort $(notdir $(basename \
  935. $(filter-out $(ERLC_EXCLUDE_PATHS),$(ERL_FILES) $(CORE_FILES) $(BEAM_FILES)))))))
  936. ifeq ($(wildcard src/$(PROJECT).app.src),)
  937. $(app_verbose) printf "$(subst $(newline),\n,$(subst ",\",$(call app_file,$(GITDESCRIBE),$(MODULES))))" \
  938. > ebin/$(PROJECT).app
  939. else
  940. $(verbose) if [ -z "$$(grep -E '^[^%]*{\s*modules\s*,' src/$(PROJECT).app.src)" ]; then \
  941. echo "Empty modules entry not found in $(PROJECT).app.src. Please consult the erlang.mk README for instructions." >&2; \
  942. exit 1; \
  943. fi
  944. $(appsrc_verbose) cat src/$(PROJECT).app.src \
  945. | sed "s/{[[:space:]]*modules[[:space:]]*,[[:space:]]*\[\]}/{modules, \[$(call comma_list,$(MODULES))\]}/" \
  946. | sed "s/{id,[[:space:]]*\"git\"}/{id, \"$(GITDESCRIBE)\"}/" \
  947. > ebin/$(PROJECT).app
  948. endif
  949. clean:: clean-app
  950. clean-app:
  951. $(gen_verbose) rm -rf $(PROJECT).d ebin/ priv/mibs/ $(XRL_ERL_FILES) $(YRL_ERL_FILES) \
  952. $(addprefix include/,$(patsubst %.mib,%.hrl,$(notdir $(MIB_FILES)))) \
  953. $(addprefix include/,$(patsubst %.asn1,%.hrl,$(notdir $(ASN1_FILES)))) \
  954. $(addprefix include/,$(patsubst %.asn1,%.asn1db,$(notdir $(ASN1_FILES)))) \
  955. $(addprefix src/,$(patsubst %.asn1,%.erl,$(notdir $(ASN1_FILES))))
  956. endif
  957. # Copyright (c) 2015, Viktor Söderqvist <viktor@zuiderkwast.se>
  958. # This file is part of erlang.mk and subject to the terms of the ISC License.
  959. .PHONY: docs-deps
  960. # Configuration.
  961. ALL_DOC_DEPS_DIRS = $(addprefix $(DEPS_DIR)/,$(DOC_DEPS))
  962. # Targets.
  963. $(foreach dep,$(DOC_DEPS),$(eval $(call dep_target,$(dep))))
  964. ifneq ($(SKIP_DEPS),)
  965. doc-deps:
  966. else
  967. doc-deps: $(ALL_DOC_DEPS_DIRS)
  968. $(verbose) for dep in $(ALL_DOC_DEPS_DIRS) ; do $(MAKE) -C $$dep; done
  969. endif
  970. # Copyright (c) 2015, Loïc Hoguin <essen@ninenines.eu>
  971. # This file is part of erlang.mk and subject to the terms of the ISC License.
  972. .PHONY: test-deps test-dir test-build clean-test-dir
  973. # Configuration.
  974. TEST_DIR ?= $(CURDIR)/test
  975. ALL_TEST_DEPS_DIRS = $(addprefix $(DEPS_DIR)/,$(TEST_DEPS))
  976. TEST_ERLC_OPTS ?= +debug_info +warn_export_vars +warn_shadow_vars +warn_obsolete_guard
  977. TEST_ERLC_OPTS += -DTEST=1
  978. # Targets.
  979. $(foreach dep,$(TEST_DEPS),$(eval $(call dep_target,$(dep))))
  980. ifneq ($(SKIP_DEPS),)
  981. test-deps:
  982. else
  983. test-deps: $(ALL_TEST_DEPS_DIRS)
  984. $(verbose) for dep in $(ALL_TEST_DEPS_DIRS) ; do $(MAKE) -C $$dep IS_DEP=1; done
  985. endif
  986. ifneq ($(wildcard $(TEST_DIR)),)
  987. test-dir:
  988. $(gen_verbose) erlc -v $(TEST_ERLC_OPTS) -I include/ -o $(TEST_DIR) \
  989. $(call core_find,$(TEST_DIR)/,*.erl) -pa ebin/
  990. endif
  991. ifeq ($(wildcard ebin/test),)
  992. test-build:: ERLC_OPTS=$(TEST_ERLC_OPTS)
  993. test-build:: clean deps test-deps $(PROJECT).d
  994. $(verbose) $(MAKE) --no-print-directory app-build test-dir ERLC_OPTS="$(TEST_ERLC_OPTS)"
  995. $(gen_verbose) touch ebin/test
  996. else
  997. test-build:: ERLC_OPTS=$(TEST_ERLC_OPTS)
  998. test-build:: deps test-deps $(PROJECT).d
  999. $(verbose) $(MAKE) --no-print-directory app-build test-dir ERLC_OPTS="$(TEST_ERLC_OPTS)"
  1000. endif
  1001. clean:: clean-test-dir
  1002. clean-test-dir:
  1003. ifneq ($(wildcard $(TEST_DIR)/*.beam),)
  1004. $(gen_verbose) rm -f $(TEST_DIR)/*.beam
  1005. endif
  1006. # Copyright (c) 2015, Loïc Hoguin <essen@ninenines.eu>
  1007. # This file is part of erlang.mk and subject to the terms of the ISC License.
  1008. .PHONY: asciidoc asciidoc-guide asciidoc-manual install-asciidoc distclean-asciidoc
  1009. MAN_INSTALL_PATH ?= /usr/local/share/man
  1010. MAN_SECTIONS ?= 3 7
  1011. docs:: asciidoc
  1012. asciidoc: distclean-asciidoc doc-deps asciidoc-guide asciidoc-manual
  1013. ifeq ($(wildcard doc/src/guide/book.asciidoc),)
  1014. asciidoc-guide:
  1015. else
  1016. asciidoc-guide:
  1017. a2x -v -f pdf doc/src/guide/book.asciidoc && mv doc/src/guide/book.pdf doc/guide.pdf
  1018. a2x -v -f chunked doc/src/guide/book.asciidoc && mv doc/src/guide/book.chunked/ doc/html/
  1019. endif
  1020. ifeq ($(wildcard doc/src/manual/*.asciidoc),)
  1021. asciidoc-manual:
  1022. else
  1023. asciidoc-manual:
  1024. for f in doc/src/manual/*.asciidoc ; do \
  1025. a2x -v -f manpage $$f ; \
  1026. done
  1027. for s in $(MAN_SECTIONS); do \
  1028. mkdir -p doc/man$$s/ ; \
  1029. mv doc/src/manual/*.$$s doc/man$$s/ ; \
  1030. gzip doc/man$$s/*.$$s ; \
  1031. done
  1032. install-docs:: install-asciidoc
  1033. install-asciidoc: asciidoc-manual
  1034. for s in $(MAN_SECTIONS); do \
  1035. mkdir -p $(MAN_INSTALL_PATH)/man$$s/ ; \
  1036. install -g 0 -o 0 -m 0644 doc/man$$s/*.gz $(MAN_INSTALL_PATH)/man$$s/ ; \
  1037. done
  1038. endif
  1039. distclean:: distclean-asciidoc
  1040. distclean-asciidoc:
  1041. $(gen_verbose) rm -rf doc/html/ doc/guide.pdf doc/man3/ doc/man7/
  1042. # Copyright (c) 2014-2015, Loïc Hoguin <essen@ninenines.eu>
  1043. # This file is part of erlang.mk and subject to the terms of the ISC License.
  1044. .PHONY: bootstrap bootstrap-lib bootstrap-rel new list-templates
  1045. # Core targets.
  1046. help::
  1047. $(verbose) printf "%s\n" "" \
  1048. "Bootstrap targets:" \
  1049. " bootstrap Generate a skeleton of an OTP application" \
  1050. " bootstrap-lib Generate a skeleton of an OTP library" \
  1051. " bootstrap-rel Generate the files needed to build a release" \
  1052. " new-app n=NAME Create a new local OTP application NAME" \
  1053. " new-lib n=NAME Create a new local OTP library NAME" \
  1054. " new t=TPL n=NAME Generate a module NAME based on the template TPL" \
  1055. " new t=T n=N in=APP Generate a module NAME based on the template TPL in APP" \
  1056. " list-templates List available templates"
  1057. # Bootstrap templates.
  1058. define bs_appsrc
  1059. {application, $p, [
  1060. {description, ""},
  1061. {vsn, "0.1.0"},
  1062. {id, "git"},
  1063. {modules, []},
  1064. {registered, []},
  1065. {applications, [
  1066. kernel,
  1067. stdlib
  1068. ]},
  1069. {mod, {$p_app, []}},
  1070. {env, []}
  1071. ]}.
  1072. endef
  1073. define bs_appsrc_lib
  1074. {application, $p, [
  1075. {description, ""},
  1076. {vsn, "0.1.0"},
  1077. {id, "git"},
  1078. {modules, []},
  1079. {registered, []},
  1080. {applications, [
  1081. kernel,
  1082. stdlib
  1083. ]}
  1084. ]}.
  1085. endef
  1086. ifdef SP
  1087. define bs_Makefile
  1088. PROJECT = $p
  1089. PROJECT_DESCRIPTION = New project
  1090. PROJECT_VERSION = 0.0.1
  1091. # Whitespace to be used when creating files from templates.
  1092. SP = $(SP)
  1093. include erlang.mk
  1094. endef
  1095. else
  1096. define bs_Makefile
  1097. PROJECT = $p
  1098. include erlang.mk
  1099. endef
  1100. endif
  1101. define bs_apps_Makefile
  1102. PROJECT = $p
  1103. include $(call core_relpath,$(dir $(ERLANG_MK_FILENAME)),$(APPS_DIR)/app)/erlang.mk
  1104. endef
  1105. define bs_app
  1106. -module($p_app).
  1107. -behaviour(application).
  1108. -export([start/2]).
  1109. -export([stop/1]).
  1110. start(_Type, _Args) ->
  1111. $p_sup:start_link().
  1112. stop(_State) ->
  1113. ok.
  1114. endef
  1115. define bs_relx_config
  1116. {release, {$p_release, "1"}, [$p]}.
  1117. {extended_start_script, true}.
  1118. {sys_config, "rel/sys.config"}.
  1119. {vm_args, "rel/vm.args"}.
  1120. endef
  1121. define bs_sys_config
  1122. [
  1123. ].
  1124. endef
  1125. define bs_vm_args
  1126. -name $p@127.0.0.1
  1127. -setcookie $p
  1128. -heart
  1129. endef
  1130. # Normal templates.
  1131. define tpl_supervisor
  1132. -module($(n)).
  1133. -behaviour(supervisor).
  1134. -export([start_link/0]).
  1135. -export([init/1]).
  1136. start_link() ->
  1137. supervisor:start_link({local, ?MODULE}, ?MODULE, []).
  1138. init([]) ->
  1139. Procs = [],
  1140. {ok, {{one_for_one, 1, 5}, Procs}}.
  1141. endef
  1142. define tpl_gen_server
  1143. -module($(n)).
  1144. -behaviour(gen_server).
  1145. %% API.
  1146. -export([start_link/0]).
  1147. %% gen_server.
  1148. -export([init/1]).
  1149. -export([handle_call/3]).
  1150. -export([handle_cast/2]).
  1151. -export([handle_info/2]).
  1152. -export([terminate/2]).
  1153. -export([code_change/3]).
  1154. -record(state, {
  1155. }).
  1156. %% API.
  1157. -spec start_link() -> {ok, pid()}.
  1158. start_link() ->
  1159. gen_server:start_link(?MODULE, [], []).
  1160. %% gen_server.
  1161. init([]) ->
  1162. {ok, #state{}}.
  1163. handle_call(_Request, _From, State) ->
  1164. {reply, ignored, State}.
  1165. handle_cast(_Msg, State) ->
  1166. {noreply, State}.
  1167. handle_info(_Info, State) ->
  1168. {noreply, State}.
  1169. terminate(_Reason, _State) ->
  1170. ok.
  1171. code_change(_OldVsn, State, _Extra) ->
  1172. {ok, State}.
  1173. endef
  1174. define tpl_cowboy_http
  1175. -module($(n)).
  1176. -behaviour(cowboy_http_handler).
  1177. -export([init/3]).
  1178. -export([handle/2]).
  1179. -export([terminate/3]).
  1180. -record(state, {
  1181. }).
  1182. init(_, Req, _Opts) ->
  1183. {ok, Req, #state{}}.
  1184. handle(Req, State=#state{}) ->
  1185. {ok, Req2} = cowboy_req:reply(200, Req),
  1186. {ok, Req2, State}.
  1187. terminate(_Reason, _Req, _State) ->
  1188. ok.
  1189. endef
  1190. define tpl_gen_fsm
  1191. -module($(n)).
  1192. -behaviour(gen_fsm).
  1193. %% API.
  1194. -export([start_link/0]).
  1195. %% gen_fsm.
  1196. -export([init/1]).
  1197. -export([state_name/2]).
  1198. -export([handle_event/3]).
  1199. -export([state_name/3]).
  1200. -export([handle_sync_event/4]).
  1201. -export([handle_info/3]).
  1202. -export([terminate/3]).
  1203. -export([code_change/4]).
  1204. -record(state, {
  1205. }).
  1206. %% API.
  1207. -spec start_link() -> {ok, pid()}.
  1208. start_link() ->
  1209. gen_fsm:start_link(?MODULE, [], []).
  1210. %% gen_fsm.
  1211. init([]) ->
  1212. {ok, state_name, #state{}}.
  1213. state_name(_Event, StateData) ->
  1214. {next_state, state_name, StateData}.
  1215. handle_event(_Event, StateName, StateData) ->
  1216. {next_state, StateName, StateData}.
  1217. state_name(_Event, _From, StateData) ->
  1218. {reply, ignored, state_name, StateData}.
  1219. handle_sync_event(_Event, _From, StateName, StateData) ->
  1220. {reply, ignored, StateName, StateData}.
  1221. handle_info(_Info, StateName, StateData) ->
  1222. {next_state, StateName, StateData}.
  1223. terminate(_Reason, _StateName, _StateData) ->
  1224. ok.
  1225. code_change(_OldVsn, StateName, StateData, _Extra) ->
  1226. {ok, StateName, StateData}.
  1227. endef
  1228. define tpl_cowboy_loop
  1229. -module($(n)).
  1230. -behaviour(cowboy_loop_handler).
  1231. -export([init/3]).
  1232. -export([info/3]).
  1233. -export([terminate/3]).
  1234. -record(state, {
  1235. }).
  1236. init(_, Req, _Opts) ->
  1237. {loop, Req, #state{}, 5000, hibernate}.
  1238. info(_Info, Req, State) ->
  1239. {loop, Req, State, hibernate}.
  1240. terminate(_Reason, _Req, _State) ->
  1241. ok.
  1242. endef
  1243. define tpl_cowboy_rest
  1244. -module($(n)).
  1245. -export([init/3]).
  1246. -export([content_types_provided/2]).
  1247. -export([get_html/2]).
  1248. init(_, _Req, _Opts) ->
  1249. {upgrade, protocol, cowboy_rest}.
  1250. content_types_provided(Req, State) ->
  1251. {[{{<<"text">>, <<"html">>, '*'}, get_html}], Req, State}.
  1252. get_html(Req, State) ->
  1253. {<<"<html><body>This is REST!</body></html>">>, Req, State}.
  1254. endef
  1255. define tpl_cowboy_ws
  1256. -module($(n)).
  1257. -behaviour(cowboy_websocket_handler).
  1258. -export([init/3]).
  1259. -export([websocket_init/3]).
  1260. -export([websocket_handle/3]).
  1261. -export([websocket_info/3]).
  1262. -export([websocket_terminate/3]).
  1263. -record(state, {
  1264. }).
  1265. init(_, _, _) ->
  1266. {upgrade, protocol, cowboy_websocket}.
  1267. websocket_init(_, Req, _Opts) ->
  1268. Req2 = cowboy_req:compact(Req),
  1269. {ok, Req2, #state{}}.
  1270. websocket_handle({text, Data}, Req, State) ->
  1271. {reply, {text, Data}, Req, State};
  1272. websocket_handle({binary, Data}, Req, State) ->
  1273. {reply, {binary, Data}, Req, State};
  1274. websocket_handle(_Frame, Req, State) ->
  1275. {ok, Req, State}.
  1276. websocket_info(_Info, Req, State) ->
  1277. {ok, Req, State}.
  1278. websocket_terminate(_Reason, _Req, _State) ->
  1279. ok.
  1280. endef
  1281. define tpl_ranch_protocol
  1282. -module($(n)).
  1283. -behaviour(ranch_protocol).
  1284. -export([start_link/4]).
  1285. -export([init/4]).
  1286. -type opts() :: [].
  1287. -export_type([opts/0]).
  1288. -record(state, {
  1289. socket :: inet:socket(),
  1290. transport :: module()
  1291. }).
  1292. start_link(Ref, Socket, Transport, Opts) ->
  1293. Pid = spawn_link(?MODULE, init, [Ref, Socket, Transport, Opts]),
  1294. {ok, Pid}.
  1295. -spec init(ranch:ref(), inet:socket(), module(), opts()) -> ok.
  1296. init(Ref, Socket, Transport, _Opts) ->
  1297. ok = ranch:accept_ack(Ref),
  1298. loop(#state{socket=Socket, transport=Transport}).
  1299. loop(State) ->
  1300. loop(State).
  1301. endef
  1302. # Plugin-specific targets.
  1303. define render_template
  1304. $(verbose) echo "$${_$(1)}" > $(2)
  1305. endef
  1306. ifndef WS
  1307. ifdef SP
  1308. WS = $(subst a,,a $(wordlist 1,$(SP),a a a a a a a a a a a a a a a a a a a a))
  1309. else
  1310. WS = $(tab)
  1311. endif
  1312. endif
  1313. $(foreach template,$(filter bs_% tpl_%,$(.VARIABLES)), \
  1314. $(eval _$(template) = $$(subst $$(tab),$$(WS),$$($(template)))) \
  1315. $(eval export _$(template)))
  1316. bootstrap:
  1317. ifneq ($(wildcard src/),)
  1318. $(error Error: src/ directory already exists)
  1319. endif
  1320. $(eval p := $(PROJECT))
  1321. $(eval n := $(PROJECT)_sup)
  1322. $(call render_template,bs_Makefile,Makefile)
  1323. $(verbose) mkdir src/
  1324. ifdef LEGACY
  1325. $(call render_template,bs_appsrc,src/$(PROJECT).app.src)
  1326. endif
  1327. $(call render_template,bs_app,src/$(PROJECT)_app.erl)
  1328. $(call render_template,tpl_supervisor,src/$(PROJECT)_sup.erl)
  1329. bootstrap-lib:
  1330. ifneq ($(wildcard src/),)
  1331. $(error Error: src/ directory already exists)
  1332. endif
  1333. $(eval p := $(PROJECT))
  1334. $(call render_template,bs_Makefile,Makefile)
  1335. $(verbose) mkdir src/
  1336. ifdef LEGACY
  1337. $(call render_template,bs_appsrc_lib,src/$(PROJECT).app.src)
  1338. endif
  1339. bootstrap-rel:
  1340. ifneq ($(wildcard relx.config),)
  1341. $(error Error: relx.config already exists)
  1342. endif
  1343. ifneq ($(wildcard rel/),)
  1344. $(error Error: rel/ directory already exists)
  1345. endif
  1346. $(eval p := $(PROJECT))
  1347. $(call render_template,bs_relx_config,relx.config)
  1348. $(verbose) mkdir rel/
  1349. $(call render_template,bs_sys_config,rel/sys.config)
  1350. $(call render_template,bs_vm_args,rel/vm.args)
  1351. new-app:
  1352. ifndef in
  1353. $(error Usage: $(MAKE) new-app in=APP)
  1354. endif
  1355. ifneq ($(wildcard $(APPS_DIR)/$in),)
  1356. $(error Error: Application $in already exists)
  1357. endif
  1358. $(eval p := $(in))
  1359. $(eval n := $(in)_sup)
  1360. $(verbose) mkdir -p $(APPS_DIR)/$p/src/
  1361. $(call render_template,bs_apps_Makefile,$(APPS_DIR)/$p/Makefile)
  1362. ifdef LEGACY
  1363. $(call render_template,bs_appsrc,$(APPS_DIR)/$p/src/$p.app.src)
  1364. endif
  1365. $(call render_template,bs_app,$(APPS_DIR)/$p/src/$p_app.erl)
  1366. $(call render_template,tpl_supervisor,$(APPS_DIR)/$p/src/$p_sup.erl)
  1367. new-lib:
  1368. ifndef in
  1369. $(error Usage: $(MAKE) new-lib in=APP)
  1370. endif
  1371. ifneq ($(wildcard $(APPS_DIR)/$in),)
  1372. $(error Error: Application $in already exists)
  1373. endif
  1374. $(eval p := $(in))
  1375. $(verbose) mkdir -p $(APPS_DIR)/$p/src/
  1376. $(call render_template,bs_apps_Makefile,$(APPS_DIR)/$p/Makefile)
  1377. ifdef LEGACY
  1378. $(call render_template,bs_appsrc_lib,$(APPS_DIR)/$p/src/$p.app.src)
  1379. endif
  1380. new:
  1381. ifeq ($(wildcard src/)$(in),)
  1382. $(error Error: src/ directory does not exist)
  1383. endif
  1384. ifndef t
  1385. $(error Usage: $(MAKE) new t=TEMPLATE n=NAME [in=APP])
  1386. endif
  1387. ifndef tpl_$(t)
  1388. $(error Unknown template)
  1389. endif
  1390. ifndef n
  1391. $(error Usage: $(MAKE) new t=TEMPLATE n=NAME [in=APP])
  1392. endif
  1393. ifdef in
  1394. $(verbose) $(MAKE) -C $(APPS_DIR)/$(in)/ new t=$t n=$n in=
  1395. else
  1396. $(call render_template,tpl_$(t),src/$(n).erl)
  1397. endif
  1398. list-templates:
  1399. $(verbose) echo Available templates: $(sort $(patsubst tpl_%,%,$(filter tpl_%,$(.VARIABLES))))
  1400. # Copyright (c) 2014-2015, Loïc Hoguin <essen@ninenines.eu>
  1401. # This file is part of erlang.mk and subject to the terms of the ISC License.
  1402. .PHONY: clean-c_src distclean-c_src-env
  1403. # Configuration.
  1404. C_SRC_DIR ?= $(CURDIR)/c_src
  1405. C_SRC_ENV ?= $(C_SRC_DIR)/env.mk
  1406. C_SRC_OUTPUT ?= $(CURDIR)/priv/$(PROJECT).so
  1407. C_SRC_TYPE ?= shared
  1408. # System type and C compiler/flags.
  1409. ifeq ($(PLATFORM),darwin)
  1410. CC ?= cc
  1411. CFLAGS ?= -O3 -std=c99 -arch x86_64 -finline-functions -Wall -Wmissing-prototypes
  1412. CXXFLAGS ?= -O3 -arch x86_64 -finline-functions -Wall
  1413. LDFLAGS ?= -arch x86_64 -flat_namespace -undefined suppress
  1414. else ifeq ($(PLATFORM),freebsd)
  1415. CC ?= cc
  1416. CFLAGS ?= -O3 -std=c99 -finline-functions -Wall -Wmissing-prototypes
  1417. CXXFLAGS ?= -O3 -finline-functions -Wall
  1418. else ifeq ($(PLATFORM),linux)
  1419. CC ?= gcc
  1420. CFLAGS ?= -O3 -std=c99 -finline-functions -Wall -Wmissing-prototypes
  1421. CXXFLAGS ?= -O3 -finline-functions -Wall
  1422. endif
  1423. CFLAGS += -fPIC -I $(ERTS_INCLUDE_DIR) -I $(ERL_INTERFACE_INCLUDE_DIR)
  1424. CXXFLAGS += -fPIC -I $(ERTS_INCLUDE_DIR) -I $(ERL_INTERFACE_INCLUDE_DIR)
  1425. LDLIBS += -L $(ERL_INTERFACE_LIB_DIR) -lerl_interface -lei
  1426. # Verbosity.
  1427. c_verbose_0 = @echo " C " $(?F);
  1428. c_verbose = $(c_verbose_$(V))
  1429. cpp_verbose_0 = @echo " CPP " $(?F);
  1430. cpp_verbose = $(cpp_verbose_$(V))
  1431. link_verbose_0 = @echo " LD " $(@F);
  1432. link_verbose = $(link_verbose_$(V))
  1433. # Targets.
  1434. ifeq ($(wildcard $(C_SRC_DIR)),)
  1435. else ifneq ($(wildcard $(C_SRC_DIR)/Makefile),)
  1436. app:: app-c_src
  1437. test-build:: app-c_src
  1438. app-c_src:
  1439. $(MAKE) -C $(C_SRC_DIR)
  1440. clean::
  1441. $(MAKE) -C $(C_SRC_DIR) clean
  1442. else
  1443. ifeq ($(SOURCES),)
  1444. SOURCES := $(sort $(foreach pat,*.c *.C *.cc *.cpp,$(call core_find,$(C_SRC_DIR)/,$(pat))))
  1445. endif
  1446. OBJECTS = $(addsuffix .o, $(basename $(SOURCES)))
  1447. COMPILE_C = $(c_verbose) $(CC) $(CFLAGS) $(CPPFLAGS) -c
  1448. COMPILE_CPP = $(cpp_verbose) $(CXX) $(CXXFLAGS) $(CPPFLAGS) -c
  1449. app:: $(C_SRC_ENV) $(C_SRC_OUTPUT)
  1450. test-build:: $(C_SRC_ENV) $(C_SRC_OUTPUT)
  1451. $(C_SRC_OUTPUT): $(OBJECTS)
  1452. $(verbose) mkdir -p priv/
  1453. $(link_verbose) $(CC) $(OBJECTS) \
  1454. $(LDFLAGS) $(if $(filter $(C_SRC_TYPE),shared),-shared) $(LDLIBS) \
  1455. -o $(C_SRC_OUTPUT)
  1456. %.o: %.c
  1457. $(COMPILE_C) $(OUTPUT_OPTION) $<
  1458. %.o: %.cc
  1459. $(COMPILE_CPP) $(OUTPUT_OPTION) $<
  1460. %.o: %.C
  1461. $(COMPILE_CPP) $(OUTPUT_OPTION) $<
  1462. %.o: %.cpp
  1463. $(COMPILE_CPP) $(OUTPUT_OPTION) $<
  1464. clean:: clean-c_src
  1465. clean-c_src:
  1466. $(gen_verbose) rm -f $(C_SRC_OUTPUT) $(OBJECTS)
  1467. endif
  1468. ifneq ($(wildcard $(C_SRC_DIR)),)
  1469. $(C_SRC_ENV):
  1470. $(verbose) $(ERL) -eval "file:write_file(\"$(C_SRC_ENV)\", \
  1471. io_lib:format( \
  1472. \"ERTS_INCLUDE_DIR ?= ~s/erts-~s/include/~n\" \
  1473. \"ERL_INTERFACE_INCLUDE_DIR ?= ~s~n\" \
  1474. \"ERL_INTERFACE_LIB_DIR ?= ~s~n\", \
  1475. [code:root_dir(), erlang:system_info(version), \
  1476. code:lib_dir(erl_interface, include), \
  1477. code:lib_dir(erl_interface, lib)])), \
  1478. halt()."
  1479. distclean:: distclean-c_src-env
  1480. distclean-c_src-env:
  1481. $(gen_verbose) rm -f $(C_SRC_ENV)
  1482. -include $(C_SRC_ENV)
  1483. endif
  1484. # Templates.
  1485. define bs_c_nif
  1486. #include "erl_nif.h"
  1487. static int loads = 0;
  1488. static int load(ErlNifEnv* env, void** priv_data, ERL_NIF_TERM load_info)
  1489. {
  1490. /* Initialize private data. */
  1491. *priv_data = NULL;
  1492. loads++;
  1493. return 0;
  1494. }
  1495. static int upgrade(ErlNifEnv* env, void** priv_data, void** old_priv_data, ERL_NIF_TERM load_info)
  1496. {
  1497. /* Convert the private data to the new version. */
  1498. *priv_data = *old_priv_data;
  1499. loads++;
  1500. return 0;
  1501. }
  1502. static void unload(ErlNifEnv* env, void* priv_data)
  1503. {
  1504. if (loads == 1) {
  1505. /* Destroy the private data. */
  1506. }
  1507. loads--;
  1508. }
  1509. static ERL_NIF_TERM hello(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
  1510. {
  1511. if (enif_is_atom(env, argv[0])) {
  1512. return enif_make_tuple2(env,
  1513. enif_make_atom(env, "hello"),
  1514. argv[0]);
  1515. }
  1516. return enif_make_tuple2(env,
  1517. enif_make_atom(env, "error"),
  1518. enif_make_atom(env, "badarg"));
  1519. }
  1520. static ErlNifFunc nif_funcs[] = {
  1521. {"hello", 1, hello}
  1522. };
  1523. ERL_NIF_INIT($n, nif_funcs, load, NULL, upgrade, unload)
  1524. endef
  1525. define bs_erl_nif
  1526. -module($n).
  1527. -export([hello/1]).
  1528. -on_load(on_load/0).
  1529. on_load() ->
  1530. PrivDir = case code:priv_dir(?MODULE) of
  1531. {error, _} ->
  1532. AppPath = filename:dirname(filename:dirname(code:which(?MODULE))),
  1533. filename:join(AppPath, "priv");
  1534. Path ->
  1535. Path
  1536. end,
  1537. erlang:load_nif(filename:join(PrivDir, atom_to_list(?MODULE)), 0).
  1538. hello(_) ->
  1539. erlang:nif_error({not_loaded, ?MODULE}).
  1540. endef
  1541. $(foreach template,bs_c_nif bs_erl_nif, \
  1542. $(eval _$(template) = $$(subst $$(tab),$$(WS),$$($(template)))) \
  1543. $(eval export _$(template)))
  1544. new-nif:
  1545. ifneq ($(wildcard $(C_SRC_DIR)/$n.c),)
  1546. $(error Error: $(C_SRC_DIR)/$n.c already exists)
  1547. endif
  1548. ifneq ($(wildcard src/$n.erl),)
  1549. $(error Error: src/$n.erl already exists)
  1550. endif
  1551. ifdef in
  1552. $(verbose) $(MAKE) -C $(APPS_DIR)/$(in)/ new-nif n=$n in=
  1553. else
  1554. $(verbose) mkdir -p $(C_SRC_DIR) src/
  1555. $(call render_template,bs_c_nif,$(C_SRC_DIR)/$n.c)
  1556. $(call render_template,bs_erl_nif,src/$n.erl)
  1557. endif
  1558. # Copyright (c) 2015, Loïc Hoguin <essen@ninenines.eu>
  1559. # This file is part of erlang.mk and subject to the terms of the ISC License.
  1560. .PHONY: ci ci-setup distclean-kerl
  1561. KERL ?= $(CURDIR)/kerl
  1562. export KERL
  1563. KERL_URL ?= https://raw.githubusercontent.com/yrashk/kerl/master/kerl
  1564. OTP_GIT ?= https://github.com/erlang/otp
  1565. CI_INSTALL_DIR ?= $(HOME)/erlang
  1566. CI_OTP ?=
  1567. ifeq ($(strip $(CI_OTP)),)
  1568. ci::
  1569. else
  1570. ci:: $(addprefix ci-,$(CI_OTP))
  1571. ci-prepare: $(addprefix $(CI_INSTALL_DIR)/,$(CI_OTP))
  1572. ci-setup::
  1573. ci_verbose_0 = @echo " CI " $(1);
  1574. ci_verbose = $(ci_verbose_$(V))
  1575. define ci_target
  1576. ci-$(1): $(CI_INSTALL_DIR)/$(1)
  1577. $(ci_verbose) \
  1578. PATH="$(CI_INSTALL_DIR)/$(1)/bin:$(PATH)" \
  1579. CI_OTP_RELEASE="$(1)" \
  1580. CT_OPTS="-label $(1)" \
  1581. $(MAKE) clean ci-setup tests
  1582. endef
  1583. $(foreach otp,$(CI_OTP),$(eval $(call ci_target,$(otp))))
  1584. define ci_otp_target
  1585. ifeq ($(wildcard $(CI_INSTALL_DIR)/$(1)),)
  1586. $(CI_INSTALL_DIR)/$(1): $(KERL)
  1587. $(KERL) build git $(OTP_GIT) $(1) $(1)
  1588. $(KERL) install $(1) $(CI_INSTALL_DIR)/$(1)
  1589. endif
  1590. endef
  1591. $(foreach otp,$(CI_OTP),$(eval $(call ci_otp_target,$(otp))))
  1592. $(KERL):
  1593. $(gen_verbose) $(call core_http_get,$(KERL),$(KERL_URL))
  1594. $(verbose) chmod +x $(KERL)
  1595. help::
  1596. $(verbose) printf "%s\n" "" \
  1597. "Continuous Integration targets:" \
  1598. " ci Run '$(MAKE) tests' on all configured Erlang versions." \
  1599. "" \
  1600. "The CI_OTP variable must be defined with the Erlang versions" \
  1601. "that must be tested. For example: CI_OTP = OTP-17.3.4 OTP-17.5.3"
  1602. distclean:: distclean-kerl
  1603. distclean-kerl:
  1604. $(gen_verbose) rm -rf $(KERL)
  1605. endif
  1606. # Copyright (c) 2013-2015, Loïc Hoguin <essen@ninenines.eu>
  1607. # This file is part of erlang.mk and subject to the terms of the ISC License.
  1608. .PHONY: ct distclean-ct
  1609. # Configuration.
  1610. CT_OPTS ?=
  1611. ifneq ($(wildcard $(TEST_DIR)),)
  1612. CT_SUITES ?= $(sort $(subst _SUITE.erl,,$(notdir $(call core_find,$(TEST_DIR)/,*_SUITE.erl))))
  1613. else
  1614. CT_SUITES ?=
  1615. endif
  1616. # Core targets.
  1617. tests:: ct
  1618. distclean:: distclean-ct
  1619. help::
  1620. $(verbose) printf "%s\n" "" \
  1621. "Common_test targets:" \
  1622. " ct Run all the common_test suites for this project" \
  1623. "" \
  1624. "All your common_test suites have their associated targets." \
  1625. "A suite named http_SUITE can be ran using the ct-http target."
  1626. # Plugin-specific targets.
  1627. CT_RUN = ct_run \
  1628. -no_auto_compile \
  1629. -noinput \
  1630. -pa $(CURDIR)/ebin $(DEPS_DIR)/*/ebin $(TEST_DIR) \
  1631. -dir $(TEST_DIR) \
  1632. -logdir $(CURDIR)/logs
  1633. ifeq ($(CT_SUITES),)
  1634. ct:
  1635. else
  1636. ct: test-build
  1637. $(verbose) mkdir -p $(CURDIR)/logs/
  1638. $(gen_verbose) $(CT_RUN) -suite $(addsuffix _SUITE,$(CT_SUITES)) $(CT_OPTS)
  1639. endif
  1640. define ct_suite_target
  1641. ct-$(1): test-build
  1642. $(verbose) mkdir -p $(CURDIR)/logs/
  1643. $(gen_verbose) $(CT_RUN) -suite $(addsuffix _SUITE,$(1)) $(CT_OPTS)
  1644. endef
  1645. $(foreach test,$(CT_SUITES),$(eval $(call ct_suite_target,$(test))))
  1646. distclean-ct:
  1647. $(gen_verbose) rm -rf $(CURDIR)/logs/
  1648. # Copyright (c) 2013-2015, Loïc Hoguin <essen@ninenines.eu>
  1649. # This file is part of erlang.mk and subject to the terms of the ISC License.
  1650. .PHONY: plt distclean-plt dialyze
  1651. # Configuration.
  1652. DIALYZER_PLT ?= $(CURDIR)/.$(PROJECT).plt
  1653. export DIALYZER_PLT
  1654. PLT_APPS ?=
  1655. DIALYZER_DIRS ?= --src -r src
  1656. DIALYZER_OPTS ?= -Werror_handling -Wrace_conditions \
  1657. -Wunmatched_returns # -Wunderspecs
  1658. # Core targets.
  1659. check:: dialyze
  1660. distclean:: distclean-plt
  1661. help::
  1662. $(verbose) printf "%s\n" "" \
  1663. "Dialyzer targets:" \
  1664. " plt Build a PLT file for this project" \
  1665. " dialyze Analyze the project using Dialyzer"
  1666. # Plugin-specific targets.
  1667. $(DIALYZER_PLT): deps app
  1668. $(verbose) dialyzer --build_plt --apps erts kernel stdlib $(PLT_APPS) $(OTP_DEPS) $(LOCAL_DEPS) $(DEPS)
  1669. plt: $(DIALYZER_PLT)
  1670. distclean-plt:
  1671. $(gen_verbose) rm -f $(DIALYZER_PLT)
  1672. ifneq ($(wildcard $(DIALYZER_PLT)),)
  1673. dialyze:
  1674. else
  1675. dialyze: $(DIALYZER_PLT)
  1676. endif
  1677. $(verbose) dialyzer --no_native $(DIALYZER_DIRS) $(DIALYZER_OPTS)
  1678. # Copyright (c) 2015, Erlang Solutions Ltd.
  1679. # This file is part of erlang.mk and subject to the terms of the ISC License.
  1680. .PHONY: elvis distclean-elvis
  1681. # Configuration.
  1682. ELVIS_CONFIG ?= $(CURDIR)/elvis.config
  1683. ELVIS ?= $(CURDIR)/elvis
  1684. export ELVIS
  1685. ELVIS_URL ?= https://github.com/inaka/elvis/releases/download/0.2.5/elvis
  1686. ELVIS_CONFIG_URL ?= https://github.com/inaka/elvis/releases/download/0.2.5/elvis.config
  1687. ELVIS_OPTS ?=
  1688. # Core targets.
  1689. help::
  1690. $(verbose) printf "%s\n" "" \
  1691. "Elvis targets:" \
  1692. " elvis Run Elvis using the local elvis.config or download the default otherwise"
  1693. distclean:: distclean-elvis
  1694. # Plugin-specific targets.
  1695. $(ELVIS):
  1696. $(gen_verbose) $(call core_http_get,$(ELVIS),$(ELVIS_URL))
  1697. $(verbose) chmod +x $(ELVIS)
  1698. $(ELVIS_CONFIG):
  1699. $(verbose) $(call core_http_get,$(ELVIS_CONFIG),$(ELVIS_CONFIG_URL))
  1700. elvis: $(ELVIS) $(ELVIS_CONFIG)
  1701. $(verbose) $(ELVIS) rock -c $(ELVIS_CONFIG) $(ELVIS_OPTS)
  1702. distclean-elvis:
  1703. $(gen_verbose) rm -rf $(ELVIS)
  1704. # Copyright (c) 2013-2015, Loïc Hoguin <essen@ninenines.eu>
  1705. # This file is part of erlang.mk and subject to the terms of the ISC License.
  1706. # Configuration.
  1707. DTL_FULL_PATH ?=
  1708. DTL_PATH ?= templates/
  1709. DTL_SUFFIX ?= _dtl
  1710. # Verbosity.
  1711. dtl_verbose_0 = @echo " DTL " $(filter %.dtl,$(?F));
  1712. dtl_verbose = $(dtl_verbose_$(V))
  1713. # Core targets.
  1714. define erlydtl_compile.erl
  1715. [begin
  1716. Module0 = case "$(strip $(DTL_FULL_PATH))" of
  1717. "" ->
  1718. filename:basename(F, ".dtl");
  1719. _ ->
  1720. "$(DTL_PATH)" ++ F2 = filename:rootname(F, ".dtl"),
  1721. re:replace(F2, "/", "_", [{return, list}, global])
  1722. end,
  1723. Module = list_to_atom(string:to_lower(Module0) ++ "$(DTL_SUFFIX)"),
  1724. case erlydtl:compile(F, Module, [{out_dir, "ebin/"}, return_errors, {doc_root, "templates"}]) of
  1725. ok -> ok;
  1726. {ok, _} -> ok
  1727. end
  1728. end || F <- string:tokens("$(1)", " ")],
  1729. halt().
  1730. endef
  1731. ifneq ($(wildcard src/),)
  1732. DTL_FILES = $(sort $(call core_find,$(DTL_PATH),*.dtl))
  1733. ifdef DTL_FULL_PATH
  1734. BEAM_FILES += $(addprefix ebin/,$(patsubst %.dtl,%_dtl.beam,$(subst /,_,$(DTL_FILES:$(DTL_PATH)%=%))))
  1735. else
  1736. BEAM_FILES += $(addprefix ebin/,$(patsubst %.dtl,%_dtl.beam,$(notdir $(DTL_FILES))))
  1737. endif
  1738. # Rebuild templates when the Makefile changes.
  1739. $(DTL_FILES): $(MAKEFILE_LIST)
  1740. @touch $@
  1741. ebin/$(PROJECT).app:: $(DTL_FILES)
  1742. $(if $(strip $?),\
  1743. $(dtl_verbose) $(call erlang,$(call erlydtl_compile.erl,$?,-pa ebin/ $(DEPS_DIR)/erlydtl/ebin/)))
  1744. endif
  1745. # Copyright (c) 2014 Dave Cottlehuber <dch@skunkwerks.at>
  1746. # This file is part of erlang.mk and subject to the terms of the ISC License.
  1747. .PHONY: distclean-escript escript
  1748. # Configuration.
  1749. ESCRIPT_NAME ?= $(PROJECT)
  1750. ESCRIPT_COMMENT ?= This is an -*- erlang -*- file
  1751. ESCRIPT_BEAMS ?= "ebin/*", "deps/*/ebin/*"
  1752. ESCRIPT_SYS_CONFIG ?= "rel/sys.config"
  1753. ESCRIPT_EMU_ARGS ?= -pa . \
  1754. -sasl errlog_type error \
  1755. -escript main $(ESCRIPT_NAME)
  1756. ESCRIPT_SHEBANG ?= /usr/bin/env escript
  1757. ESCRIPT_STATIC ?= "deps/*/priv/**", "priv/**"
  1758. # Core targets.
  1759. distclean:: distclean-escript
  1760. help::
  1761. $(verbose) printf "%s\n" "" \
  1762. "Escript targets:" \
  1763. " escript Build an executable escript archive" \
  1764. # Plugin-specific targets.
  1765. # Based on https://github.com/synrc/mad/blob/master/src/mad_bundle.erl
  1766. # Copyright (c) 2013 Maxim Sokhatsky, Synrc Research Center
  1767. # Modified MIT License, https://github.com/synrc/mad/blob/master/LICENSE :
  1768. # Software may only be used for the great good and the true happiness of all
  1769. # sentient beings.
  1770. define ESCRIPT_RAW
  1771. 'Read = fun(F) -> {ok, B} = file:read_file(filename:absname(F)), B end,'\
  1772. 'Files = fun(L) -> A = lists:concat([filelib:wildcard(X)||X<- L ]),'\
  1773. ' [F || F <- A, not filelib:is_dir(F) ] end,'\
  1774. 'Squash = fun(L) -> [{filename:basename(F), Read(F) } || F <- L ] end,'\
  1775. 'Zip = fun(A, L) -> {ok,{_,Z}} = zip:create(A, L, [{compress,all},memory]), Z end,'\
  1776. 'Ez = fun(Escript) ->'\
  1777. ' Static = Files([$(ESCRIPT_STATIC)]),'\
  1778. ' Beams = Squash(Files([$(ESCRIPT_BEAMS), $(ESCRIPT_SYS_CONFIG)])),'\
  1779. ' Archive = Beams ++ [{ "static.gz", Zip("static.gz", Static)}],'\
  1780. ' escript:create(Escript, [ $(ESCRIPT_OPTIONS)'\
  1781. ' {archive, Archive, [memory]},'\
  1782. ' {shebang, "$(ESCRIPT_SHEBANG)"},'\
  1783. ' {comment, "$(ESCRIPT_COMMENT)"},'\
  1784. ' {emu_args, " $(ESCRIPT_EMU_ARGS)"}'\
  1785. ' ]),'\
  1786. ' file:change_mode(Escript, 8#755)'\
  1787. 'end,'\
  1788. 'Ez("$(ESCRIPT_NAME)"),'\
  1789. 'halt().'
  1790. endef
  1791. ESCRIPT_COMMAND = $(subst ' ',,$(ESCRIPT_RAW))
  1792. escript:: distclean-escript deps app
  1793. $(gen_verbose) $(ERL) -eval $(ESCRIPT_COMMAND)
  1794. distclean-escript:
  1795. $(gen_verbose) rm -f $(ESCRIPT_NAME)
  1796. # Copyright (c) 2014, Enrique Fernandez <enrique.fernandez@erlang-solutions.com>
  1797. # Copyright (c) 2015, Loïc Hoguin <essen@ninenines.eu>
  1798. # This file is contributed to erlang.mk and subject to the terms of the ISC License.
  1799. .PHONY: eunit
  1800. # Configuration
  1801. EUNIT_OPTS ?=
  1802. # Core targets.
  1803. tests:: eunit
  1804. help::
  1805. $(verbose) printf "%s\n" "" \
  1806. "EUnit targets:" \
  1807. " eunit Run all the EUnit tests for this project"
  1808. # Plugin-specific targets.
  1809. define eunit.erl
  1810. case "$(COVER)" of
  1811. "" -> ok;
  1812. _ ->
  1813. case cover:compile_beam_directory("ebin") of
  1814. {error, _} -> halt(1);
  1815. _ -> ok
  1816. end
  1817. end,
  1818. case eunit:test([$(call comma_list,$(1))], [$(EUNIT_OPTS)]) of
  1819. ok -> ok;
  1820. error -> halt(2)
  1821. end,
  1822. case "$(COVER)" of
  1823. "" -> ok;
  1824. _ ->
  1825. cover:export("eunit.coverdata")
  1826. end,
  1827. halt()
  1828. endef
  1829. EUNIT_EBIN_MODS = $(notdir $(basename $(call core_find,ebin/,*.beam)))
  1830. EUNIT_TEST_MODS = $(notdir $(basename $(call core_find,$(TEST_DIR)/,*.beam)))
  1831. EUNIT_MODS = $(foreach mod,$(EUNIT_EBIN_MODS) $(filter-out \
  1832. $(patsubst %,%_tests,$(EUNIT_EBIN_MODS)),$(EUNIT_TEST_MODS)),{module,'$(mod)'})
  1833. eunit: test-build
  1834. $(gen_verbose) $(ERL) -pa $(TEST_DIR) $(DEPS_DIR)/*/ebin ebin \
  1835. -eval "$(subst $(newline),,$(subst ",\",$(call eunit.erl,$(EUNIT_MODS))))"
  1836. # Copyright (c) 2013-2015, Loïc Hoguin <essen@ninenines.eu>
  1837. # This file is part of erlang.mk and subject to the terms of the ISC License.
  1838. .PHONY: relx-rel distclean-relx-rel distclean-relx run
  1839. # Configuration.
  1840. RELX ?= $(CURDIR)/relx
  1841. RELX_CONFIG ?= $(CURDIR)/relx.config
  1842. RELX_URL ?= https://github.com/erlware/relx/releases/download/v3.5.0/relx
  1843. RELX_OPTS ?=
  1844. RELX_OUTPUT_DIR ?= _rel
  1845. ifeq ($(firstword $(RELX_OPTS)),-o)
  1846. RELX_OUTPUT_DIR = $(word 2,$(RELX_OPTS))
  1847. else
  1848. RELX_OPTS += -o $(RELX_OUTPUT_DIR)
  1849. endif
  1850. # Core targets.
  1851. ifeq ($(IS_DEP),)
  1852. ifneq ($(wildcard $(RELX_CONFIG)),)
  1853. rel:: distclean-relx-rel relx-rel
  1854. endif
  1855. endif
  1856. distclean:: distclean-relx-rel distclean-relx
  1857. # Plugin-specific targets.
  1858. $(RELX):
  1859. $(gen_verbose) $(call core_http_get,$(RELX),$(RELX_URL))
  1860. $(verbose) chmod +x $(RELX)
  1861. relx-rel: $(RELX) rel-deps
  1862. $(verbose) $(RELX) -c $(RELX_CONFIG) $(RELX_OPTS)
  1863. distclean-relx-rel:
  1864. $(gen_verbose) rm -rf $(RELX_OUTPUT_DIR)
  1865. distclean-relx:
  1866. $(gen_verbose) rm -rf $(RELX)
  1867. # Run target.
  1868. ifeq ($(wildcard $(RELX_CONFIG)),)
  1869. run:
  1870. else
  1871. define get_relx_release.erl
  1872. {ok, Config} = file:consult("$(RELX_CONFIG)"),
  1873. {release, {Name, _}, _} = lists:keyfind(release, 1, Config),
  1874. io:format("~s", [Name]),
  1875. halt(0).
  1876. endef
  1877. RELX_RELEASE = `$(call erlang,$(get_relx_release.erl))`
  1878. run: all
  1879. $(verbose) $(RELX_OUTPUT_DIR)/$(RELX_RELEASE)/bin/$(RELX_RELEASE) console
  1880. help::
  1881. $(verbose) printf "%s\n" "" \
  1882. "Relx targets:" \
  1883. " run Compile the project, build the release and run it"
  1884. endif
  1885. # Copyright (c) 2014, M Robert Martin <rob@version2beta.com>
  1886. # Copyright (c) 2015, Loïc Hoguin <essen@ninenines.eu>
  1887. # This file is contributed to erlang.mk and subject to the terms of the ISC License.
  1888. .PHONY: shell
  1889. # Configuration.
  1890. SHELL_ERL ?= erl
  1891. SHELL_PATHS ?= $(CURDIR)/ebin $(APPS_DIR)/*/ebin $(DEPS_DIR)/*/ebin
  1892. SHELL_OPTS ?=
  1893. ALL_SHELL_DEPS_DIRS = $(addprefix $(DEPS_DIR)/,$(SHELL_DEPS))
  1894. # Core targets
  1895. help::
  1896. $(verbose) printf "%s\n" "" \
  1897. "Shell targets:" \
  1898. " shell Run an erlang shell with SHELL_OPTS or reasonable default"
  1899. # Plugin-specific targets.
  1900. $(foreach dep,$(SHELL_DEPS),$(eval $(call dep_target,$(dep))))
  1901. build-shell-deps: $(ALL_SHELL_DEPS_DIRS)
  1902. $(verbose) for dep in $(ALL_SHELL_DEPS_DIRS) ; do $(MAKE) -C $$dep ; done
  1903. shell: build-shell-deps
  1904. $(gen_verbose) $(SHELL_ERL) -pa $(SHELL_PATHS) $(SHELL_OPTS)
  1905. # Copyright (c) 2015, Loïc Hoguin <essen@ninenines.eu>
  1906. # This file is part of erlang.mk and subject to the terms of the ISC License.
  1907. ifeq ($(filter triq,$(DEPS) $(TEST_DEPS)),triq)
  1908. .PHONY: triq
  1909. # Targets.
  1910. tests:: triq
  1911. define triq_check.erl
  1912. code:add_pathsa(["$(CURDIR)/ebin", "$(DEPS_DIR)/*/ebin"]),
  1913. try
  1914. case $(1) of
  1915. all -> [true] =:= lists:usort([triq:check(M) || M <- [$(call comma_list,$(3))]]);
  1916. module -> triq:check($(2));
  1917. function -> triq:check($(2))
  1918. end
  1919. of
  1920. true -> halt(0);
  1921. _ -> halt(1)
  1922. catch error:undef ->
  1923. io:format("Undefined property or module~n"),
  1924. halt(0)
  1925. end.
  1926. endef
  1927. ifdef t
  1928. ifeq (,$(findstring :,$(t)))
  1929. triq: test-build
  1930. $(verbose) $(call erlang,$(call triq_check.erl,module,$(t)))
  1931. else
  1932. triq: test-build
  1933. $(verbose) echo Testing $(t)/0
  1934. $(verbose) $(call erlang,$(call triq_check.erl,function,$(t)()))
  1935. endif
  1936. else
  1937. triq: test-build
  1938. $(eval MODULES := $(patsubst %,'%',$(sort $(notdir $(basename $(wildcard ebin/*.beam))))))
  1939. $(gen_verbose) $(call erlang,$(call triq_check.erl,all,undefined,$(MODULES)))
  1940. endif
  1941. endif
  1942. # Copyright (c) 2015, Erlang Solutions Ltd.
  1943. # This file is part of erlang.mk and subject to the terms of the ISC License.
  1944. .PHONY: xref distclean-xref
  1945. # Configuration.
  1946. ifeq ($(XREF_CONFIG),)
  1947. XREF_ARGS :=
  1948. else
  1949. XREF_ARGS := -c $(XREF_CONFIG)
  1950. endif
  1951. XREFR ?= $(CURDIR)/xrefr
  1952. export XREFR
  1953. XREFR_URL ?= https://github.com/inaka/xref_runner/releases/download/0.2.2/xrefr
  1954. # Core targets.
  1955. help::
  1956. $(verbose) printf "%s\n" "" \
  1957. "Xref targets:" \
  1958. " xref Run Xrefr using $XREF_CONFIG as config file if defined"
  1959. distclean:: distclean-xref
  1960. # Plugin-specific targets.
  1961. $(XREFR):
  1962. $(gen_verbose) $(call core_http_get,$(XREFR),$(XREFR_URL))
  1963. $(verbose) chmod +x $(XREFR)
  1964. xref: deps app $(XREFR)
  1965. $(gen_verbose) $(XREFR) $(XREFR_ARGS)
  1966. distclean-xref:
  1967. $(gen_verbose) rm -rf $(XREFR)
  1968. # Copyright 2015, Viktor Söderqvist <viktor@zuiderkwast.se>
  1969. # This file is part of erlang.mk and subject to the terms of the ISC License.
  1970. COVER_REPORT_DIR = cover
  1971. # Hook in coverage to ct
  1972. ifdef COVER
  1973. ifdef CT_RUN
  1974. # All modules in 'ebin'
  1975. COVER_MODS = $(notdir $(basename $(call core_ls,ebin/*.beam)))
  1976. test-build:: $(TEST_DIR)/ct.cover.spec
  1977. $(TEST_DIR)/ct.cover.spec:
  1978. $(verbose) echo Cover mods: $(COVER_MODS)
  1979. $(gen_verbose) printf "%s\n" \
  1980. '{incl_mods,[$(subst $(space),$(comma),$(COVER_MODS))]}.' \
  1981. '{export,"$(CURDIR)/ct.coverdata"}.' > $@
  1982. CT_RUN += -cover $(TEST_DIR)/ct.cover.spec
  1983. endif
  1984. endif
  1985. # Core targets
  1986. ifdef COVER
  1987. ifneq ($(COVER_REPORT_DIR),)
  1988. tests::
  1989. $(verbose) $(MAKE) --no-print-directory cover-report
  1990. endif
  1991. endif
  1992. clean:: coverdata-clean
  1993. ifneq ($(COVER_REPORT_DIR),)
  1994. distclean:: cover-report-clean
  1995. endif
  1996. help::
  1997. $(verbose) printf "%s\n" "" \
  1998. "Cover targets:" \
  1999. " cover-report Generate a HTML coverage report from previously collected" \
  2000. " cover data." \
  2001. " all.coverdata Merge {eunit,ct}.coverdata into one coverdata file." \
  2002. "" \
  2003. "If COVER=1 is set, coverage data is generated by the targets eunit and ct. The" \
  2004. "target tests additionally generates a HTML coverage report from the combined" \
  2005. "coverdata files from each of these testing tools. HTML reports can be disabled" \
  2006. "by setting COVER_REPORT_DIR to empty."
  2007. # Plugin specific targets
  2008. COVERDATA = $(filter-out all.coverdata,$(wildcard *.coverdata))
  2009. .PHONY: coverdata-clean
  2010. coverdata-clean:
  2011. $(gen_verbose) rm -f *.coverdata ct.cover.spec
  2012. # Merge all coverdata files into one.
  2013. all.coverdata: $(COVERDATA)
  2014. $(gen_verbose) $(ERL) -eval ' \
  2015. $(foreach f,$(COVERDATA),cover:import("$(f)") == ok orelse halt(1),) \
  2016. cover:export("$@"), halt(0).'
  2017. # These are only defined if COVER_REPORT_DIR is non-empty. Set COVER_REPORT_DIR to
  2018. # empty if you want the coverdata files but not the HTML report.
  2019. ifneq ($(COVER_REPORT_DIR),)
  2020. .PHONY: cover-report-clean cover-report
  2021. cover-report-clean:
  2022. $(gen_verbose) rm -rf $(COVER_REPORT_DIR)
  2023. ifeq ($(COVERDATA),)
  2024. cover-report:
  2025. else
  2026. # Modules which include eunit.hrl always contain one line without coverage
  2027. # because eunit defines test/0 which is never called. We compensate for this.
  2028. EUNIT_HRL_MODS = $(subst $(space),$(comma),$(shell \
  2029. grep -e '^\s*-include.*include/eunit\.hrl"' src/*.erl \
  2030. | sed "s/^src\/\(.*\)\.erl:.*/'\1'/" | uniq))
  2031. define cover_report.erl
  2032. $(foreach f,$(COVERDATA),cover:import("$(f)") == ok orelse halt(1),)
  2033. Ms = cover:imported_modules(),
  2034. [cover:analyse_to_file(M, "$(COVER_REPORT_DIR)/" ++ atom_to_list(M)
  2035. ++ ".COVER.html", [html]) || M <- Ms],
  2036. Report = [begin {ok, R} = cover:analyse(M, module), R end || M <- Ms],
  2037. EunitHrlMods = [$(EUNIT_HRL_MODS)],
  2038. Report1 = [{M, {Y, case lists:member(M, EunitHrlMods) of
  2039. true -> N - 1; false -> N end}} || {M, {Y, N}} <- Report],
  2040. TotalY = lists:sum([Y || {_, {Y, _}} <- Report1]),
  2041. TotalN = lists:sum([N || {_, {_, N}} <- Report1]),
  2042. TotalPerc = round(100 * TotalY / (TotalY + TotalN)),
  2043. {ok, F} = file:open("$(COVER_REPORT_DIR)/index.html", [write]),
  2044. io:format(F, "<!DOCTYPE html><html>~n"
  2045. "<head><meta charset=\"UTF-8\">~n"
  2046. "<title>Coverage report</title></head>~n"
  2047. "<body>~n", []),
  2048. io:format(F, "<h1>Coverage</h1>~n<p>Total: ~p%</p>~n", [TotalPerc]),
  2049. io:format(F, "<table><tr><th>Module</th><th>Coverage</th></tr>~n", []),
  2050. [io:format(F, "<tr><td><a href=\"~p.COVER.html\">~p</a></td>"
  2051. "<td>~p%</td></tr>~n",
  2052. [M, M, round(100 * Y / (Y + N))]) || {M, {Y, N}} <- Report1],
  2053. How = "$(subst $(space),$(comma)$(space),$(basename $(COVERDATA)))",
  2054. Date = "$(shell date -u "+%Y-%m-%dT%H:%M:%SZ")",
  2055. io:format(F, "</table>~n"
  2056. "<p>Generated using ~s and erlang.mk on ~s.</p>~n"
  2057. "</body></html>", [How, Date]),
  2058. halt().
  2059. endef
  2060. cover-report:
  2061. $(gen_verbose) mkdir -p $(COVER_REPORT_DIR)
  2062. $(gen_verbose) $(call erlang,$(cover_report.erl))
  2063. endif
  2064. endif # ifneq ($(COVER_REPORT_DIR),)