UNPKG

2.54 kBJavaScriptView Raw
1/**
2 * Module dependencies
3 */
4
5var fs = require('fs');
6var join = require('path').join;
7
8/**
9 * Read and parse .netrc
10 *
11 * @param {String} file
12 * @return {Object}
13 * @api public
14 */
15
16module.exports = exports = function(file) {
17 var home = getHomePath();
18
19 if (!file && !home) return {};
20 file = file || join(home, '.netrc');
21
22 if (!file || !fs.existsSync(file)) return {};
23 var netrc = fs.readFileSync(file, 'UTF-8');
24 return exports.parse(netrc);
25};
26
27/**
28 * Parse netrc
29 *
30 * @param {String} content
31 * @return {Object}
32 * @api public
33 */
34
35exports.parse = function(content) {
36 // Remove comments
37 var lines = content.split('\n');
38 for (var n in lines) {
39 var i = lines[n].indexOf('#');
40 if (i > -1) lines[n] = lines[n].substring(0, i);
41 }
42 content = lines.join('\n');
43
44 var tokens = content.split(/[ \t\n\r]+/);
45 var machines = {};
46 var m = null;
47 var key = null;
48
49 // if first index in array is empty string, strip it off (happens when first line of file is comment. Breaks the parsing)
50 if (tokens[0] === '') tokens.shift();
51
52 for(var i = 0, key, value; i < tokens.length; i+=2) {
53 key = tokens[i];
54 value = tokens[i+1];
55
56 // Whitespace
57 if (!key || !value) continue;
58
59 // We have a new machine definition
60 if (key === 'machine') {
61 m = {};
62 machines[value] = m;
63 }
64 // key=value
65 else {
66 m[key] = value;
67 }
68 }
69
70 return machines
71};
72
73/**
74 * Generate contents of netrc file from objects.
75 * @param {Object} machines as returned by `netrc.parse`
76 * @return {String} text of the netrc file
77 */
78
79exports.format = function format(machines){
80 var lines = [];
81 var keys = Object.getOwnPropertyNames(machines).sort();
82
83 keys.forEach(function(key){
84 lines.push('machine ' + key);
85 var machine = machines[key];
86 var attrs = Object.getOwnPropertyNames(machine).sort();
87 attrs.forEach(function(attr){
88 if (typeof(machine[attr]) === 'string') lines.push(' ' + attr + ' ' + machine[attr]);
89 });
90 });
91 return lines.join('\n');
92};
93
94/**
95 * Serialise contents objects to netrc file.
96 *
97 * @param {Object} machines as returned by `netrc.parse`
98 * @api public
99 */
100
101exports.save = function save(machines){
102 var home = getHomePath();
103 var destFile = join(home, '.netrc');
104 var data = exports.format(machines) + '\n';
105 fs.writeFileSync(destFile, data);
106};
107
108/**
109 * Get the home path
110 *
111 * @return {String} path to home directory
112 * @api private
113 */
114
115function getHomePath() {
116 return process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE;
117}