This repository has been archived by the owner on Jan 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 28
/
file-watcher.js
330 lines (316 loc) · 12.1 KB
/
file-watcher.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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
const { ipcMain } = require('electron');
const { requireArgParams } = require('../infrastructure/handler-helper');
const path = require('path');
const NodeGit = require('nodegit');
const uuid = require('uuid');
var Repo;
var window = null;
var refreshInterval;
var fileRefreshSubscriptions = {};
ipcMain.on('Repo-Open', openRepo);
ipcMain.on('Repo-Close', closeRepo);
ipcMain.on('Repo-GetFileDetail', requireArgParams(getFileDetailWrapper, ['file', 'commit']))
ipcMain.on('Repo-SubscribeFileUpdate', requireArgParams(subscribeUpdate, ['file', 'commit']))
ipcMain.on('Repo-UnsubscribeFileUpdate', requireArgParams(unsubscribeUpdate, ['id']));
function init(win) {
window = win;
window.on('close', (event) => {
clearInterval(refreshInterval);
unsubscribeAllUpdate();
})
}
function closeRepo(event, arg) {
Repo = null;
clearInterval(refreshInterval);
unsubscribeAllUpdate();
}
function openRepo(event, arg) {
Repo = null;
clearInterval(refreshInterval);
unsubscribeAllUpdate();
if (arg.workingDir) {
NodeGit.Repository.open(arg.workingDir).then(res => {
Repo = res;
refreshInterval = setInterval(() => {
getStatus()
}, 5 * 1000);
getStatus()
})
}
}
function getStatus() {
if (Repo && window) {
return Repo.getStatus().then((statuses) => {
let stagedSummary = {
ignored: 0,
newCount: 0,
deleted: 0,
modified: 0,
renamed: 0
}
let unstagedSummary = {
ignored: 0,
newCount: 0,
deleted: 0,
modified: 0,
renamed: 0
}
let staged = [];
let unstaged = [];
let result = statuses.forEach(status => {
let item = {
path: status.path(),
isNew: status.isNew(),
isModified: status.isModified(),
isRenamed: status.isRenamed(),
isIgnored: status.isIgnored(),
isDeleted: status.isDeleted(),
}
if (status.inIndex()) {
staged.push(item);
if (status.isNew()) {
stagedSummary.newCount += 1;
} else if (status.isModified()) {
stagedSummary.modified += 1;
} else if (status.isIgnored()) {
stagedSummary.ignored += 1;
} else if (status.isRenamed()) {
stagedSummary.rename += 1;
} else if (status.isDeleted()) {
stagedSummary.deleted += 1;
}
}
if (status.inWorkingTree()) {
unstaged.push(item);
if (status.isNew()) {
unstagedSummary.newCount += 1;
} else if (status.isModified()) {
unstagedSummary.modified += 1;
} else if (status.isIgnored()) {
unstagedSummary.ignored += 1;
} else if (status.isRenamed()) {
unstagedSummary.rename += 1;
} else if (status.isDeleted()) {
unstagedSummary.deleted += 1;
}
}
});
window.webContents.send('Repo-FileStatusRetrieved', {
staged: staged,
unstaged: unstaged,
stagedSummary: stagedSummary,
unstagedSummary: unstagedSummary,
summary: {
ignored: stagedSummary.ignored + unstagedSummary.ignored,
newCount: stagedSummary.newCount + unstagedSummary.newCount,
deleted: stagedSummary.deleted + unstagedSummary.deleted,
modified: stagedSummary.modified + unstagedSummary.modified,
renamed: stagedSummary.renamed + unstagedSummary.renamed
}
});
return Promise.resolve();
});
}
}
function getFileDetailWrapper(event, arg) {
if (Repo) {
getFileDetail(arg.file, arg.commit, arg.fullFile).then(result => {
event.sender.send('Repo-FileDetailRetrieved', result);
}).catch(err => {
if (err === 'FILE_NOT_FOUND') {
event.sender.send('Repo-FileDetailNotFound', {});
}
})
}
}
function subscribeUpdate(event, arg) {
let subID = uuid.v4();
fileRefreshSubscriptions[subID] = setInterval(() => {
getFileDetail(arg.file, arg.commit, arg.fullFile).then(result => {
event.sender.send('Repo-FileDetailRetrieved', result);
}).catch(err => {
if (err === 'FILE_NOT_FOUND') {
event.sender.send('Repo-LiveUpdateFileNotFound', {});
}
});
}, 2 * 1000);
event.returnValue = subID;
}
function unsubscribeUpdate(event, arg) {
if (fileRefreshSubscriptions[arg.id]) {
clearInterval(fileRefreshSubscriptions[arg.id]);
delete fileRefreshSubscriptions[arg.id];
}
}
function getFileDetail(path, commit, fullFile = false) {
if (commit !== 'tree' && commit !== 'workdir') {
return Repo.getCommit(commit).then(x => {
return x.getDiff().then(diffs => {
diff = diffs[0]
return diff
}).then(diff => {
return processDiff(diff, path, commit, fullFile);
})
});
} else if (commit === 'workdir') {
return Repo.index().then(ind => {
return NodeGit.Diff.indexToWorkdir(Repo, ind, {
flags: NodeGit.Diff.OPTION.SHOW_UNTRACKED_CONTENT | NodeGit.Diff.OPTION.RECURSE_UNTRACKED_DIRS
})
}).then(diff => {
return processDiff(diff, path, commit, fullFile);
})
} else {
let index;
return Repo.index().then(ind => {
index = ind;
return Repo.getHeadCommit().then(cmt => {
return cmt.getTree();
}).then(tree => {
return NodeGit.Diff.treeToIndex(Repo, tree, index);
}).catch(err => {
return NodeGit.Diff.treeToIndex(Repo, null, index);
})
}).then(diff => {
return processDiff(diff, path, commit, fullFile);
})
}
}
function processDiff(diff, path, commit, fullFile = false) {
return diff.findSimilar({ renameThreshold: 50 }).then(() => {
return diff.patches()
}).then(patches => {
let patch;
patches.forEach(p => {
if (p.newFile().path() === path) {
patch = p;
}
});
if (patch) {
return patch.hunks().then(hunks => {
let req = [];
hunks.forEach(function (hunk) {
req.push(hunk.lines());
});
return Promise.all(req);
}).then(hunks => {
let result = [];
hunks.forEach(lines => {
result.push({
lines: []
});
lines.forEach(function (line) {
let isNewLine = String.fromCharCode(line.origin()) === '<' || String.fromCharCode(line.origin()) === '>' || String.fromCharCode(line.origin()) === '='
result[result.length - 1].lines.push({
op: String.fromCharCode(line.origin()),
content: isNewLine ? line.content().trim() : line.content(),
oldLineno: line.oldLineno(),
newLineno: line.newLineno(),
});
});
});
return Promise.resolve(result);
}).then(result => {
let linesAdded = 0;
let linesRemoved = 0;
result.forEach(h => {
h.lines.forEach(l => {
if (l.op === '+') {
linesAdded += 1;
} else if (l.op === '-') {
linesRemoved += 1;
}
})
})
if (!fullFile) {
return { path: path, paths: path.split('/'), commit: commit, hunks: result, summary: { added: linesAdded, removed: linesRemoved } };
} else {
return getFileLines(commit, path).then(hunkLikeLines => {
for (let j = 0; j < result.length; j++) {
for (let i = 0; i < hunkLikeLines.length; i++) {
if (hunkLikeLines[i].newLineno === result[j].lines[0].newLineno ||
hunkLikeLines[i].newLineno === result[j].lines[0].oldLineno) {
// found a line with a hunk starting the line
// get ending line number
let lastLineNum = result[j].lines[result[j].lines.length - 1].newLineno;
// get endling line index in hunkLikeLines
let iEnd;
for (iEnd = i; iEnd < hunkLikeLines.length; iEnd++) {
if (hunkLikeLines[iEnd].newLineno === lastLineNum) {
break;
}
}
let lineCount = iEnd - i + 1;
// clear oldLineno in result[j].lines
result[j].lines.map(l => {
if (l.op !== '+' && l.op !== '-') {
l.oldLineno = -1
}
})
hunkLikeLines.splice(i, lineCount, ...result[j].lines);
break;
}
}
}
let hunks;
if (hunkLikeLines.length === 0) {
hunks = result;
} else {
hunks = [{ lines: hunkLikeLines }];
}
return { path: path, paths: path.split('/'), commit: commit, hunks: hunks, summary: { added: linesAdded, removed: linesRemoved } };
})
}
});
} else {
return Promise.reject('FILE_NOT_FOUND');
}
});
}
function getFileLines(commit, path) {
let getCmtPromise;
if (commit === 'workdir' || commit === 'tree') {
getCmtPromise = Repo.getHeadCommit();
} else {
getCmtPromise = Repo.getCommit(commit)
};
return getCmtPromise.then(cmt => {
return cmt.getTree();
}).then(tree => {
return tree.getEntry(path);
}).then(treeEntry => {
if (treeEntry.isFile()) {
return treeEntry.getBlob();
} else {
return Promise.reject('PATH_NOT_FILE');
}
}).then(blob => {
if (blob.isBinary()) {
return [{ op: "binary", content: "Binary File Content", oldLineno: -1, newLineno: -1 }]
}
let lines = blob.toString().split(/\r?\n/);
let hunkLike = lines.map((l, index) => {
return {
op: "",
content: l,
oldLineno: -1,
newLineno: index + 1
}
})
return hunkLike;
}).catch(err => {
return Promise.resolve([]);
});
}
function unsubscribeAllUpdate() {
let subs = Object.keys(fileRefreshSubscriptions);
subs.forEach(s => {
clearInterval(fileRefreshSubscriptions[s]);
delete fileRefreshSubscriptions[s];
});
}
module.exports = {
init: init,
getStatus: getStatus,
getFileDetail: getFileDetail,
}