UNPKG

9.01 kBJavaScriptView Raw
1/**
2* Copyright (c) Microsoft. All rights reserved.
3*
4* Licensed under the Apache License, Version 2.0 (the "License");
5* you may not use this file except in compliance with the License.
6* You may obtain a copy of the License at
7* http://www.apache.org/licenses/LICENSE-2.0
8*
9* Unless required by applicable law or agreed to in writing, software
10* distributed under the License is distributed on an "AS IS" BASIS,
11* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12* See the License for the specific language governing permissions and
13* limitations under the License.
14*/
15
16'use strict';
17
18var _ = require('underscore');
19var fs = require('fs');
20var path = require('path');
21
22var utilsCore = require('./util/utilsCore');
23
24function CmdLoader(topCmd, mode) {
25 this.topCmd = topCmd;
26 this.cmdMode = mode;
27 this.cmdMetadataFile = path.join(__dirname, 'plugins.' + this.cmdMode + '.json');
28 this.cmdBasePath = __dirname;
29}
30
31_.extend(CmdLoader.prototype, {
32 harvestPlugins: function (topLevelOnly) {
33 var self = this;
34 var plugins = this._loadCmdsFromFolder(path.join(this.cmdBasePath, 'commands'), false);
35 plugins.forEach(function (plugin) { plugin.init(self.topCmd); });
36
37 if (!topLevelOnly) {
38 // Load mode specific plugins
39 var modePlugins = this._loadCmdsFromFolder(path.join(this.cmdBasePath, 'commands', this.cmdMode), true);
40 modePlugins.forEach(function (plugin) { plugin.init(self.topCmd); });
41 }
42 },
43
44 harvestModules: function () {
45 var self = this;
46
47 var basePath = path.dirname(__filename);
48
49 var walkPath = path.join(basePath, '../node_modules');
50 var harvestPaths = [walkPath];
51
52 while (path.basename(walkPath) === 'node_modules' && path.dirname(walkPath) !== 'npm') {
53 var nextPath = path.join(walkPath, '../..');
54 if (nextPath === walkPath) {
55 break;
56 }
57 harvestPaths.push(nextPath);
58 walkPath = nextPath;
59 }
60
61 var modules = [];
62 harvestPaths.forEach(function (harvestPath) {
63 modules = modules.concat(self._loadCmdsFromNodeModules(harvestPath));
64 });
65
66 modules.forEach(function (module) {
67 module.plugin.init(self.topCmd);
68 });
69 },
70
71 initFromCmdMetadata: function (AzureCli) {
72 var self = this;
73 var initCategory = function (category, parent) {
74 function process(entity, entityParent) {
75 var newEntity = new AzureCli(entity.name, entityParent);
76
77 if (entity.description) {
78 newEntity._description = entity.description;
79 }
80
81 //TODO, for some fields, we create wrapper functions here,
82 //so that existing code won't break. We should get rid of them soon.
83 newEntity.description = function () {
84 return newEntity._description;
85 };
86
87 newEntity.fullName = function () {
88 return entity.fullName;
89 };
90
91 newEntity._usage = entity.usage;
92 newEntity.usage = function () {
93 return newEntity._usage;
94 };
95
96 newEntity.filePath = entity.filePath ?
97 path.resolve(self.cmdBasePath, entity.filePath) : entity.filePath;
98 newEntity.stub = true;
99
100 if (entity.options) {
101 for (var o in entity.options) {
102 newEntity.option(entity.options[o].flags, entity.options[o].description);
103 }
104 }
105
106 return newEntity;
107 }
108
109
110 var newCategory = category;
111 //can't invoke "process" for top category, which would new
112 //up a top AzureCli and get us into an infinite loop.
113 if (parent) {
114 newCategory = process(category, parent);
115 }
116
117 for (var i = 0 ; i < category.commands.length; i++) {
118 newCategory.commands[i] = (process(category.commands[i], newCategory));
119 }
120
121 if (!newCategory.categories) {
122 newCategory.categories = {};
123 }
124
125 for (var j in category.categories) {
126 newCategory.categories[j] = initCategory(category.categories[j], newCategory);
127 }
128
129 return newCategory;
130 };
131
132 var data = fs.readFileSync(this.cmdMetadataFile);
133 var cachedPlugins = JSON.parse(data);
134 var plugins = initCategory(cachedPlugins);
135
136 this.topCmd.commands = plugins.commands;
137 this.topCmd.categories = plugins.categories;
138 },
139
140 saveCmdMetadata: function () {
141 var metadate = this._serializeCategory(this.topCmd);
142 fs.writeFileSync(this.cmdMetadataFile, JSON.stringify(metadate, null, 2));
143 },
144
145 cmdMetadataExists: function () {
146 return utilsCore.pathExistsSync(this.cmdMetadataFile);
147 },
148
149 _loadCmdsFromFolder: function (scanPath, recursively) {
150 var results = utilsCore.getFiles(scanPath, recursively);
151
152 results = results.filter(function (filePath) {
153 var extname = path.extname(filePath);
154 if (filePath.substring(0, 5) === 'tmp--') {
155 return false;
156 } else if (extname !== '.js' && extname !== '._js') {
157 //Skip unrelated/temp files
158 return false;
159 }
160 return true;
161 });
162
163 if (process.env.PRECOMPILE_STREAMLINE_FILES) {
164 results = results.filter(function (filePath) {
165 if (filePath.substring(filePath.length - 4) === '._js') {
166 return false;
167 }
168 return true;
169 });
170 }
171
172 // sort them so they load in a predictable order
173 results = results.sort();
174
175 // skip directories
176 results = results.filter(function (filePath) {
177 return fs.statSync(filePath).isFile();
178 });
179
180 // load modules
181 results = results.map(function (filePath) {
182 return require(filePath);
183 });
184
185 // look for exports.init
186 results = results.filter(function (entry) {
187 return entry.init !== undefined;
188 });
189 return results;
190 },
191
192 _loadCmdsFromNodeModules: function (scanPath) {
193 var results = fs.readdirSync(scanPath);
194
195 results = results.map(function (moduleName) {
196 return {
197 moduleName: moduleName,
198 modulePath: path.join(scanPath, moduleName)
199 };
200 });
201
202 results = results.filter(function (item) {
203 try {
204 item.moduleStat = fs.statSync(item.modulePath);
205 } catch (error) {
206 return false;
207 }
208 return item.moduleStat.isDirectory();
209 });
210
211 results = results.filter(function (item) {
212 item.packagePath = path.join(item.modulePath, 'package.json');
213 item.packageStat = utilsCore.pathExistsSync(item.packagePath) ? fs.statSync(item.packagePath) : undefined;
214 return item.packageStat && item.packageStat.isFile();
215 });
216
217 results = results.filter(function (item) {
218 try {
219 item.packageInfo = JSON.parse(fs.readFileSync(item.packagePath));
220 return item.packageInfo && item.packageInfo.plugins && item.packageInfo.plugins['azure-cli'];
221 }
222 catch (err) {
223 return false;
224 }
225 });
226
227 results = this._flatten(results.map(function (item) {
228 var plugins = item.packageInfo.plugins['azure-cli'];
229 if (!_.isArray(plugins)) {
230 plugins = [plugins];
231 }
232
233 return plugins.map(function (relativePath) {
234 return {
235 context: item,
236 pluginPath: path.join(item.modulePath, relativePath)
237 };
238 });
239 }));
240
241 results = results.filter(function (item) {
242 item.plugin = require(item.pluginPath);
243 return item.plugin.init;
244 });
245
246 return results;
247 },
248
249 _flatten: function (arrays) {
250 var result = [];
251 arrays.forEach(function (array) {
252 result = result.concat(array);
253 });
254 return result;
255 },
256
257 _serializeIndividualEntity: function (entity) {
258 //TODO: split out the concept of category or command
259 var cmdOrCat = {};
260
261 if (entity.name) {
262 cmdOrCat.name = entity.name;
263 }
264
265 if (entity.description) {
266 cmdOrCat.description = entity.description();
267 }
268
269 if (entity.fullName) {
270 cmdOrCat.fullName = entity.fullName();
271 }
272
273 if (entity.usage) {
274 cmdOrCat.usage = entity.usage();
275 }
276
277 if (entity.filePath) {
278 //Normalize the file path, so that it can be used for both linux and windows.
279 cmdOrCat.filePath = path.relative(this.cmdBasePath, entity.filePath).split('\\').join('/');
280 }
281
282 if (entity.options) {
283 cmdOrCat.options = entity.options;
284 }
285
286 return cmdOrCat;
287 },
288
289 _serializeCategory: function (category) {
290 var cat = this._serializeIndividualEntity(category);
291 cat.commands = [];
292 cat.categories = {};
293
294 if (category.commands) {
295 for (var i in category.commands) {
296 cat.commands.push(this._serializeIndividualEntity(category.commands[i]));
297 }
298 }
299
300 if (category.categories) {
301 for (var j in category.categories) {
302 var currentCategory = this._serializeCategory(category.categories[j]);
303 cat.categories[currentCategory.name] = currentCategory;
304 }
305 }
306
307 return cat;
308 }
309
310});
311
312module.exports = CmdLoader;
\No newline at end of file