-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
365 lines (313 loc) · 10.6 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
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
/*jslint node: true */
"use strict";
var fs = require("fs");
var rc = require("rc")("npm");
var npm = require("npm");
var path = require('path');
var STATIC = require("./constant");
//We will store all registry links at user level in .npmregistry file
var RPATH = process.env.HOME + "/.npmregistry";
var FILENAME = ".registryInfo";
const YARNRC = path.join(process.env.HOME, '.yarnrc');
/**
* Module exports.
* @public
*/
module.exports.usage = usage;
module.exports.init = init;
module.exports.ls = list;
module.exports.list = list;
module.exports.add = add;
module.exports.remove = remove;
module.exports.use = change;
module.exports.change = change;
module.exports.checkArgs = checkArgs;
function checkArgs(possibleActions, cmd) {
return possibleActions.indexOf(cmd);
}
/**
* [usage description]
* @return {[type]} [description]
*/
function usage(message) {
if (message === "error") {
console.log("Oopps there is something wrong. Check your params.");
}
console.log(`
You can run Switch Registry as
${STATIC.COLORS.FgGreen}
switch-registry {command} {arguments}
${STATIC.COLORS.Reset}
----------------------------------------------
Command Description
----------------------------------------------
init | Initialize base files and entries
usage | Display this help
ls | Display list of added registries
add | Add a new registry
remove | Remove an existing registry
use | Change to other existing registry
Short Command npmrs
--------------------
npmrs {command} {arguments}
`);
console.log(process.env.HOME);
return "";
}
/**
* [fetchFileData description]
* @param {[type]} str [description]
* @return {Boolean} [description]
*/
function fetchFileData(str) {
var data = "";
try {
return JSON.parse(str);
} catch (e) {
return {}; //Just return blank if there is any error
//TODO : Need to check if this failure will case any issue.
}
}
/**
* [showFormatedData Function will show all added registries and mark currently active one]
* @param {object} data [will contain single entry of added registry]
*/
function showFormatedData (data) {
var activeMark = '';
//Check and mark active registry with > symbol
if(data.active === true) {
activeMark = '>';
}
console.log(` ${activeMark} `,` ${data.name} `,`${data.url}`);
return true;
}
function addToFile(data) {
fs.writeFile(RPATH + "/" + FILENAME, JSON.stringify(data), "utf8", function (
err
) {
if (err) console.log(err);
});
}
function getCurrentRegistry() {
//Fetch current registry
//TODO: Think of a better way to manage this, we can use exec but
//TODO: that is also not a very good idea
try {
return rc.registry.slice(-1) === "/" ? rc.registry : rc.registry + "/";
} catch (e) {
return "https://registry.npmjs.org/";
}
}
function initRegistryFile(data) {
//Convert file data to Object -- At this point it will be blank
//TODO: Have to check if data is there
//TODO: If data is there then normal additon will happen only if it's not there
var url = getCurrentRegistry();
var currData = fetchFileData(data);
//Adding default entry
currData.Default = { name: "Default", active: true, url: url };
//Convert back to JSON string
addToFile(currData);
}
function init() {
//Create npmregistry
if (!fs.existsSync(RPATH)) {
//Create file
fs.mkdirSync(RPATH);
}
//Save current registry to registry file if its npmjs default registry
//TODO : Will check for npmjs thing later, right now considering current one as default
fs.readFile(RPATH + "/" + FILENAME, "utf8", function readFileCallback(
err,
data
) {
if (err) {
fs.open(RPATH + "/" + FILENAME, "w+", function readFileCallback(
err,
data
) {
initRegistryFile("");
});
//TODO: Create file here and call add data function
} else {
initRegistryFile(data);
}
});
}
/**
* Function will list down all added registry
* @param {[type]} args [description]
*/
function list(args) {
fs.readFile(RPATH + "/" + FILENAME, "utf8", function readFileCallback(
err,
data
) {
if (err) {
init();
//TODO: Create file here and call add data function
} else {
//Convert file data to Object -- At this point it will be blank
var currData = fetchFileData(data);
for (var key in currData) {
showFormatedData(currData[key]);
}
}
});
}
/**
* Function will add new custom registry
* @param {[type]} args [description]
*/
function add(args) {
var currData = {};
/* Proceed only if parameters are all valid */
if (
checkRequiredParams(args.length, STATIC.REQ_PARAM_LEN.add) &&
validateUrl(args[2]) &&
validateKey(args[1])
) {
fs.readFile(RPATH + "/" + FILENAME, "utf8", function (err, data) {
if (err) {
init();
//TODO: Create file here and call add data function
} else {
//Convert file data to Object
currData = fetchFileData(data);
if (typeof currData[args[1]] === "undefined") {
currData[args[1]] = { name: args[1], active: false, url: args[2] };
fs.writeFile(
RPATH + "/" + FILENAME,
JSON.stringify(currData),
function (err) {
if (err) throw err;
console.log(
`New registry entry with key ${args[1]} added successfully.`
);
}
);
} else {
console.log(`${STATIC.COLORS.FgRed}Another entry with key "${
args[1]
}" already exist, Please use another key to add
${STATIC.COLORS.Reset}`);
}
}
});
} else {
console.log("Error. Please check params.");
}
}
/**
* Function will remove existing custom registry by name
* @param {[type]} args [description]
*/
function remove(args) {
var currData = {};
fs.readFile(RPATH + "/" + FILENAME, "utf8", function (err, data) {
if (err) {
init();
//TODO: Create file here and call add data function
} else {
//Convert file data to Object
currData = fetchFileData(data);
if (currData[args[1]]) {
delete currData[args[1]];
fs.writeFile(RPATH + "/" + FILENAME, JSON.stringify(currData), function (
err
) {
if (err) throw err;
console.log("complete");
});
}
}
});
}
/**
* Function will change any existing custom registry by name
* @param {[type]} args [description]
*/
function change(args) {
let changeYarn = true;
let changeNpm = true;
npm.load(function (err) {
if (err) return "";
fs.readFile(RPATH + "/" + FILENAME, "utf8", function (err, data) {
if (err) {
init();
//TODO: Create file here and call add data function
} else {
//Convert file data to Object
var currData = fetchFileData(data);
if (currData[args[1]]) {
var changeTo = currData[args[1]];
const changeModifier = args[2] ? args[2] : "";
if(changeModifier === "yarn") changeNpm = false;
else if(changeModifier === "npm") changeYarn = false;
// Change Yarn registry
if (changeYarn) {
fs.writeFile(YARNRC, 'registry "' + changeTo.url + '"', function (err) {
if (err) throw err;
console.log(`
YARN Registry is set to: ${STATIC.COLORS.FgGreen}${changeTo.url}${STATIC.COLORS.Reset}
`);
});
}
//Change npm registry
if(changeNpm) {
npm.commands.config(["set", "registry", changeTo.url], function (
err,
data
) {
if (err) return "";
var newR = npm.config.get("registry");
console.log(`
npm registry is set to ${STATIC.COLORS.FgGreen}${newR}${STATIC.COLORS.Reset}
Updating configurations ....`);
//Setting all active to false
for (var key in currData) {
if (currData.hasOwnProperty(key)) {
currData[key].active = false;
}
}
//Setting newly activated registry to active
currData[args[1]].active = true;
//Update settings with new changes
fs.writeFile(RPATH + "/" + FILENAME, JSON.stringify(currData), function (
err
) {
if (err) throw err;
console.log(` All Done.!!!`);
});
});
}
} else {
console.log(` No registry exist with ${args[1]}. Please use switch-registry ls to list all existing entries.`);
}
}
});
});
}
function showErrors(options) { }
/**
* Function will validate if required number of parameters are passed
* @param number argsLength [length of parameters passed]
* @param number requiredLength [length of required parameters]
* @return boolean
*/
function checkRequiredParams(argsLength, requiredLength) {
if (argsLength - 1 < requiredLength) {
return false;
}
return true;
}
/**
* Function will validate given url
* @param string url; return boolean
*/
function validateUrl(url) {
return /^(?:\w+:)?\/\/([^\s\.]+\.\S{2}|localhost[\:?\d]*)\S*$/.test(url);
}
function validateKey(key) {
return /^[a-z0-9]+$/i.test(key);
}