/
difio.js
280 lines (263 loc) · 7.65 KB
/
difio.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
/*************************************************************************************
*
* Copyright (c) 2012, Svetlozar Argirov <zarrro [AT] gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*************************************************************************************/
// dLog - used for debug logging
var dLog = function(){}
var dependenciesDebug = false;
// loadNpm() - load npm module.
// Workaround the fact that for some unknow reason, by default npm is installed in
// directory which is not on require.paths and so it is not loadable with simple 'require'
function loadNpm() {
var npm;
// Try to load npm from NODE_PATH, not very probable to succeed :)
try {
npm = require('npm');
} catch(e) {
}
var path = require("path");
// Try to load NPM from where nodejs install dir. This should work for all 0.6.x
// versions and also some 0.4.x.
if(!npm) {
var p = path.join(process.execPath, "../../lib", "node_modules", "npm");
try {
npm = require(p);
} catch(e) {
}
}
// Try to find npm on the require paths, but only for versions < 0.6.x,
// since require.paths is missing in 0.6.x
if(!npm && (process.version.split('.')[1]<6) ) {
for(var i in require.paths) {
var p = require.paths[i];
if(path.basename(p) == "node") {
p = path.join(p, "..", "node_modules", "npm");
try {
npm = require(p);
if(npm) {
break;
}
} catch (e) {
}
}
}
}
if(!npm){
throw new Error("Cannot find module 'npm' !");
}
return npm;
}
var DATA_TEMPLATE = {
'user_id' : null,
'app_name' : null,
'app_uuid' : null,
'app_type' : 'nodejs',
'app_url' : null,
'app_vendor' : null,
'pkg_type' : null,
'installed' : [],
};
var DIFIO_HOST = "difio-otb.rhcloud.com";
var DIFIO_REGISTER_PATH = "/application/register/";
function configure(options) {
if(options.url) {
var url = require('url').parse(options.url);
DIFIO_HOST = url.hostname;
DIFIO_REGISTER_PATH = url.pathname;
}
for(var k in DATA_TEMPLATE){
if(options[k] != undefined) {
DATA_TEMPLATE[k] = options[k];
}
}
return module.exports;
}
module.exports.configure = configure;
// recurseDependencies(data, out) - recurse the dependency tree and return a flat
// list with package dependencies
// data - dependency tree as provided by npm
// out - initial output data
function recurseDependencies(data, out) {
var dep = data.dependencies;
out = out || {};
for (var k in dep) {
if(dependenciesDebug) {
dLog(">dep>["+k+"]=", dep[k]);
}
// Ignore all kind of not resolved dependencies
if (typeof dep[k] === "string") {
continue;
}
out[dep[k]._id] ={
n: dep[k].name,
v: dep[k].version,
};
recurseDependencies(dep[k], out);
}
return out;
}
// listDependencies(cb) - lists dependencies described in the current directory
// cb - callback called wiht single parameter, the dependency list
function listDependencies(cb) {
var npm = loadNpm()
, conf = { command: "ls" };
npm.load(conf, function(er) {
if (er) {
throw new Error("Couldn't load 'npm'. Error: " + er);
};
npm.commands["ls"]([], true, function(er, data) {
if (er) {
throw new Error("'npm ls' failed. Error: " + er)
return;
};
var depData = recurseDependencies(data);
if(cb) {
cb(depData);
}
});
});
}
// httpPost(options, json_data, cb) - POST json data
// options - http.request() options
// json_data - object to be converted to JSON and send as json_data parameter
// cb - callback , if present called on error or success
function httpPost(options, json_data, cb) {
var https = require('https');
dLog("REQ TO: " + JSON.stringify(options));
var req = https.request(options);
req.on('response', function(res){
var resData = '';
res.on('data', function (chunk) {
dLog("RES_DATA: " + chunk);
resData += chunk;
});
res.on('end', function (chunk) {
dLog("RESPONSE[" + res.statusCode+"] "+ resData);
if( res.statusCode != 200 || (res.headers['content-type'].indexOf("application/json")!=0)) {
var errMsg = "Error "+ res.statusCode + " while posting data to " + options.host +"\n";
errMsg += resData;
if(cb) {
cb(null,errMsg);
} else {
throw new Error(errMsg);
}
return;
}
var response = JSON.parse(resData);
if(cb) {
cb(response,null);
}
});
});
req.on('upgrade', function(res, socket, upgradeHead){
console.log("POSTING got upgrade ... WTF? :", upgradeHead);
});
req.on('error', function (e) {
dLog("Error while posting data:" + e);
throw new Error("Error while posting data:" + e);
});
dLog("POSTING: " + JSON.stringify(json_data));
req.write(encodeURI('json_data=' + JSON.stringify(json_data)));
req.end();
dLog("POSTING DONE: Waiting for response.");
}
function getDepsAsJSON(depData){
var postData = DATA_TEMPLATE;
var deps = [];
for(var i in depData){
dLog("DEP: [" + i + "]=" + JSON.stringify(depData[i]));
deps.push(depData[i]);
}
postData['installed'] = deps;
return postData;
}
// postToDifio(cb) - send package info to Difio
// cb - callback , if present called on error or success
function postToDifio(cb){
listDependencies(function(depData){
var postData = getDepsAsJSON(depData);
var thisModule, vendorModule;
for(var k in depData){
if(k.indexOf('common-nodejs-difio')==0){
thisModule = depData[k]['n'] + '/' + depData[k]['v'];
}
if(/difio-(.*?)-nodejs/.test(k)){
vendorModule = depData[k]['n'] + '/' + depData[k]['v'];
}
}
var options = {
host: DIFIO_HOST,
path: DIFIO_REGISTER_PATH,
method: 'POST',
headers: {
'User-Agent' : 'common-nodejs-difio'
}
};
if(thisModule || vendorModule){
options.headers['User-Agent'] = vendorModule + ' ' + thisModule;
}
httpPost(options, postData, cb)
});
}
module.exports.postToDifio = postToDifio;
// Command line tool implementation
function cli(){
var printJSON = false;
for(var i in process.argv) {
if(process.argv[i] == "--debug") {
dLog = function() {
console.log.apply(this, arguments);
}
}
if(process.argv[i] == "--dependenciesDebug") {
dependenciesDebug = true;
}
if(process.argv[i] == "--printJSON") {
printJSON = true;
}
}
process.on('uncaughtException', function (err) {
console.log(err.message);
});
if(printJSON){
listDependencies(function(depData){
var postData = getDepsAsJSON(depData);
console.log(JSON.stringify(postData));
});
return;
}
dLog("Difio: Starting in dir " + process.cwd() + " ...");
try {
postToDifio(function(result, error){
if(result) {
console.log("Difio: " + result['message']);
} else {
console.log("Difio: " + error);
}
});
} catch(e) {
console.log("Difio client exception:");
console.log(e.message);
}
dLog("Difio: Done!");
}
module.exports.cli = cli;