-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathconfig-file.js
More file actions
322 lines (270 loc) · 8.28 KB
/
Copy pathconfig-file.js
File metadata and controls
322 lines (270 loc) · 8.28 KB
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
// Copyright IBM Corp. 2015,2019. All Rights Reserved.
// Node module: loopback-workspace
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
const g = require('strong-globalize')();
module.exports = function(ConfigFile) {
const assert = require('assert');
const app = require('../../server/server');
const path = require('path');
const async = require('async');
const fs = require('fs-extra');
const glob = require('glob');
const ROOT_COMPONENT = '.';
const groupBy = require('lodash').groupBy;
const debug = require('debug')('workspace:config-file');
/**
* Various definitions in the workspace are backed by a `ConfigFile`.
* This class provides a very simple abstraction from the `fs` module,
* to make working with config files simpler throughout the workspace.
*
* @property {String} path Workspace relative path to the config file
* @property {*} data Config data from file. Defaults to `{}`.
*
* @class ConfigFile
* @inherits Model
*/
/**
* Initialize and save a config file.
*/
ConfigFile.create = function(obj, cb) {
const configFile = new ConfigFile(obj);
configFile.save(cb);
};
/**
* Create and load a `ConfigFile` object with the given path.
*
* @param {String} path
* @callback {Function} callback
* @param {Error} err
* @param {ConfigFile} configFile
*/
ConfigFile.loadFromPath = function(path, cb) {
const configFile = new ConfigFile({
path: path,
});
configFile.load(function(err) {
if (err) return cb(err);
cb(null, configFile);
});
};
/**
* Load and parse the data in the file. If a file does not exist,
* the `data` property will be null.
*/
ConfigFile.prototype.load = function(cb) {
const configFile = this;
if (!this.path) return cb(new Error(g.f('no path specified')));
const absolutePath = configFile.constructor.toAbsolutePath(this.path);
async.waterfall([
configFile.exists.bind(configFile),
load,
setup,
], cb);
function load(exists, cb) {
if (exists) {
fs.readJson(absolutePath, function(err, data) {
if (err && err.name === 'SyntaxError') {
err.message = g.f('Cannot parse %s: %s', configFile.path, err.message);
}
cb(err, err ? undefined : data);
});
} else {
cb(null, null);
}
}
function setup(data, cb) {
debug('loaded [%s] %j', configFile.path, data);
configFile.data = data || {};
cb();
}
};
/**
* Stringify and save the data to a file.
*
* @callback {Function} callback
* @param {Error} err
*/
ConfigFile.prototype.save = function(cb) {
const configFile = this;
if (!this.path) return cb(new Error(g.f('no path specified')));
const absolutePath = configFile.getAbsolutePath();
configFile.data = configFile.data || {};
debug('output [%s] %j', absolutePath, configFile.data);
fs.mkdirp(path.dirname(absolutePath), function(err) {
if (err) return cb(err);
fs.writeJson(absolutePath, configFile.data, {spaces: ' '}, cb);
});
};
/**
* Remove the file from disk.
*
* @callback {Function} callback
* @param {Error} err
*/
ConfigFile.prototype.remove = function(cb) {
const configFile = this;
if (!this.path) return cb(new Error(g.f('no path specified')));
const absolutePath = configFile.getAbsolutePath();
fs.unlink(absolutePath, cb);
};
/**
* Does the config file exist at `configFile.path`?
*
* @callback {Function} callback
* @param {Error} err
* @param {Boolean} exists
*/
ConfigFile.prototype.exists = function(cb) {
fs.exists(this.getAbsolutePath(), function(exists) {
cb(null, exists);
});
};
/**
* Get the path to the workspace directory. First check the env
* variable `WORKSPACE_DIR`. Otherwise default to `process.cwd()`.
*
* @returns {String}
*/
ConfigFile.getWorkspaceDir = function() {
return process.env.WORKSPACE_DIR || process.cwd();
};
/**
* Resolve the relative workspace path to a fully qualified
* absolute file path.
*
* @param {String} relativePath
* @returns {String}
*/
ConfigFile.toAbsolutePath = function(relativePath) {
return path.join(this.getWorkspaceDir(), relativePath);
};
/**
* See: ConfigFile.getAbsolutePath()
*/
ConfigFile.prototype.getAbsolutePath = function() {
return this.constructor.toAbsolutePath(this.path);
};
ConfigFile.find = function(entityFilter, cb) {
const Ctor = this;
const models = app.models();
if (!cb) {
cb = entityFilter;
entityFilter = function() { return true; };
}
let patterns = [];
const workspaceDir = this.getWorkspaceDir();
models.forEach(function(Model) {
if (!entityFilter(Model.modelName, Model.definition)) return;
const options = Model.settings || {};
if (options.configFiles) {
patterns = patterns.concat(options.configFiles);
}
});
patterns = patterns.concat(patterns.map(function(pattern) {
return path.join('*', pattern);
}));
async.map(patterns, find, function(err, paths) {
if (err) return cb(err);
// flatten paths into single list
let merged = [];
merged = merged.concat.apply(merged, paths);
const configFiles = merged.map(function(filePath) {
return new Ctor({path: filePath});
});
cb(null, configFiles);
});
function find(pattern, cb) {
// set strict to false to avoid perm issues
glob(pattern, {cwd: workspaceDir, strict: false}, cb);
}
};
ConfigFile.prototype.getExtension = function() {
return path.extname(this.path);
};
ConfigFile.prototype.getDirName = function() {
return path.basename(path.dirname(this.path));
};
ConfigFile.prototype.getFacetName = function() {
const dir = this.getDirName();
// NOTE: glob always returns the path using forward-slash even on Windows
// See: https://github.com/strongloop/generator-loopback/issues/12
const baseDir = this.path.split('/')[0];
const isRootComponent = dir === ROOT_COMPONENT ||
baseDir === this.path ||
baseDir === 'models';
const facetName = isRootComponent ? ROOT_COMPONENT : baseDir;
return facetName;
};
ConfigFile.findFacetFiles = function(cb) {
this.find(entityBelongsToFacet, function(err, configFiles) {
if (err) return cb(err);
const result =
groupBy(configFiles, function(configFile) {
return configFile.getFacetName();
});
cb(null, result);
});
};
function entityBelongsToFacet(name, definition) {
return definition && definition.properties &&
definition.properties.facetName;
}
ConfigFile.findPackageDefinitions = function(cb) {
this.find(
function(name/* , definition */) { return name === 'PackageDefinition'; },
cb,
);
};
/**
* Get the filename exlcuding the extension.
*
* **Example:**
*
* `my-app/my-file.json` => `my-file`
*
* @returns {String}
*/
ConfigFile.prototype.getBase = function() {
return path.basename(this.path, this.getExtension());
};
/**
* From the given `configFiles`, get the first with a matching `base`
* (see: `configFile.getBase()`).
*
* @returns {ConfigFile}
*/
ConfigFile.getFileByBase = function(configFiles, base) {
assert(Array.isArray(configFiles));
let configFile;
for (let i = 0; i < configFiles.length; i++) {
configFile = configFiles[i];
if (configFile && configFile.getBase() === base) {
return configFile;
}
}
return null;
};
/**
* From the given `configFiles`, get an array of files that represent
* `ModelDefinition`s.
*
* @returns {ConfigFile[]}
*/
ConfigFile.getModelDefFiles = function(configFiles, facetName) {
assert(Array.isArray(configFiles));
let configFile;
const results = [];
for (let i = 0; i < configFiles.length; i++) {
configFile = configFiles[i];
// TODO(ritch) support other directories
if (configFile && configFile.getFacetName() === facetName &&
configFile.getDirName() === 'models') {
results.push(configFile);
}
}
return results;
};
ConfigFile.ROOT_COMPONENT = ROOT_COMPONENT;
};