/
dsh.js
88 lines (78 loc) · 2.38 KB
/
dsh.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
#!/usr/bin/env node
const vorpal = require('vorpal')()
const Dat = require('util').promisify(require('dat-node'))
const SHELL_FILE = '.dshell'
const DAT_FOLDER = '.datsrc'
const DAT_RESULTS = '.datdest'
const path = require('path')
const mkdirp = require('util').promisify(require('mkdirp'))
const fs = require('fs')
const writeFile = require('util').promisify(fs.writeFile)
const readFile = require('util').promisify(fs.readFile)
const unlink = require('util').promisify(fs.unlink)
let dat
let datRes
let key
let stdout
let stderr
vorpal
.command('run [commands...]', 'Run commands when connected to a Dat')
.action(async function (args, next) {
// TODO: check if connected before actually running anything
await writeFile(path.join(DAT_FOLDER, SHELL_FILE), args.commands.join(' '))
next()
})
vorpal
.command('start')
.option('-q, --quiet')
.action(async function (args, next) {
// make folders
await mkdirp(DAT_FOLDER)
await mkdirp(DAT_RESULTS)
try {
await unlink(path.join(DAT_FOLDER, SHELL_FILE))
} catch (e) {}
// TODO: make .datignore only if it doesn't exists
await writeFile(path.join(DAT_FOLDER, '.datignore'), '.key')
try {
key = await readFile(path.join(DAT_FOLDER, '.key'))
} catch (err) {}
dat = await Dat(DAT_FOLDER)
dat.importFiles({ watch: true, ignoreHidden: false })
dat.joinNetwork()
if (!args.options.quiet) this.log('Dat link is: dat://' + dat.key.toString('hex'))
if (key) {
datRes = await Dat(DAT_RESULTS, { key })
datRes.joinNetwork()
} else {
await this.prompt({
type: 'input',
name: 'key',
message: 'Enter remote Dat key? '
}, async function (result) {
// results dat
key = result.key
await writeFile(path.join(DAT_FOLDER, '.key'), key)
datRes = await Dat(DAT_RESULTS, { key })
datRes.joinNetwork()
})
}
fs.watchFile(DAT_RESULTS, async (current, previous) => {
try {
stdout = await readFile(path.join(DAT_RESULTS, '.stdout'), 'utf8')
stderr = await readFile(path.join(DAT_RESULTS, '.stderr'), 'utf8')
} catch (e) {}
if (stdout) this.log(stdout)
if (stderr) this.log(stderr)
})
next()
})
vorpal.
command('close', 'Close connection to Dat')
.action((args, next) => {
if (dat) dat.leaveNetwork()
next()
})
vorpal
.delimiter('dsh >')
.show()