UNPKG

2.67 kBJavaScriptView Raw
1import fsPath from "path";
2import Promise from "bluebird";
3import appInstall from "./app-install";
4import log from "./log";
5import { pathExists } from "./util";
6
7
8
9
10/**
11 * Downloads a new version of the app (if necessary) and restarts it.
12 * @param {String} id: The unique identifier of the app.
13 * @param {String} localFolder: The path to where the app it stored on the local disk.
14 * @param {Function} getVersion: Function that gets the version details.
15 * @param {Function} startDownload: Function that initiates a download.
16 * @param {Function} start: Function that starts the application.
17 * @param options
18 * - start: Flag indicating if the app should be started after an update.
19 * Default: true.
20 */
21export default (id, localFolder, getVersion, startDownload, start, options = {}) => {
22 return new Promise((resolve, reject) => {
23 Promise.coroutine(function*() {
24 let restart = false;
25 const restartAfterUpdate = options.start === undefined ? true : options.start;
26 const version = yield getVersion().catch(err => reject(err));
27 const result = { id, updated: false, installed: false, version: version.remote };
28
29 // Determine if the `node_modules` folder exists.
30 const nodeModulesPath = fsPath.join(localFolder, "node_modules");
31 const nodeModulesExist = yield pathExists(nodeModulesPath).catch(err => reject(err));
32
33 if (version.isUpdateRequired && !version.isDownloading) {
34 log.info();
35 log.info(
36 version.local
37 ? `Updating '${ id }' from v${ version.local } to v${ version.remote }...`
38 : `First time initialization of '${ id }' at v${ version.remote }...`
39 );
40
41 // Download remote files.
42 yield startDownload().catch(err => reject(err));
43 result.updated = true;
44 restart = true;
45 }
46
47 // NPM install if required.
48 if (!nodeModulesExist || version.isDependenciesChanged) {
49 log.info(`Running [npm install] for '${ id }'...`);
50 yield appInstall(localFolder);
51 log.info(`...[npm install] complete for '${ id }'`);
52 result.installed = true;
53 restart = true;
54 }
55
56 // Start the app if required.
57 if (restartAfterUpdate && restart) {
58 yield start().catch(err => reject(err));
59 }
60
61 // Log output.
62 if (result.updated) {
63 const msg = restartAfterUpdate && restart
64 ? `...updated and restarted '${ id }' to v${ version.remote }.`
65 : `...updated '${ id }' to v${ version.remote }.`;
66 log.info("");
67 log.info(msg);
68 }
69
70 // Finish up.
71 resolve(result);
72 })();
73 });
74};