update_appup.escript 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. #!/usr/bin/env -S escript -c
  2. %% -*- erlang-indent-level:4 -*-
  3. usage() ->
  4. "A script that fills in boilerplate for appup files.
  5. Algorithm: this script compares md5s of beam files of each
  6. application, and creates a `{load_module, Module, brutal_purge,
  7. soft_purge, []}` action for the changed and new modules. For deleted
  8. modules it creates `{delete_module, M}` action. These entries are
  9. added to each patch release preceding the current release. If an entry
  10. for a module already exists, this module is ignored. The existing
  11. actions are kept.
  12. Please note that it only compares the current release with its
  13. predecessor, assuming that the upgrade actions for the older releases
  14. are correct.
  15. Note: The defaults are set up for emqx, but they can be tuned to
  16. support other repos too.
  17. Usage:
  18. update_appup.escript [--check] [--repo URL] [--remote NAME] [--skip-build] [--make-commad SCRIPT] [--release-dir DIR] <previous_release_tag>
  19. Options:
  20. --check Don't update the appfile, just check that they are complete
  21. --repo Upsteam git repo URL
  22. --remote Get upstream repo URL from the specified git remote
  23. --skip-build Don't rebuild the releases. May produce wrong results
  24. --make-command A command used to assemble the release
  25. --release-dir Release directory
  26. --src-dirs Directories where source code is found. Defaults to '{src,apps,lib-*}/**/'
  27. --binary-rel-url Binary release URL pattern. %TAG% variable is substituted with the release tag.
  28. E.g. \"https://github.com/emqx/emqx/releases/download/v%TAG%/emqx-centos7-%TAG%-amd64.zip\"
  29. ".
  30. -record(app,
  31. { modules :: #{module() => binary()}
  32. , version :: string()
  33. }).
  34. default_options() ->
  35. #{ clone_url => find_upstream_repo("origin")
  36. , make_command => "make emqx-rel"
  37. , beams_dir => "_build/emqx/rel/emqx/lib/"
  38. , check => false
  39. , prev_tag => undefined
  40. , src_dirs => "{src,apps,lib-*}/**/"
  41. , binary_rel_url => undefined
  42. }.
  43. %% App-specific actions that should be added unconditionally to any update/downgrade:
  44. app_specific_actions(_) ->
  45. [].
  46. ignored_apps() ->
  47. [emqx_dashboard, emqx_management] ++ otp_standard_apps().
  48. main(Args) ->
  49. #{prev_tag := Baseline} = Options = parse_args(Args, default_options()),
  50. init_globals(Options),
  51. main(Options, Baseline).
  52. parse_args([PrevTag = [A|_]], State) when A =/= $- ->
  53. State#{prev_tag => PrevTag};
  54. parse_args(["--check"|Rest], State) ->
  55. parse_args(Rest, State#{check => true});
  56. parse_args(["--skip-build"|Rest], State) ->
  57. parse_args(Rest, State#{make_command => "true"});
  58. parse_args(["--repo", Repo|Rest], State) ->
  59. parse_args(Rest, State#{clone_url => Repo});
  60. parse_args(["--remote", Remote|Rest], State) ->
  61. parse_args(Rest, State#{clone_url => find_upstream_repo(Remote)});
  62. parse_args(["--make-command", Command|Rest], State) ->
  63. parse_args(Rest, State#{make_command => Command});
  64. parse_args(["--release-dir", Dir|Rest], State) ->
  65. parse_args(Rest, State#{beams_dir => Dir});
  66. parse_args(["--src-dirs", Pattern|Rest], State) ->
  67. parse_args(Rest, State#{src_dirs => Pattern});
  68. parse_args(["--binary-rel-url", URL|Rest], State) ->
  69. parse_args(Rest, State#{binary_rel_url => {ok, URL}});
  70. parse_args(_, _) ->
  71. fail(usage()).
  72. main(Options, Baseline) ->
  73. {CurrRelDir, PrevRelDir} = prepare(Baseline, Options),
  74. log("~n===================================~n"
  75. "Processing changes..."
  76. "~n===================================~n"),
  77. CurrAppsIdx = index_apps(CurrRelDir),
  78. PrevAppsIdx = index_apps(PrevRelDir),
  79. %% log("Curr: ~p~nPrev: ~p~n", [CurrAppsIdx, PrevAppsIdx]),
  80. AppupChanges = find_appup_actions(CurrAppsIdx, PrevAppsIdx),
  81. case getopt(check) of
  82. true ->
  83. case AppupChanges of
  84. [] ->
  85. ok;
  86. _ ->
  87. Diffs =
  88. lists:filtermap(
  89. fun({App, {Upgrade, Downgrade, OldUpgrade, OldDowngrade}}) ->
  90. case parse_appup_diffs(Upgrade, OldUpgrade,
  91. Downgrade, OldDowngrade) of
  92. ok ->
  93. false;
  94. {diffs, Diffs} ->
  95. {true, {App, Diffs}}
  96. end
  97. end,
  98. AppupChanges),
  99. case Diffs =:= [] of
  100. true ->
  101. ok;
  102. false ->
  103. set_invalid(),
  104. log("ERROR: The appup files are incomplete. Missing changes:~n ~p",
  105. [Diffs])
  106. end
  107. end;
  108. false ->
  109. update_appups(AppupChanges)
  110. end,
  111. check_appup_files(),
  112. warn_and_exit(is_valid()).
  113. warn_and_exit(true) ->
  114. log("
  115. NOTE: Please review the changes manually. This script does not know about NIF
  116. changes, supervisor changes, process restarts and so on. Also the load order of
  117. the beam files might need updating.~n"),
  118. halt(0);
  119. warn_and_exit(false) ->
  120. log("~nERROR: Incomplete appups found. Please inspect the output for more details.~n"),
  121. halt(1).
  122. prepare(Baseline, Options = #{make_command := MakeCommand, beams_dir := BeamDir, binary_rel_url := BinRel}) ->
  123. log("~n===================================~n"
  124. "Baseline: ~s"
  125. "~n===================================~n", [Baseline]),
  126. log("Building the current version...~n"),
  127. bash(MakeCommand),
  128. log("Downloading and building the previous release...~n"),
  129. PrevRelDir =
  130. case BinRel of
  131. undefined ->
  132. {ok, PrevRootDir} = build_prev_release(Baseline, Options),
  133. filename:join(PrevRootDir, BeamDir);
  134. {ok, _URL} ->
  135. {ok, PrevRootDir} = download_prev_release(Baseline, Options),
  136. PrevRootDir
  137. end,
  138. {BeamDir, PrevRelDir}.
  139. build_prev_release(Baseline, #{clone_url := Repo, make_command := MakeCommand}) ->
  140. BaseDir = "/tmp/emqx-baseline/",
  141. Dir = filename:basename(Repo, ".git") ++ [$-|Baseline],
  142. %% TODO: shallow clone
  143. Script = "mkdir -p ${BASEDIR} &&
  144. cd ${BASEDIR} &&
  145. { [ -d ${DIR} ] || git clone --branch ${TAG} ${REPO} ${DIR}; } &&
  146. cd ${DIR} &&" ++ MakeCommand,
  147. Env = [{"REPO", Repo}, {"TAG", Baseline}, {"BASEDIR", BaseDir}, {"DIR", Dir}],
  148. bash(Script, Env),
  149. {ok, filename:join(BaseDir, Dir)}.
  150. download_prev_release(Tag, #{binary_rel_url := {ok, URL0}, clone_url := Repo}) ->
  151. URL = string:replace(URL0, "%TAG%", Tag, all),
  152. BaseDir = "/tmp/emqx-baseline-bin/",
  153. Dir = filename:basename(Repo, ".git") ++ [$-|Tag],
  154. Filename = filename:join(BaseDir, Dir),
  155. Script = "mkdir -p ${OUTFILE} &&
  156. wget -c -O ${OUTFILE}.zip ${URL} &&
  157. unzip -n -d ${OUTFILE} ${OUTFILE}.zip",
  158. Env = [{"TAG", Tag}, {"OUTFILE", Filename}, {"URL", URL}],
  159. bash(Script, Env),
  160. {ok, Filename}.
  161. find_upstream_repo(Remote) ->
  162. string:trim(os:cmd("git remote get-url " ++ Remote)).
  163. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  164. %% Appup action creation and updating
  165. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  166. find_appup_actions(CurrApps, PrevApps) ->
  167. maps:fold(
  168. fun(App, CurrAppIdx, Acc) ->
  169. case PrevApps of
  170. #{App := PrevAppIdx} ->
  171. find_appup_actions(App, CurrAppIdx, PrevAppIdx) ++ Acc;
  172. _ ->
  173. %% New app, nothing to upgrade here.
  174. Acc
  175. end
  176. end,
  177. [],
  178. CurrApps).
  179. find_appup_actions(_App, AppIdx, AppIdx) ->
  180. %% No changes to the app, ignore:
  181. [];
  182. find_appup_actions(App, CurrAppIdx, PrevAppIdx = #app{version = PrevVersion}) ->
  183. {OldUpgrade, OldDowngrade} = find_old_appup_actions(App, PrevVersion),
  184. Upgrade = merge_update_actions(App, diff_app(App, CurrAppIdx, PrevAppIdx), OldUpgrade),
  185. Downgrade = merge_update_actions(App, diff_app(App, PrevAppIdx, CurrAppIdx), OldDowngrade),
  186. if OldUpgrade =:= Upgrade andalso OldDowngrade =:= Downgrade ->
  187. %% The appup file has been already updated:
  188. [];
  189. true ->
  190. [{App, {Upgrade, Downgrade, OldUpgrade, OldDowngrade}}]
  191. end.
  192. %% For external dependencies, show only the changes that are missing
  193. %% in their current appup.
  194. diff_appup_instructions(ComputedChanges, PresentChanges) ->
  195. lists:foldr(
  196. fun({VsnOrRegex, ComputedActions}, Acc) ->
  197. case find_matching_version(VsnOrRegex, PresentChanges) of
  198. undefined ->
  199. [{VsnOrRegex, ComputedActions} | Acc];
  200. PresentActions ->
  201. DiffActions = ComputedActions -- PresentActions,
  202. case DiffActions of
  203. [] ->
  204. %% no diff
  205. Acc;
  206. _ ->
  207. [{VsnOrRegex, DiffActions} | Acc]
  208. end
  209. end
  210. end,
  211. [],
  212. ComputedChanges).
  213. %% For external dependencies, checks if any missing diffs are present
  214. %% and groups them by `up' and `down' types.
  215. parse_appup_diffs(Upgrade, OldUpgrade, Downgrade, OldDowngrade) ->
  216. DiffUp = diff_appup_instructions(Upgrade, OldUpgrade),
  217. DiffDown = diff_appup_instructions(Downgrade, OldDowngrade),
  218. case {DiffUp, DiffDown} of
  219. {[], []} ->
  220. %% no diff for external dependency; ignore
  221. ok;
  222. _ ->
  223. set_invalid(),
  224. Diffs = #{ up => DiffUp
  225. , down => DiffDown
  226. },
  227. {diffs, Diffs}
  228. end.
  229. %% TODO: handle regexes
  230. %% Since the first argument may be a regex itself, we would need to
  231. %% check if it is "contained" within other regexes inside list of
  232. %% versions in the second argument.
  233. find_matching_version(VsnOrRegex, PresentChanges) ->
  234. proplists:get_value(VsnOrRegex, PresentChanges).
  235. find_old_appup_actions(App, PrevVersion) ->
  236. {Upgrade0, Downgrade0} =
  237. case locate(ebin_current, App, ".appup") of
  238. {ok, AppupFile} ->
  239. log("Found the previous appup file: ~s~n", [AppupFile]),
  240. {_, U, D} = read_appup(AppupFile),
  241. {U, D};
  242. undefined ->
  243. %% Fallback to the app.src file, in case the
  244. %% application doesn't have a release (useful for the
  245. %% apps that live outside the EMQX monorepo):
  246. case locate(src, App, ".appup.src") of
  247. {ok, AppupSrcFile} ->
  248. log("Using ~s as a source of previous update actions~n", [AppupSrcFile]),
  249. {_, U, D} = read_appup(AppupSrcFile),
  250. {U, D};
  251. undefined ->
  252. {[], []}
  253. end
  254. end,
  255. {ensure_version(PrevVersion, Upgrade0), ensure_version(PrevVersion, Downgrade0)}.
  256. merge_update_actions(App, Changes, Vsns) ->
  257. lists:map(fun(Ret = {<<".*">>, _}) ->
  258. Ret;
  259. ({Vsn, Actions}) ->
  260. {Vsn, do_merge_update_actions(App, Vsn, Changes, Actions)}
  261. end,
  262. Vsns).
  263. do_merge_update_actions(App, Vsn, {New0, Changed0, Deleted0}, OldActions) ->
  264. AppSpecific = app_specific_actions(App) -- OldActions,
  265. AlreadyHandled = lists:flatten(lists:map(fun process_old_action/1, OldActions)),
  266. New = New0 -- AlreadyHandled,
  267. Changed = Changed0 -- AlreadyHandled,
  268. Deleted = Deleted0 -- AlreadyHandled,
  269. Reloads = [{load_module, M, brutal_purge, soft_purge, []}
  270. || not contains_restart_application(App, OldActions),
  271. M <- Changed ++ New],
  272. {OldActionsWithStop, OldActionsAfterStop} =
  273. find_application_stop_instruction(App, OldActions),
  274. OldActionsWithStop ++
  275. Reloads ++
  276. OldActionsAfterStop ++
  277. [{delete_module, M} || M <- Deleted] ++
  278. AppSpecific.
  279. %% If an entry restarts an application, there's no need to use
  280. %% `load_module' instructions.
  281. contains_restart_application(Application, Actions) ->
  282. lists:member({restart_application, Application}, Actions).
  283. %% If there is an `application:stop(Application)' call in the
  284. %% instructions, we insert `load_module' instructions after it.
  285. find_application_stop_instruction(Application, Actions) ->
  286. {Before, After0} =
  287. lists:splitwith(
  288. fun({apply, {application, stop, [App]}}) when App =:= Application ->
  289. false;
  290. (_) ->
  291. true
  292. end, Actions),
  293. case After0 of
  294. [StopInst | After] ->
  295. {Before ++ [StopInst], After};
  296. [] ->
  297. {[], Before}
  298. end.
  299. %% @doc Process the existing actions to exclude modules that are
  300. %% already handled
  301. process_old_action({purge, Modules}) ->
  302. Modules;
  303. process_old_action({delete_module, Module}) ->
  304. [Module];
  305. process_old_action(LoadModule) when is_tuple(LoadModule) andalso
  306. element(1, LoadModule) =:= load_module ->
  307. element(2, LoadModule);
  308. process_old_action(_) ->
  309. [].
  310. ensure_version(Version, OldInstructions) ->
  311. OldVersions = [element(1, I) || I <- OldInstructions],
  312. case contains_version(Version, OldVersions) of
  313. false ->
  314. [{Version, []} | OldInstructions];
  315. true ->
  316. OldInstructions
  317. end.
  318. contains_version(Needle, Haystack) when is_list(Needle) ->
  319. lists:any(
  320. fun(Regex) when is_binary(Regex) ->
  321. case re:run(Needle, Regex) of
  322. {match, _} ->
  323. true;
  324. nomatch ->
  325. false
  326. end;
  327. (Vsn) ->
  328. Vsn =:= Needle
  329. end,
  330. Haystack).
  331. read_appup(File) ->
  332. %% NOTE: appup file is a script, it may contain variables or functions.
  333. case file:script(File, [{'VSN', "VSN"}]) of
  334. {ok, Terms} ->
  335. Terms;
  336. Error ->
  337. fail("Failed to parse appup file ~s: ~p", [File, Error])
  338. end.
  339. check_appup_files() ->
  340. AppupFiles = filelib:wildcard(getopt(src_dirs) ++ "/*.appup.src"),
  341. lists:foreach(fun read_appup/1, AppupFiles).
  342. update_appups(Changes) ->
  343. lists:foreach(
  344. fun({App, {Upgrade, Downgrade, OldUpgrade, OldDowngrade}}) ->
  345. do_update_appup(App, Upgrade, Downgrade, OldUpgrade, OldDowngrade)
  346. end,
  347. Changes).
  348. do_update_appup(App, Upgrade, Downgrade, OldUpgrade, OldDowngrade) ->
  349. case locate(src, App, ".appup.src") of
  350. {ok, AppupFile} ->
  351. case contains_contents(AppupFile, Upgrade, Downgrade) of
  352. true ->
  353. ok;
  354. false ->
  355. render_appfile(AppupFile, Upgrade, Downgrade)
  356. end;
  357. undefined ->
  358. case create_stub(App) of
  359. {ok, AppupFile} ->
  360. render_appfile(AppupFile, Upgrade, Downgrade);
  361. false ->
  362. case parse_appup_diffs(Upgrade, OldUpgrade,
  363. Downgrade, OldDowngrade) of
  364. ok ->
  365. %% no diff for external dependency; ignore
  366. ok;
  367. {diffs, Diffs} ->
  368. set_invalid(),
  369. log("ERROR: Appup file for the external dependency '~p' is not complete.~n Missing changes: ~100p~n", [App, Diffs]),
  370. log("NOTE: Some changes above might be already covered by regexes.~n")
  371. end
  372. end
  373. end.
  374. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  375. %% Appup file creation
  376. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  377. render_appfile(File, Upgrade, Downgrade) ->
  378. IOList = io_lib:format("%% -*- mode: erlang -*-\n{VSN,~n ~p,~n ~p}.~n", [Upgrade, Downgrade]),
  379. ok = file:write_file(File, IOList).
  380. create_stub(App) ->
  381. case locate(src, App, Ext = ".app.src") of
  382. {ok, AppSrc} ->
  383. DirName = filename:dirname(AppSrc),
  384. AppupFile = filename:basename(AppSrc, Ext) ++ ".appup.src",
  385. Default = {<<".*">>, []},
  386. AppupFileFullpath = filename:join(DirName, AppupFile),
  387. render_appfile(AppupFileFullpath, [Default], [Default]),
  388. {ok, AppupFileFullpath};
  389. undefined ->
  390. false
  391. end.
  392. %% we check whether the destination file already has the contents we
  393. %% want to write to avoid writing and losing indentation and comments.
  394. contains_contents(File, Upgrade, Downgrade) ->
  395. %% the file may contain the VSN variable, so it's a script
  396. case file:script(File, [{'VSN', 'VSN'}]) of
  397. {ok, {_, Upgrade, Downgrade}} ->
  398. true;
  399. _ ->
  400. false
  401. end.
  402. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  403. %% application and release indexing
  404. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  405. index_apps(ReleaseDir) ->
  406. Apps0 = maps:from_list([index_app(filename:join(ReleaseDir, AppFile)) ||
  407. AppFile <- filelib:wildcard("**/ebin/*.app", ReleaseDir)]),
  408. maps:without(ignored_apps(), Apps0).
  409. index_app(AppFile) ->
  410. {ok, [{application, App, Properties}]} = file:consult(AppFile),
  411. Vsn = proplists:get_value(vsn, Properties),
  412. %% Note: assuming that beams are always located in the same directory where app file is:
  413. EbinDir = filename:dirname(AppFile),
  414. Modules = hashsums(EbinDir),
  415. {App, #app{ version = Vsn
  416. , modules = Modules
  417. }}.
  418. diff_app(App,
  419. #app{version = NewVersion, modules = NewModules},
  420. #app{version = OldVersion, modules = OldModules}) ->
  421. {New, Changed} =
  422. maps:fold( fun(Mod, MD5, {New, Changed}) ->
  423. case OldModules of
  424. #{Mod := OldMD5} when MD5 =:= OldMD5 ->
  425. {New, Changed};
  426. #{Mod := _} ->
  427. {New, [Mod | Changed]};
  428. _ ->
  429. {[Mod | New], Changed}
  430. end
  431. end
  432. , {[], []}
  433. , NewModules
  434. ),
  435. Deleted = maps:keys(maps:without(maps:keys(NewModules), OldModules)),
  436. NChanges = length(New) + length(Changed) + length(Deleted),
  437. if NewVersion =:= OldVersion andalso NChanges > 0 ->
  438. set_invalid(),
  439. log("ERROR: Application '~p' contains changes, but its version is not updated~n", [App]);
  440. NewVersion > OldVersion ->
  441. log("INFO: Application '~p' has been updated: ~p -> ~p~n", [App, OldVersion, NewVersion]),
  442. ok;
  443. true ->
  444. ok
  445. end,
  446. {New, Changed, Deleted}.
  447. -spec hashsums(file:filename()) -> #{module() => binary()}.
  448. hashsums(EbinDir) ->
  449. maps:from_list(lists:map(
  450. fun(Beam) ->
  451. File = filename:join(EbinDir, Beam),
  452. {ok, Ret = {_Module, _MD5}} = beam_lib:md5(File),
  453. Ret
  454. end,
  455. filelib:wildcard("*.beam", EbinDir)
  456. )).
  457. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  458. %% Global state
  459. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  460. init_globals(Options) ->
  461. ets:new(globals, [named_table, set, public]),
  462. ets:insert(globals, {valid, true}),
  463. ets:insert(globals, {options, Options}).
  464. getopt(Option) ->
  465. maps:get(Option, ets:lookup_element(globals, options, 2)).
  466. %% Set a global flag that something about the appfiles is invalid
  467. set_invalid() ->
  468. ets:insert(globals, {valid, false}).
  469. is_valid() ->
  470. ets:lookup_element(globals, valid, 2).
  471. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  472. %% Utility functions
  473. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  474. %% Locate a file in a specified application
  475. locate(ebin_current, App, Suffix) ->
  476. ReleaseDir = getopt(beams_dir),
  477. AppStr = atom_to_list(App),
  478. case filelib:wildcard(ReleaseDir ++ "/**/ebin/" ++ AppStr ++ Suffix) of
  479. [File] ->
  480. {ok, File};
  481. [] ->
  482. undefined
  483. end;
  484. locate(src, App, Suffix) ->
  485. AppStr = atom_to_list(App),
  486. SrcDirs = getopt(src_dirs),
  487. case filelib:wildcard(SrcDirs ++ AppStr ++ Suffix) of
  488. [File] ->
  489. {ok, File};
  490. [] ->
  491. undefined
  492. end.
  493. bash(Script) ->
  494. bash(Script, []).
  495. bash(Script, Env) ->
  496. log("+ ~s~n+ Env: ~p~n", [Script, Env]),
  497. case cmd("bash", #{args => ["-c", Script], env => Env}) of
  498. 0 -> true;
  499. _ -> fail("Failed to run command: ~s", [Script])
  500. end.
  501. %% Spawn an executable and return the exit status
  502. cmd(Exec, Params) ->
  503. case os:find_executable(Exec) of
  504. false ->
  505. fail("Executable not found in $PATH: ~s", [Exec]);
  506. Path ->
  507. Params1 = maps:to_list(maps:with([env, args, cd], Params)),
  508. Port = erlang:open_port( {spawn_executable, Path}
  509. , [ exit_status
  510. , nouse_stdio
  511. | Params1
  512. ]
  513. ),
  514. receive
  515. {Port, {exit_status, Status}} ->
  516. Status
  517. end
  518. end.
  519. fail(Str) ->
  520. fail(Str, []).
  521. fail(Str, Args) ->
  522. log(Str ++ "~n", Args),
  523. halt(1).
  524. log(Msg) ->
  525. log(Msg, []).
  526. log(Msg, Args) ->
  527. io:format(standard_error, Msg, Args).
  528. otp_standard_apps() ->
  529. [ssl, mnesia, kernel, asn1, stdlib].