forked from bgotink/montana
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
105 lines (83 loc) · 2.69 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
'use strict';
var path = require('path');
var impl;
try {
impl = require('./lib/impl/' + process.platform);
} catch (e) {
console.error('Unsupported platform: ' + process.platform);
process.exit(1);
}
var rootPromise = Promise.resolve();
if (impl.init) {
rootPromise = impl.init();
}
module.exports = exports = Montana;
var kCwd = Symbol('cwd');
var kDirectory = Symbol('directory');
var kResolvedDirectory = Symbol('resolvedDirectory');
var kStorage = Symbol('storage');
var kResolvedStorage = Symbol('resolvedStorage');
var kOptions = Symbol('options');
function Montana(directory, storage, options) {
options = options || {};
this[kOptions] = options;
this[kCwd] = options.cwd || process.cwd();
this[kDirectory] = directory;
this[kResolvedDirectory] = path.resolve(this[kCwd], directory);
this[kStorage] = storage;
this[kResolvedStorage] = path.resolve(this[kCwd], storage);
}
function wrapPrototypeFunction(fn) {
return function wrappedFunction() {
var args = Array.prototype.slice.call(arguments);
var self = this;
return rootPromise.then(function () {
return fn.apply(self, args);
});
};
}
Montana.prototype = {
constructor: Montana,
hasVersion: wrapPrototypeFunction(function hasVersion(name) {
return impl.exists(this.getVersionPath(name));
}),
getVersionPath: function getVersionPath(name) {
return path.join(this[kResolvedStorage], name);
},
isActive: wrapPrototypeFunction(function isActive() {
return impl.isMounted(this[kResolvedDirectory]);
}),
umount: wrapPrototypeFunction(function umount() {
return this.isActive().then(function (active) {
if (active) {
return impl.unmount(this[kResolvedDirectory]);
}
}.bind(this));
}),
mount: wrapPrototypeFunction(function link(version) {
return this.hasVersion(version).then(function (hasVersion) {
if (!hasVersion) {
throw new Error('Unknown version ' + version + ' in ' + this[kStorage]);
}
return this.umount();
}.bind(this))
.then(function () {
return impl.mount(this.getVersionPath(version), this[kResolvedDirectory]);
}.bind(this));
}),
create: wrapPrototypeFunction(function create(version) {
return Promise.all([
this.hasVersion(version),
this.isActive()
]).then(function (res) {
if (res[0]) {
throw new Error('Version ' + version + ' already exists in ' + this[kStorage]);
}
if (res[1]) {
throw new Error('Directory ' + this[kDirectory] + ' is already managed, nothing to create');
}
return impl.create(this.getVersionPath(version), this[kResolvedDirectory]);
}.bind(this));
})
};
Montana.prototype.unmount = Montana.prototype.umount;