-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheditor.js
54 lines (44 loc) · 1.6 KB
/
editor.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
const { spawn } = require('child_process');
const editor = process.env.EDITOR || 'vi';
const requireFileParams = require('./lib/requireFileParams.js');
const generateFallbackFile = (options = {}) => {
const fs = require('fs');
const path = require('path');
// templates are js parsed strings
const templateString = require('./templates/_default.js')(options);
// generate a random file name
const generatedFile = path.join('/tmp', `${Math.random().toString(36).substring(7)}.js`);
// like copy, but node doesn't complain about it
fs.writeFileSync(generatedFile, templateString);
return [
// send the path of the new file
generatedFile,
// provide function to delete the file
() => fs.unlinkSync(generatedFile)
];
};
/**
* Will call out your default editor to write or edit a file to be used as
* parameter for command
*
* @param {String} filepath path of the file to edit, pass nothing to create one
* @returns {Promise} will give back to the contents of the file
*/
module.exports = (filepath, options = {}) => {
let afterEdit = () => {}; // noop function
// if no file is provided generate one from templates
if (!filepath) {
[filepath, afterEdit] = generateFallbackFile(options);
}
return new Promise((resolve) => {
spawn(editor, [filepath], { stdio: 'inherit' }).on('exit', (e) => {
if (e) throw e;
try {
resolve(requireFileParams(filepath, options));
} catch (fe) {
throw fe;
}
afterEdit();
});
});
};