UNPKG

2.89 kBJavaScriptView Raw
1import fs from "fs-extra";
2import fsPath from "path";
3import Promise from "bluebird";
4import { getLocalPackage } from "./app-package";
5import { pathExists } from "./util";
6import log from "./log";
7
8const fsRemove = Promise.promisify(fs.remove);
9const fsReadDir = Promise.promisify(fs.readdir);
10
11
12
13
14
15
16
17/**
18 * Downloads the app from the remote repository.
19 *
20 * @param id: The unique ID of the application.
21 * @param repo: The repository to pull from.
22 * @param subFolder: The sub-folder into the repo (if there is one).
23 * @param branch: The branch to query.
24 * @param options:
25 * - force: Flag indicating if the repository should be downloaded if
26 * is already present on the local disk.
27 * Default: true
28 *
29 * @return {Promise}.
30 */
31export default (id, localFolder, repo, subFolder, branch, options = {}) => {
32 const force = options.force === undefined ? true : options.force;
33
34 return new Promise((resolve, reject) => {
35
36 const localPackage = () => getLocalPackage(id, localFolder).catch(err => reject(err));
37
38 const onComplete = (wasDownloaded, result) => {
39 Promise.coroutine(function*() {
40 const local = yield localPackage().catch(err => reject(err));
41 result.version = local.json.version;
42 if (wasDownloaded) {
43 log.info(`...downloaded '${ id }'.`);
44 }
45 resolve(result);
46 })();
47 };
48
49
50 const download = () => {
51 // Check whether another process is already downloading the repo.
52 Promise.coroutine(function*() {
53 // Download files.
54 log.info(`Downloading '${ id }'...`);
55 const files = yield repo.get(subFolder, { branch }).catch(err => reject(err));
56
57 // Delete the old files.
58 // Note: The `node_modules` is retained so that NPM install does not
59 // need to be rerun unless there is a dependency change.
60 if (yield pathExists(localFolder)) {
61 const fileNames = yield fsReadDir(localFolder).catch(err => reject(err));
62 for (let fileName of fileNames) {
63 if (fileName !== "node_modules") {
64 yield fsRemove(fsPath.join(localFolder, fileName));
65 }
66 }
67 }
68
69 // Save the files to disk.
70 yield files.save(localFolder).catch(err => reject(err));
71
72 // Finish up.
73 onComplete(true, { id });
74 })();
75 };
76
77 // Don't download if the app files already exist.
78 Promise.coroutine(function*() {
79 if (force) {
80 download();
81 } else {
82 const local = yield localPackage();
83 if (local.exists) {
84 onComplete(false, { alreadyExists: true });
85 } else {
86 download();
87 }
88 }
89 })();
90 });
91};