/
resolveConflicts.js
563 lines (405 loc) · 19 KB
/
resolveConflicts.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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
// Define DEBUG features
var devTools = false;
var isPaused = false; // Stop timer. In console, type : isPaused = true
// ---------
// INIT
// ---------
var gui = require("nw.gui");
var os = require('os');
var fs = require('fs');
const pathsep = require('path').sep; // Os-dependent path separator
const simpleGit = opener.simpleGit;
const pragmaLog = opener.pragmaLog; // Defined in app.js
const util = require('./util_module.js'); // Pragma-git common functions
var state = global.state; // internal copy of global.state
var localState = global.localState;
var win
const delayInMs = 1000;
// Initiate GUI update loop
var timer = _loopTimer( 1000);
// Storage of paths to backup files
var origConflictingFiles = []; // Store files found to be conflicting. Use to remove .orig files of these at the end
// ---------
// FUNCTIONS
// ---------
// Start initiated from settings.html
async function injectIntoJs(document) {
console.log('resolveConflicts.js entered');
win = gui.Window.get();
// For systems that have multiple workspaces (virtual screens)
if ( win.canSetVisibleOnAllWorkspaces() ){
win.setVisibleOnAllWorkspaces( state.onAllWorkspaces );
}
let status_data;
if (devTools == true){
win.showDevTools(); // WARNING : causes redraw issues on startup
}
try{
await simpleGit( state.repos[state.repoNumber].localFolder).status( onStatus );
function onStatus(err, result ){ status_data = result; console.log(result); console.log(err) };
}catch(err){
}
// Draw tables, and store found files
let b = createUnsureFileTable(document, status_data);
document.getElementById('collapsibleUnsure').click(); // Open collapsed section 1)
if (b.length == 0){
document.getElementById('resolveAllUnsureButton').disabled = true;
document.getElementById('resolveAllConflictsButton').disabled = false; // Second button is enabled if no conflicts
}
let a = createConflictingFileTable(document, status_data);
document.getElementById('collapsibleConflict').click(); // Open collapsed section 2)
if (a.length == 0){
document.getElementById('resolveAllConflictsButton').disabled = true; // Second button is enabled if any conflicts
}
document.getElementById('collapsibleResolved').click(); // Open collapsed section 3)
// Store conflicting file-list
origConflictingFiles = a.concat(b);
};
// Main functions
async function _callback( name, event){
let id = event.id;
console.log('_callback = ' + name);
switch(name) {
case 'resolveAllConflictsButton':
console.log('resolveAllConflictsButton');
console.log(event);
gitResolveConflicts( state.repos[state.repoNumber].localFolder);
break;
case 'resolveAllUnsureButton':
console.log('resolveAllUnsureButton');
console.log(event);
gitResolveUnsureFiles( state.repos[state.repoNumber].localFolder);
// Enable "Solve conflicting files" button in step 2)
document.getElementById('resolveAllConflictsButton').disabled = false;
// Disable this button from step 1)
document.getElementById('resolveAllUnsureButton').disabled = true;
break;
case 'conflictsResolvedButton':
console.log('conflictsResolvedButton');
console.log(event);
gitDeleteBackups( state.repos[state.repoNumber].localFolder);
gitConflictsResolutionSolved( state.repos[state.repoNumber].localFolder);
break;
case 'undoMergeButton':
console.log('undoMergeButton');
console.log(event);
await gitUndoMerge( state.repos[state.repoNumber].localFolder);
opener.writeTextOutput( { value: '' } ); // Clean message
break;
} // End switch
// ---------------
// LOCAL FUNCTIONS
// ---------------
async function gitResolveConflicts( folder){
let tool = state.tools.mergetool;
let command = [
'mergetool',
'--gui' ,
'--tool=' + tool
];
// Loop all unresolved files TODO : Status to files to merge (not all conflicting files as now)
for (let i in origConflictingFiles) {
try{
// Store conflicting file names
console.log('gitResolveConflicts -- Resolving conflicting files');
// Resolve with external merge tool
//writeMessage( 'Resolving conflicts');
await simpleGit( folder).raw(command.concat( origConflictingFiles[i] ), onResolveConflict );
function onResolveConflict(err, result){ console.log(result); console.log(err) };
//await waitTime( 1000);
console.log('gitResolveConflicts -- Finished resolving conflicting files');
}catch(err){
console.log('gitResolveConflicts -- caught error ');
console.log(err);
// If external diff tool does not exist => write messate about this
}
// Update table
let status_data;
try{
console.log('gitResolveConflicts -- update table getting status');
await simpleGit( state.repos[state.repoNumber].localFolder).status( onStatus );
function onStatus(err, result ){ status_data = result; console.log(result); console.log(err) };
console.log('gitResolveConflicts -- redraw table ');
createConflictingFileTable(document, status_data)
}catch(err){
console.log('gitResolveConflicts -- error redrawing table');
console.log(err);
}
}
}
async function gitResolveUnsureFiles( folder){
var tbody = document.getElementById("deletedTableBody");
for (var i = 0, row; row = tbody.rows[i]; i++) {
//iterate through rows (accessed using the "row" variable assigned in the for loop)
let fileName = row.cells[0].getElementsByTagName('label')[0].innerText;
let checked = row.cells[0].getElementsByTagName('input')[0].checked;
if (checked){
// Add
try{
// Store conflicting file names
console.log('gitResolveUnsureFiles -- add file = ' +fileName);
await simpleGit( folder).add(fileName, onAdd );
function onAdd(err, result){ console.log(result); console.log(err) };
}catch(err){
console.log('gitResolveUnsureFiles -- caught error adding file = ' +fileName);
console.log(err);
}
}else{
// Remove
try{
// Store conflicting file names
console.log('gitResolveUnsureFiles -- deleting file = ' +fileName);
await simpleGit( folder).rm(fileName, onDelete );
function onDelete(err, result){ console.log(result); console.log(err) };
}catch(err){
console.log('gitResolveUnsureFiles -- caught error deleting file = ' +fileName);
console.log(err);
}
}
}
// Update table
let status_data;
try{
console.log('gitResolveUnsureFiles -- update table getting status');
await simpleGit( state.repos[state.repoNumber].localFolder).status( onStatus );
function onStatus(err, result ){
status_data = result;
console.log(result);
console.log(err)
createUnsureFileTable(document, status_data);
};
console.log('gitResolveUnsureFiles -- redraw table ');
createUnsureFileTable(document, status_data)
}catch(err){
console.log('gitResolveUnsureFiles -- error redrawing table');
console.log(err);
}
}
async function gitConflictsResolutionSolved(folder){
// Let git finish the conflict resolution
// Handle two scenarios :
// 1) no files were modified,
// 2) files were modified
let status_data = await opener.gitStatus();
if (status_data.changedFiles === false){
// Case 1) no changed files : End conflict resolution from here
// Pragma-git does not know that it needs to commit to finish the conflict resolution.
// Force it to finish with a standard message.
await opener.gitAddCommitAndPush( 'Conflict resolved without modifying files');
}else {
// Case 2) most common : Files are modified, and Pragma-git will know that a commit is required
localState.mode = 'UNKNOWN';
opener.writeTextOutput( { value: '' } ); // Clear
}
}
function gitDeleteBackups( folder){
// Remove .orig
for (let i in origConflictingFiles) {
try {
let file = folder + pathsep + origConflictingFiles[i] + '.orig';
console.log('gitDeleteBackups -- deleting file = ' + file);
fs.unlinkSync(file)
//file removed
}catch(err) {
console.log('gitDeleteBackups -- failed deleting file');
console.log(err)
}
}
// Remove _BACKUP_nnnn, _BASE_nnnn, B_LOCAL_nnnn, B_REMOTE_nnnn
// - BASE is the first commit down the tree the two branches split off from. It is the first common ancestor. Often it is useful to have this to help decide which of the newer commits you want.
// - LOCAL is your local file, the one in the current branch you are standing on.
// - REMOTE is the remote file, of the branch you are merging into your common on.
// Take the originally conflicting files one-by-one
for (let i in origConflictingFiles) {
try {
let path = folder + pathsep + origConflictingFiles[i];
let directory = path.match(/(.*)[\/\\]/)[1]||'';
let fileName = path.split(/^.*[\\\/]/).pop();
// Look for files that start with fileName followed by "_"
let filesInThisFolder = fs.readdirSync(directory);
for (let j in filesInThisFolder) {
if ( filesInThisFolder[j].startsWith(fileName + '_') ){
// Identified as A_BASE_12345 etc, should be removed :
console.log('Found matching file = ' + filesInThisFolder[j]);
let file = folder + pathsep + filesInThisFolder[j];
fs.unlinkSync(file);
}
}
}catch(err) {
console.log('gitDeleteBackups -- failed deleting file');
console.log(err)
}
}
// Close window
closeWindow();
}
async function gitUndoMerge( folder){
try{
// Store conflicting file names
console.log('gitUndoMerge -- entered');
await simpleGit( folder).merge(['--abort'], onUndoMerge );
function onUndoMerge(err, result){ console.log(result); console.log(err) };
//await waitTime( 1000);
// Remove git backup-files
gitDeleteBackups( state.repos[state.repoNumber].localFolder);
// Close pragma-merge window (may or may not be opened)
opener.merge_win.close();
}catch(err){
console.log('gitUndoMerge -- caught error ');
console.log(err);
}
// Close window
closeWindow();
}
// ================= END CALLBACK =================
}
async function _loopTimer( delayInMs){
// Define timer
let timer = window.setInterval( _update, delayInMs );
return timer
}
async function _update(){
if(isPaused) {
return;
}
let folder = state.repos[state.repoNumber].localFolder;
let status_data;
try{
await simpleGit( folder).status( onStatus );
function onStatus(err, result ){
status_data = result;
console.log(result);
console.log(err);
createConflictingFileTable(document, status_data);
};
}catch(err){
}
}
async function closeWindow(){
// Remove from menu
opener.deleteWindowMenu("Resolve Conflicts");
// Close window and return
localState.conflictsWindow = false
//localState.fileListWindow = false; // Show to main program that window is closed
win.close();
}
// Draw
function createConflictingFileTable(document, status_data) {
var index = 0;
let cell, row;
let foundFiles = [];
// Old tbody
let old_tbody = document.getElementById('conflictingTableBody');
// Make a new tbody
let tbody = document.createElement("tbody"); // Empty tbody
tbody.setAttribute('id','conflictingTableBody');
// Fill tbody with content
console.log('createConflictingFileTable');
for (let i in status_data.conflicted) {
let index = util.findObjectIndex(status_data.files, 'path', status_data.conflicted[i]);
let fileStruct = status_data.files[index];
let XY = fileStruct.index + fileStruct.working_dir; // See : https://git-scm.com/docs/git-status
console.log( 'XY = ' + XY + ' ' + fileStruct.path);
/* For paths with merge conflicts, X and Y show the modification states of each side of the merge
* A A unmerged, both added - conflict (true file conflicts)
* U U unmerged, both modified - conflict
*/
if ( XY == 'AA' || XY == 'UU' ){
// remember found file
foundFiles.push(fileStruct.path);
console.log( fileStruct.path);
let row = tbody.insertRow();
// Into tbody cell : path
cell = row.insertCell();
text = document.createTextNode( fileStruct.path );
cell.appendChild(text);
}
index = index + 1;
}
// Replace old tbody content with new tbody
old_tbody.parentNode.replaceChild(tbody, old_tbody);
return foundFiles;
}
function createUnsureFileTable(document, status_data) {
var index = 10000; // Checkbox id
let cell, row;
let foundFiles = [];
// Old tbody
let old_tbody = document.getElementById('deletedTableBody');
// Make a new tbody
let tbody = document.createElement("tbody"); // Empty tbody
tbody.setAttribute('id','deletedTableBody');
// Fill tbody with content
console.log('createUnsureFileTable');
for (let i in status_data.conflicted) {
let index = util.findObjectIndex(status_data.files, 'path', status_data.conflicted[i]);
let fileStruct = status_data.files[index];
let XY = fileStruct.index + fileStruct.working_dir; // See : https://git-scm.com/docs/git-status
console.log( 'XY = ' + XY + ' ' + fileStruct.path);
/* For paths with merge conflicts, X and Y show the modification states of each side of the merge
* D D unmerged, both deleted - no conflict
*
* A U unmerged, added by us - accept (file only on our side)
* U D unmerged, deleted by them- ask ( fixed in createUnsureFileTable)
*
* U A unmerged, added by them - accept (file only on their side)
* D U unmerged, deleted by us - ask
*
*/
if ( XY == 'D ' || XY == ' D' ||XY == 'DU' || XY == 'UD' || XY == 'AU'|| XY == 'UA'){
console.log( fileStruct.path);
// Description of what has happened
let reason = "unknown reason";
switch (XY){
case 'D ' :
reason = 'File deleted in current branch';
break;
case 'DU' :
reason = 'File deleted in current branch';
break;
case 'AU' :
reason = 'File added in current branch';
break;
case ' D' :
reason = 'File deleted in other branch';
break;
case 'UD' :
reason = 'File deleted in other branch';
break;
case 'UA' :
reason = 'File added in other branch';
break;
}
// Remember found file
foundFiles.push(fileStruct.path);
let row = tbody.insertRow();
//
// First cell
//
cell = row.insertCell();
cell.setAttribute("class", 'localFolder');
// Checkbox
var checkbox = document.createElement('input');
checkbox.setAttribute("name", "repoGroup");
checkbox.setAttribute("onclick", "_callback('repoRadiobuttonChanged',this)");
checkbox.type = 'checkbox';
checkbox.id = index;
checkbox.checked = true;
// Label
var label = document.createElement('label')
label.htmlFor = index;
var description = document.createTextNode( fileStruct.path );
label.appendChild(description);
var htmlReason = document.createTextNode( ' (' + reason + ')');
var newline = document.createElement('br');
cell.appendChild(checkbox);
cell.appendChild(label);
cell.appendChild(htmlReason);
cell.appendChild(newline);
}
index = index + 1;
}
// Replace old tbody content with new tbody
old_tbody.parentNode.replaceChild(tbody, old_tbody);
return foundFiles;
}