-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmongorc-manager.js
executable file
·88 lines (79 loc) · 2.71 KB
/
mongorc-manager.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
const os = require('os');
const path = require('path');
const debug = require('debug')('mongorc-manager');
const package = require('./package.json');
const mongorcPath = path.join(os.homedir(), '.mongorc.js');
const mongorcBackupPath = path.join(os.homedir(), '.mongorc.original.js');
const WATERMARK = `managed by ${package.name}`;
function _checkMongorc(fileManager) {
debug(mongorcPath);
if(!fileManager.fileExistsRW(mongorcPath)) {
debug(`${mongorcPath} not found. Will create one.`);
return _createMongorc(fileManager);
}
let lines = fileManager.readAsArray(mongorcPath);
if (lines[0].includes(WATERMARK)) {
debug(`${mongorcPath} found and already managed`);
return lines;
}
debug(`${mongorcPath} found but not managed`);
_backupExistingFile(fileManager);
lines = _createMongorc(fileManager);
//Refer back to the old .mongorc.js so no previous
//configuration gets lost.
lines = _linkLibrary(mongorcBackupPath, fileManager, lines);
return lines;
}
function _backupExistingFile(fileManager) {
debug(`Backing up ${mongorcPath} to ${mongorcBackupPath}`);
return fileManager.rename(mongorcPath, mongorcBackupPath);
}
function _createMongorc(fileManager) {
debug(`Creating ${mongorcPath}`);
const lines = [`//${WATERMARK}//`];
fileManager.writeFromArray(mongorcPath, lines);
return lines;
}
function _linkLibrary(path, fileManager, lines) {
debug(`Linking ${path} to ${mongorcPath}`);
const alreadyLinkedPath = lines.find(l => l.includes(path));
if(alreadyLinkedPath) {
return console.warn('Skipping: library already linked.');
}
lines.push(`load('${path}');`);
fileManager.writeFromArray(mongorcPath, lines);
return lines;
}
function linkLibrary(path, fileManager) {
const lines = _checkMongorc(fileManager);
return _linkLibrary(path, fileManager, lines);
}
function unlinkLibrary(path, fileManager) {
const lines = _checkMongorc(fileManager);
debug(`Unlinking ${path} from ${mongorcPath}`);
const linesWithoutUnlinked = lines.filter(l => !l.includes(path));
fileManager.writeFromArray(mongorcPath, linesWithoutUnlinked);
return linesWithoutUnlinked;
}
function listLinkedLibraries(fileManager, c=console) {
const lines = _checkMongorc(fileManager);
c.log('Libraries linked to your .mongorc.js');
lines.forEach(l => {
const matcher = l.match(/load\('(.*)'\);/i);
if (matcher) {
c.log(` ${matcher[1]}`);
}
});
}
module.exports = {
linkLibrary,
unlinkLibrary,
listLinkedLibraries,
_checkMongorc,
_backupExistingFile,
_createMongorc,
_linkLibrary,
mongorcPath,
mongorcBackupPath,
WATERMARK
};