-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
94 lines (85 loc) · 2.31 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
const spawn = require('child_process').spawn
const fs = require('fs')
const { unlink } = require('node:fs/promises')
const os = require('os')
const path = require('path')
const crypto = require("crypto")
const ccurllib = require('ccurllib')
const spoolchanges = require('./lib/spoolchanges.js')
const tmpFile = () => {
const tmpDir = os.tmpdir()
const filename = crypto.randomUUID()
return path.join(tmpDir, filename)
}
// get info on database at url
const info = async (url) => {
return await ccurllib.request({ url })
}
// sort file f1 and output sorted data to f2
const sort = async function (f1, f2) {
return new Promise(function (resolve, reject) {
const ws = fs.createWriteStream(f2)
const proc = spawn('sort', [f1])
proc.stdout.on('data', function (data) {
ws.write(data)
})
proc.on('exit', (code) => {
ws.end(function () {
if (code === 0) {
resolve()
} else {
reject(new Error('failed to sort'))
}
})
})
})
}
// diff two files - output to stdout
const diff = async function (f1, f2, unified) {
return new Promise(function (resolve, reject) {
const params = [f1, f2]
if (unified) {
params.unshift('-u')
}
const proc = spawn('diff', params)
proc.stdout.on('data', function (data) {
process.stdout.write(data)
})
proc.on('exit', (code) => {
resolve()
})
})
}
// quick diff
const quick = async function (a, b) {
const data = await Promise.all([info(a), info(b)])
const obj = {
a: data[0],
b: data[1],
ok: !!((data[0].doc_count === data[1].doc_count && data[0].doc_del_count === data[1].doc_del_count))
}
return obj
}
// slow diff
const full = async function (a, b, conflicts, unified) {
// four temp files
const aunsorted = tmpFile()
const asorted = tmpFile()
const bunsorted = tmpFile()
const bsorted = tmpFile()
console.error('spooling changes...')
await Promise.all([spoolchanges(a, aunsorted, conflicts), spoolchanges(b, bunsorted, conflicts)])
console.error('sorting...')
await sort(aunsorted, asorted)
await sort(bunsorted, bsorted)
console.error('calculating difference...')
await diff(asorted, bsorted, unified)
await unlink(aunsorted)
await unlink(asorted)
await unlink(bunsorted)
await unlink(bsorted)
}
module.exports = {
quick,
full
}