This repository was archived by the owner on Feb 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathedit.js
107 lines (85 loc) · 2.21 KB
/
edit.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
'use strict'
const spawn = require('child_process').spawn
const fs = require('fs')
const temp = require('temp')
const waterfall = require('async/waterfall')
const utils = require('../../utils')
module.exports = {
command: 'edit',
describe: 'Opens the config file for editing in $EDITOR',
builder: {},
handler (argv) {
if (argv._handled) return
argv._handled = true
const editor = process.env.EDITOR
if (!editor) {
throw new Error('ENV variable $EDITOR not set')
}
function getConfig (next) {
argv.ipfs.config.get((err, config) => {
if (err) {
next(new Error('failed to get the config'))
}
next(null, config)
})
}
function saveTempConfig (config, next) {
temp.open('ipfs-config', (err, info) => {
if (err) {
next(new Error('failed to open the config'))
}
fs.write(info.fd, JSON.stringify(config, null, 2))
fs.close(info.fd, (err) => {
if (err) {
next(new Error('failed to open the config'))
}
})
next(null, info.path)
})
}
function openEditor (path, next) {
const child = spawn(editor, [path], {
stdio: 'inherit'
})
child.on('exit', (err, code) => {
if (err) {
throw new Error('error on the editor')
}
next(null, path)
})
}
function readTempConfig (path, next) {
fs.readFile(path, 'utf8', (err, data) => {
if (err) {
next(new Error('failed to get the updated config'))
}
try {
next(null, JSON.parse(data))
} catch (err) {
next(new Error(`failed to parse the updated config "${err.message}"`))
}
})
}
function saveConfig (config, next) {
config = utils.isDaemonOn()
? Buffer.from(JSON.stringify(config)) : config
argv.ipfs.config.replace(config, (err) => {
if (err) {
next(new Error('failed to save the config'))
}
next()
})
}
waterfall([
getConfig,
saveTempConfig,
openEditor,
readTempConfig,
saveConfig
], (err) => {
if (err) {
throw err
}
})
}
}