-
Notifications
You must be signed in to change notification settings - Fork 16
/
index.js
90 lines (79 loc) · 2.01 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
/**
* Module dependencies
*/
var fs = require("fs")
, join = require("path").join;
/**
* Read and parse .netrc
*
* @param {String} file
* @return {Object}
* @api public
*/
module.exports = exports = function(file) {
var home = process.env.HOME || process.env.HOMEPATH
, file = file || join(home, ".netrc");
if(!fs.existsSync(file)) return {};
var netrc = fs.readFileSync(file, "UTF-8");
return exports.parse(netrc);
};
/**
* Parse netrc
*
* @param {String} content
* @return {Object}
* @api public
*/
exports.parse = function(content) {
// Remove comments
var lines = content.split('\n');
for (var n in lines) {
var i = lines[n].indexOf('#');
if (i > -1) lines[n] = lines[n].substring(0,i);
}
content = lines.join('\n');
var tokens = content.split(/[ \t\n\r]+/)
, machines = {}
, m = null
, key = null;
//if first index in array is empty string, strip it off (happens when first line of file is comment. Breaks the parsing)
if (tokens[0] === "") {
tokens.shift();
}
for(var i = 0; i < tokens.length; i+=2) {
var key = tokens[i]
, value = tokens[i+1];
// Whitespace
if(!key || !value) continue;
// We have a new machine definition
if(key === "machine") {
m = {};
machines[value] = m;
}
// key=value
else {
m[key] = value;
}
}
return machines
};
/**
* Generate contents of netrc file from objects.
* @param {Object} machines as returned by `netrc.parse`
* @return {String} text of the netrc file
*/
exports.unparse = function(machines){
var lines = [],
keys = Object.getOwnPropertyNames(machines).sort();
keys.forEach(function(key){
lines.push('machine ' + key);
var machine = machines[key];
var attrs = Object.getOwnPropertyNames(machine).sort();
attrs.forEach(function(attr){
if(typeof(machine[attr]) === 'string'){
lines.push(' ' + attr + ' ' + machine[attr]);
}
});
});
return lines.join('\n');
};