forked from mvila/on-save
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
162 lines (139 loc) · 4.79 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
'use babel';
import {existsSync, readFileSync} from 'fs';
import {join, relative, dirname, extname} from 'path';
import {exec} from 'child_process';
import {CompositeDisposable} from 'atom';
import minimatch from 'minimatch';
import mkdirp from 'mkdirp';
const PROPS_WHITELIST = ['files', 'command', 'srcDir', 'destDir', 'showOutput', 'showError', 'exportedFunctions'];
const CONFIGS_FILENAME = '.on-save.json';
const EXEC_TIMEOUT = 60 * 1000; // 1 minute
export default {
activate() {
this.subscriptions = new CompositeDisposable();
this.subscriptions.add(atom.workspace.observeTextEditors(textEditor => {
this.subscriptions.add(textEditor.onDidSave(this.handleDidSave.bind(this)));
}));
},
deactivate() {
this.subscriptions.dispose();
},
handleDidSave(event) {
let savedFile = event.path;
const savedFileDir = dirname(savedFile);
const rootDir = this.findRootDir(savedFileDir);
if (!rootDir) {
return;
}
savedFile = relative(rootDir, savedFile);
const configs = this.loadConfigs(rootDir);
for (const config of configs) {
this.run({rootDir, config, savedFile});
}
},
findRootDir(dir) {
if (existsSync(join(dir, CONFIGS_FILENAME))) {
return dir;
}
const parentDir = join(dir, '..');
if (parentDir === dir) {
return undefined;
}
return this.findRootDir(parentDir);
},
loadConfigs(rootDir) {
const configsFile = join(rootDir, CONFIGS_FILENAME);
let configs = readFileSync(configsFile, 'utf8');
configs = JSON.parse(configs);
if (!Array.isArray(configs)) {
configs = [configs];
}
configs = configs.map(config => this.normalizeConfig(config));
return configs;
},
normalizeConfig(rawConfig) {
const config = this.filterToWhitelist(rawConfig);
console.log('filtered for whitelist:', config);
if (!config.files) {
throw new Error('on-save: \'files\' property is missing in \'.on-save.json\' configuration file');
}
if (!Array.isArray(config.files)) {
config.files = [config.files];
}
if (!config.command) {
throw new Error('on-save: \'command\' property is missing in \'.on-save.json\' configuration file');
}
if (!config.srcDir) {
config.srcDir = '';
}
if (!config.destDir) {
config.destDir = config.srcDir;
}
if (config.showOutput === undefined) {
config.showOutput = false;
}
if (config.showError === undefined) {
config.showError = true;
}
return {...config, files: config.files};
},
filterToWhitelist(normalizedConfig) {
return Object.keys(normalizedConfig).reduce((accum, propName) => {
return PROPS_WHITELIST.includes(propName) ? ({...accum, [propName]: normalizedConfig[propName]}) : accum;
}, {});
},
run({rootDir, savedFile, config}) {
const matched = config.files.find(glob => {
glob = join(config.srcDir, glob);
return minimatch(savedFile, glob);
});
if (!matched) {
return;
}
let destFile = relative(config.srcDir, savedFile);
destFile = join(config.destDir, destFile);
const exportNames = this.getExportedFunctions([savedFile], rootDir).map(f => `"_${f}"`);
const exportedFunctions = exportNames.join(',');
const srcFile = savedFile;
const extension = extname(destFile);
const destFileWithoutExtension = destFile.substr(0, destFile.length - extension.length);
mkdirp.sync(join(rootDir, dirname(destFile)));
const command = this.resolveVariables(config.command, {
...config,
srcFile,
destFile,
destFileWithoutExtension,
exportedFunctions
});
const options = {cwd: rootDir, timeout: EXEC_TIMEOUT};
const message = {detail: {command, options}, dismissable: true};
atom.notifications.addSuccess(`CLI Command: ${JSON.stringify(message)}`);
exec(command, options, (err, stdout, stderr) => {
const message = 'on-save';
const output = stdout.trim();
if (config.showOutput && output) {
atom.notifications.addSuccess(message, {detail: output, dismissable: true});
}
const error = stderr.trim() || (err && err.message);
if (config.showError && error) {
atom.notifications.addError(message, {detail: error, dismissable: true});
}
});
},
resolveVariables(command, vars) {
for (const key of Object.keys(vars)) {
const value = vars[key];
const regExp = new RegExp(`\\$\\{${key}\\}`, 'g');
command = command.replace(regExp, value);
}
return command;
},
getExportedFunctions(sources, rootDir) {
return sources.reduce((accum, fname) => {
const fNameResolved = join(rootDir, fname);
const content = readFileSync(fNameResolved, 'utf8');
const mtch = content.match(/\w*(?=\s\/\*f\*\/)/g);
return accum.concat(mtch.filter(m => Boolean(m)));
}, []);
}
};