-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
diff-minimiser.js
executable file
·1864 lines (1647 loc) · 69.2 KB
/
diff-minimiser.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
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
// TODO: In compareNormalizedCodeDiffs
// Maybe make a refactored compareNormalizedCodeDiffsV2 version of this function and revert the
// existing to it's former state
// Figure out how to use the results of arrayDiff to minimise the lines of changes we return for
// this group, to just the ones that have actually changed after identifiers are normalised
// Explore whether we can simplify the code for doing this by changing the comparator function used
// by arrayDiff (or another of the jsDiff diff functions)
// TODO: If a group of diff changes isn't perfectly equal, can we at least make it smaller by removing/converting matching lines?
// Maybe if a chunk has the same number of added/removed lines we could group it together? (would need to adjust the logic of normalising though maybe?)
// eg.
// 52717⋮ │ ef = Y.initiallyHighlightedMessageId,
// 52718⋮ │ ep = Y.continueConversationUrl,
// 52719⋮ │ eb = Y.urlThreadId,
// 52720⋮ │ eS = null !== (0, ec.useContext)(ey.gB),
// 52721⋮ │ eU = (0, e_.rm)();
// 52722⋮ │ (0, em.ax)(
// ⋮52748│ eu = Y.initiallyHighlightedMessageId,
// ⋮52749│ ec = Y.continueConversationUrl,
// ⋮52750│ eh = Y.urlThreadId,
// ⋮52751│ em = null !== (0, ef.useContext)(ew.gB),
// ⋮52752│ eg = eG().focusedView,
// ⋮52753│ eC = (0, eO.rm)();
// ⋮52754│ (0, eb.ax)(
// eg.
// 53734⋮ │ e5 = en(26272),
// 53735⋮ │ e4 = en(90387),
// 53736⋮ │ e3 = en(79505),
// 53737⋮ │ e6 = en(90439),
// 53738⋮ │ e7 = en(58369),
// 53739⋮ │ e8 = en(36292),
// 53740⋮ │ tt = en(35250);
// 53741⋮ │ function ta(Y, et) {
// ⋮53772│ e5 = en(40670),
// ⋮53773│ e4 = en(26272),
// ⋮53774│ e3 = en(90387),
// ⋮53775│ e6 = en(79505),
// ⋮53776│ e7 = en(90439),
// ⋮53777│ e8 = en(58369),
// ⋮53778│ tt = en(36292),
// ⋮53779│ ta = en(35250);
// ⋮53780│ function tu(Y, et) {
// TODO: Can we process chunks better that have context between their added/removed?
// eg.
// 53705⋮53743│ eT,
// 53706⋮53744│ e_,
// 53707⋮53745│ ej,
// 53708⋮ │ eO,
// 53709⋮53746│ eM,
// ⋮53747│ eO,
// 53710⋮53748│ eA,
// 53711⋮53749│ eP,
// 53712⋮53750│ eN,
// TODO: do we even need to fully parse with babel/parser? Can we just use a tokenizer then filter out the identifiers?
// https://github.com/eslint/espree#tokenize
// https://github.com/eslint/espree#options
// See normalizeIdentifierNamesInCodeV3
// TODO: We could also try using a more error tolerant parser, like acorn's loose parser
// https://github.com/acornjs/acorn/tree/master/acorn-loose/
// An error-tolerant JavaScript parser written in JavaScript.
// This parser will parse any text into an ESTree syntax tree that is a reasonable approximation of what it might mean as a JavaScript program.
// It will, to recover from missing brackets, treat whitespace as significant, which has the downside that it might mis-parse a valid but weirdly indented file. It is recommended to always try a parse with the regular acorn parser first, and only fall back to this parser when that one finds syntax errors.
// See normalizeIdentifierNamesInCodeV2
// This seems to work pretty well!
// TODO: we need to figure out how to make this preserve the colouring from git diff colour moved when passed through it
// TODO: This seems to have all the relevant bits and pieces.. we just need to refactor it to process the diff lines better, rather than just logging outputs..
// We essentially want to be able to:
// - consume a diff
// - parse it
// - loop through the chunks
// - group add/removes
// - for groups with equal counts of removes/adds
// - normalize the code to stabilize symbol names
// - check if the normalized code is equal
// - if it is, we can mark it to be filtered out of the diff
// - we somehow need to figure out how to handle the context/etc lines on either side when we remove part of the diff like this
// - once we have done all the above processing, we then want to 'unroll' the groups to get the filtered diff back
// - ?maybe some more stuff here?
// TODO: Can we use jsDiff's diffChars/diffWords to suppress a diff chunk group (that doesn't currently parse as an AST) where the differences are only ~2 chars (or multiple chunks of 2 chars)?
// This would help suppress a lot more of the minimised variable churn, without relying on us being able to fix all the related parsing errors
// TODO: Can we figure out how to detect/suppress a diff chunk where the added/removed lines were just shifted (with some context in between, so doesn't work with our current grouping method)
// @@ -313,8 +313,8 @@
// eh = 0,
// eb = eu,
// ew = 0,
// - eE = 0,
// eS = 0,
// + eE = 0,
// eT = 1,
// e_ = 1,
// ej = 1,
// https://github.com/sergeyt/parse-diff
// Simple unified diff parser for JavaScript
// https://github.com/kpdecker/jsdiff
// A javascript text differencing implementation
//
// TODO: explore jsdiff's ability to customize diffing
// https://github.com/kpdecker/jsdiff#defining-custom-diffing-behaviors
// The simplest way to customize tokenization behavior is to simply tokenize the texts you want to diff yourself, with your own code, then pass the arrays of tokens to diffArrays. For instance, if you wanted a semantically-aware diff of some code, you could try tokenizing it using a parser specific to the programming language the code is in, then passing the arrays of tokens to diffArrays.
// To customize the notion of token equality used, use the comparator option to diffArrays
//
// For even more customisation of the diffing behavior, you can create a new Diff.Diff() object, overwrite its castInput, tokenize, removeEmpty, equals, and join properties with your own functions, then call its diff(oldString, newString[, options]) method. The methods you can overwrite are used as follows:
//
// - castInput(value): used to transform the oldString and newString before any other steps in the diffing algorithm happen. For instance, diffJson uses castInput to serialize the objects being diffed to JSON. Defaults to a no-op.
// - tokenize(value): used to convert each of oldString and newString (after they've gone through castInput) to an array of tokens. Defaults to returning value.split('') (returning an array of individual characters).
// - removeEmpty(array): called on the arrays of tokens returned by tokenize and can be used to modify them. Defaults to stripping out falsey tokens, such as empty strings. diffArrays overrides this to simply return the array, which means that falsey values like empty strings can be handled like any other token by diffArrays.
// - equals(left, right): called to determine if two tokens (one from the old string, one from the new string) should be considered equal. Defaults to comparing them with ===.
// - join(tokens): gets called with an array of consecutive tokens that have either all been added, all been removed, or are all common. Needs to join them into a single value that can be used as the value property of the change object for these tokens. Defaults to simply returning tokens.join('').
//
// TODO: explore whether jsdiff can parse an existing git diff directly (or if it only works for patches)
const { parseArgs } = require('util');
const path = require('path');
const { readFileSync, existsSync } = require('fs');
const { createInterface } = require('readline');
const { once } = require('events');
const parseDiff = require('parse-diff');
const { diffChars, diffWords, diffLines, diffArrays } = require('diff');
const acorn = require('acorn');
const acornLoose = require('acorn-loose');
const estraverse = require('estraverse');
const escodegen = require('escodegen');
const parser = require('@babel/parser');
const traverse = require('@babel/traverse').default;
const generator = require('@babel/generator').default;
let DEBUG = false; // Initial debug state
/**
* Displays usage information for the script.
*
* @param {string} scriptName - The name of the script for which to display usage information.
*/
function displayUsage(scriptName) {
console.log(`Usage: ${scriptName} <file-path>
Options:
--debug Enable debug mode.
-h, --help Display this usage information.`);
}
/**
* Parses command line arguments, reads the specified file, and returns its content.
* Exits the process on argument errors or file read errors.
*
* @returns {Object} An object containing:
* - code: The source code read from the file.
*/
async function parseArgsAndReadInput() {
const scriptName = path.basename(process.argv[1]);
const parsedArgs = (() => {
try {
return parseArgs({
strict: true,
allowPositionals: false,
options: {
debug: {
type: 'boolean',
default: false,
},
help: {
type: 'boolean',
short: 'h',
},
file: {
type: 'string',
short: 'f',
},
},
});
} catch (error) {
displayUsage(scriptName);
console.error('\nError: Invalid arguments provided.', error.message);
process.exit(1);
}
})();
if (parsedArgs.values.help) {
displayUsage(scriptName);
process.exit(0);
}
DEBUG = parsedArgs.values.debug || false;
const filePath = parsedArgs.values.file;
const hasStdin = !process.stdin.isTTY;
if (filePath && filePath !== '-' && hasStdin) {
console.error(
`Error: Both file path and stdin were provided. Please provide only one.`
);
process.exit(1);
}
if (filePath === '-' && !hasStdin) {
console.error(
`Error: File path is set to read from stdin, but no stdin input was provided.`
);
process.exit(1);
}
if (!hasStdin && !existsSync(filePath)) {
console.error(`Error: File does not exist at path ${filePath}`);
process.exit(1);
}
const rawDiffText = hasStdin
? (await readAllStdin()).join('\n')
: readFileSync(filePath, 'utf8');
return {
scriptName,
filePath,
rawDiffText,
};
}
async function readAllStdin() {
const rl = createInterface({
input: process.stdin,
output: process.stdout,
terminal: false,
crlfDelay: Infinity,
});
const lines = [];
rl.on('line', (line) => lines.push(line));
await once(rl, 'close');
return lines;
}
/**
* Main entry point of the script. Parses input, analyzes data, and outputs results.
*/
async function main() {
const { rawDiffText } = await parseArgsAndReadInput();
// Parse the diff content
const diffFiles = parseDiff(rawDiffText);
const diffStats = diffFiles.map((file, fileIndex) => {
const { chunks, additions, deletions } = file;
return {
file: fileIndex + 1,
chunks: chunks.length,
additions,
deletions,
};
});
console.error('[diff] diffStats:', diffStats);
// Process each file in the diff
const modifiedDiffFiles = diffFiles.map((file, fileIndex) => {
const { deletions, additions } = file;
console.error(`[diff] file ${fileIndex + 1}`, {
chunks: file.chunks.length,
additions,
deletions,
});
const enrichedChunks = file.chunks.map((chunk, chunkIndex) => {
const { content, changes } = chunk;
const groupedChanges = groupChunkChanges(changes);
// const groupedChanges = groupChunkChangesV2(chunk);
DEBUG &&
console.error(
`[diff::debug] file ${fileIndex + 1}, chunk ${chunkIndex + 1}`,
{
content,
changes: changes.length,
groupedChanges: groupedChanges.length,
}
);
const updatedGroupedChanges = groupedChanges.map((group, groupIndex) => {
const { changes, isEqualModifiedLinesCount } = group;
const errorContext = {
file: fileIndex + 1,
chunk: chunkIndex + 1,
group: groupIndex + 1,
};
DEBUG &&
console.error(
`[diff::debug] file ${fileIndex + 1}, chunk ${
chunkIndex + 1
}, group ${groupIndex + 1}`,
group
);
// TODO: Do we want to exit early? If so, we need to figure how to mimic the rest of the normalizedDiffResult object
// if (!isEqualModifiedLinesCount) {
// DEBUG &&
// console.error(
// `[diff::debug] skipping group due to isEqualModifiedLinesCount being false`
// );
//
// return group;
// }
const normalizedDiffResult = compareNormalizedCodeDiffs(
changes,
errorContext
);
// const normalizedDiffResult = compareNormalizedCodeDiffsV2(
// changes,
// errorContext
// );
// TODO: do we want to keep or remove this isEqualModifiedLinesCount if statement?
// Minimise the logging to only show those we're properly normalising/comparing
// isEqualModifiedLinesCount &&
DEBUG &&
console.error(
`[diff::debug] file ${fileIndex + 1}, chunk ${
chunkIndex + 1
}, group ${groupIndex + 1}`,
{
...group,
...normalizedDiffResult,
}
);
return {
...group,
...normalizedDiffResult,
};
});
const stats = updatedGroupedChanges.reduce(
(acc, group) => {
const totalGroups = acc.totalGroups + 1;
const contextGroups =
acc.contextGroups + (group.isContextGroup ? 1 : 0);
const equalModifiedLinesGroups =
acc.equalModifiedLinesGroups +
(group.isEqualModifiedLinesCount ? 1 : 0);
const normalisedCodeEqualGroups =
acc.normalisedCodeEqualGroups +
(group.isNormalisedCodeEqual ? 1 : 0);
// Calculate remaining change groups after excluding context groups and those with normalized code equal
const remainingChangeGroupsAfterFilter =
totalGroups - contextGroups - normalisedCodeEqualGroups;
return {
totalGroups,
contextGroups,
equalModifiedLinesGroups,
normalisedCodeEqualGroups,
remainingChangeGroupsAfterFilter,
};
},
{
totalGroups: 0,
contextGroups: 0,
equalModifiedLinesGroups: 0,
normalisedCodeEqualGroups: 0,
remainingChangeGroupsAfterFilter: 0,
}
);
return {
...chunk,
groupedChanges,
updatedGroupedChanges,
stats,
};
});
enrichedChunks.forEach((chunk, chunkIndex) => {
console.error(
`[diff] file ${fileIndex + 1}, chunk ${chunkIndex + 1} stats`,
chunk.stats
);
});
const cumulativeStats = enrichedChunks.reduce(
(acc, chunk) => {
return {
totalGroups: acc.totalGroups + chunk.stats.totalGroups,
contextGroups: acc.contextGroups + chunk.stats.contextGroups,
equalModifiedLinesGroups:
acc.equalModifiedLinesGroups + chunk.stats.equalModifiedLinesGroups,
normalisedCodeEqualGroups:
acc.normalisedCodeEqualGroups +
chunk.stats.normalisedCodeEqualGroups,
remainingChangeGroupsAfterFilter:
acc.remainingChangeGroupsAfterFilter +
chunk.stats.remainingChangeGroupsAfterFilter,
};
},
{
totalGroups: 0,
contextGroups: 0,
equalModifiedLinesGroups: 0,
normalisedCodeEqualGroups: 0,
remainingChangeGroupsAfterFilter: 0,
}
);
console.error(
`[diff] file ${fileIndex + 1} cumulative stats`,
cumulativeStats
);
// TODO: remove this basic match filter
const filteredChunksBasicAllMatch = enrichedChunks.filter(
(chunk, chunkIndex) => chunk.stats.remainingChangeGroupsAfterFilter > 0
);
// TODO: refactor the core logic of this map/filter into a helper function?
const filteredChunks = enrichedChunks
.map((chunk) => {
// Filter out 'isNormalisedCodeEqual' entries from 'updatedGroupedChanges'
const groupedChangesWithoutNormalizedEqual =
chunk.updatedGroupedChanges.filter(
(entry) => !entry.isNormalisedCodeEqual
);
// Further process to remove isolated 'isContextGroup' entries
const groupedChangesWithoutNormalizedEqualOrIsolatedContextGroups =
groupedChangesWithoutNormalizedEqual.reduce(
(acc, current, index, array) => {
const isIsolatedContextGroup =
current.isContextGroup &&
!(array[index - 1] && !array[index - 1].isContextGroup) &&
!(array[index + 1] && !array[index + 1].isContextGroup);
if (!isIsolatedContextGroup || !current.isContextGroup) {
acc.push(current);
}
return acc;
},
[]
);
return {
...chunk,
filteredGroupedChanges:
groupedChangesWithoutNormalizedEqualOrIsolatedContextGroups,
};
})
.filter((chunk) => {
// Filter out chunks that after processing are either empty or contain only context groups
const hasMeaningfulChanges = chunk.filteredGroupedChanges.some(
(group) => !group.isContextGroup
);
return chunk.filteredGroupedChanges.length > 0 && hasMeaningfulChanges;
});
// TODO: remove/reduce this debug logging?
// console.error('count of diff chunks', {
// 'file.chunks': file.chunks.length,
// 'file.chunksChangeCount': file.chunks.map((chunk) => chunk.changes.length),
// enrichedChunks: enrichedChunks.length,
// enrichedChunksGroupCount: enrichedChunks.reduce(
// (total, chunk) => {
// return total + chunk.updatedGroupedChanges.length;
// },
// 0
// ),
// filteredChunksBasicAllMatch: filteredChunksBasicAllMatch.length,
// filteredChunksBasicAllMatchGroupCount: filteredChunksBasicAllMatch.reduce(
// (total, chunk) => {
// return total + chunk.updatedGroupedChanges.length;
// },
// 0
// ),
// filteredChunks: filteredChunks.length,
// filteredChunksGroupCount: filteredChunks.reduce(
// (total, chunk) => {
// return total + chunk.filteredGroupedChanges.length;
// },
// 0
// ),
// });
// Helper function to sum up the lengths of updatedGroupedChanges or filteredGroupedChanges across chunks
const sumGroupCounts = (chunks, key = 'updatedGroupedChanges') =>
chunks.reduce((total, chunk) => total + (chunk[key] || []).length, 0);
// Helper function to sum up the total change count within each group of a given chunk array
const sumChangeCounts = (chunks, key = 'updatedGroupedChanges') =>
chunks.reduce((totalChanges, chunk) => {
const changesPerGroup = chunk[key] || [];
return (
totalChanges +
changesPerGroup.reduce((sum, group) => sum + group.changes.length, 0)
);
}, 0);
console.error('Count of diff chunks', {
'file.chunks': file.chunks.length,
'file.chunksChangeCount': file.chunks.reduce(
(total, chunk) => total + chunk.changes.length,
0
),
enrichedChunks: enrichedChunks.length,
enrichedChunksGroupCount: sumGroupCounts(enrichedChunks),
enrichedChunksChangeCount: sumChangeCounts(enrichedChunks),
filteredChunksBasicAllMatch: filteredChunksBasicAllMatch.length,
filteredChunksBasicAllMatchGroupCount: sumGroupCounts(
filteredChunksBasicAllMatch
),
filteredChunksBasicAllMatchChangeCount: sumChangeCounts(
filteredChunksBasicAllMatch
),
filteredChunks: filteredChunks.length,
filteredChunksGroupCount: sumGroupCounts(
filteredChunks,
'filteredGroupedChanges'
),
filteredChunksChangeCount: sumChangeCounts(
filteredChunks,
'filteredGroupedChanges'
),
});
return {
...file,
chunks: enrichedChunks,
filteredChunks,
cumulativeStats,
};
});
// TODO: have this print out the diff for more than one file?
const file = modifiedDiffFiles[0];
// console.error(file)
// TODO: The git diff header usually looks like this, we mimic it below, but is it correct for all cases?
// diff --git a/unpacked/_next/static/chunks/pages/_app.js b/unpacked/_next/static/chunks/pages/_app.js
// index a46f6d5..2695a4b 100644
// --- a/unpacked/_next/static/chunks/pages/_app.js
// +++ b/unpacked/_next/static/chunks/pages/_app.js
console.log(`diff --git a/${file.from} b/${file.to}`);
console.log(`index ${file.index.join(' ')}`);
console.log(`--- a/${file.from}`);
console.log(`+++ b/${file.to}`);
file.filteredChunks.forEach((chunk) => {
console.log(chunk.content);
chunk.filteredGroupedChanges.forEach((group) => {
group.changes.forEach((change) => {
console.log(change.content);
});
});
});
////////////////////////////////////////////
// Below here is just hacky testing code
////////////////////////////////////////////
if (DEBUG) {
console.log('\n-------------\n');
// The JavaScript code you want to parse
const code1 = `i[e].call(n.exports, n, n.exports, b), (r = !1);`;
const code2 = `s[e].call(n.exports, n, n.exports, p), (r = !1);`;
const identifiers1 = Array.from(extractIdentifiersFromCode(code1));
const identifiers2 = Array.from(extractIdentifiersFromCode(code2));
const diffIdentifiers = diffArrays(
identifiers1,
identifiers2
// {
// comparator: (left, right) => {}
// },
);
console.log('extractIdentifiers:', {
code1,
code2,
identifiers1,
identifiers2,
areEqual: new Set(identifiers1) === new Set(identifiers2),
});
console.log('diffIdentifiers', diffIdentifiers);
const updatedCode1 = normalizeIdentifierNamesInCode(code1);
const updatedCode2 = normalizeIdentifierNamesInCode(code2);
console.log('normalizeIdentifiers:', {
updatedCode1,
updatedCode2,
areEqual: updatedCode1 === updatedCode2,
});
/////////////////////////////
customCodeDiff(code1, code2);
}
}
/**
* Groups the specified changes into arrays of related changes, directly associating type counts with each group,
* while ensuring the code adheres to the DRY principle.
*
* @param changes Array of change objects.
* @returns {Array} An array of objects, each containing a group of changes and the type counts for that group.
*/
function groupChunkChanges(changes) {
return changes.reduce((acc, change) => {
const lastGroup = acc.length > 0 ? acc[acc.length - 1] : null;
const lastChange = lastGroup
? lastGroup.changes[lastGroup.changes.length - 1]
: null;
// Determine if the current change should be grouped with the last one
const shouldGroupWithLast =
lastChange &&
(change.type === lastChange.type ||
(change.type === 'add' && lastChange.type === 'del'));
if (shouldGroupWithLast) {
// Add the change to the last group and update its type count
lastGroup.changes.push(change);
lastGroup.typeCounts[change.type] =
(lastGroup.typeCounts[change.type] || 0) + 1;
} else {
// Create a new group with the current change if there's no last group or the types don't match
acc.push({
changes: [change],
typeCounts: { [change.type]: 1 },
isContextGroup: false, // Initialized with false; will be updated below
isEqualModifiedLinesCount: false, // Initialized with false; will be updated below
});
}
// Update the flags for the group
const group = acc[acc.length - 1];
group.isContextGroup = group.changes.every(
(change) => change.type === 'normal'
);
group.isEqualModifiedLinesCount =
(group.typeCounts['add'] &&
group.typeCounts['del'] &&
group.typeCounts['add'] === group.typeCounts['del']) ||
false;
return acc;
}, []);
}
function groupChunkChangesV2(chunk) {
const { changes } = chunk;
const typeCounts = changes.reduce(
(acc, change) => ({
...acc,
[change.type]: (acc[change.type] || 0) + 1,
}),
{}
);
const isContextGroup = changes.every((change) => change.type === 'normal');
const isEqualModifiedLinesCount =
(typeCounts['add'] &&
typeCounts['del'] &&
typeCounts['add'] === typeCounts['del']) ||
false;
const wholeChunkGroup = {
changes,
typeCounts,
isContextGroup,
isEqualModifiedLinesCount,
};
// console.error({ wholeChunkGroup, chunk, changes })
return [wholeChunkGroup];
}
/**
* Compares code differences after normalizing them, to assess if the normalized additions and deletions are equal.
*
* @param {Array} changes - An array of change objects.
* @param {Object} errorContext - The context in which the error occurred.
* @returns {Object} An object containing extracted, normalized code and a flag indicating if normalized codes are equal.
*/
function compareNormalizedCodeDiffs(changes, errorContext = {}) {
const changesByType = changes.reduce((acc, change) => {
const changeType = change.type;
// const content = change.content.substring(1).trim(); // Extract content, trimming leading character
const content = change.content.substring(1); // Extract content, trimming leading character (which is the diff type marker)
acc[changeType] = acc[changeType] || [];
acc[changeType].push(content); // Accumulate content by type
return acc;
}, {});
const codeByType = {
del: changesByType.del ? changesByType.del.join('\n') : '',
add: changesByType.add ? changesByType.add.join('\n') : '',
};
// const normalisedCodeByType = {
// del: codeByType.del
// ? normalizeIdentifierNamesInCode(codeByType.del, errorContext)
// : codeByType.del,
// add: codeByType.add
// ? normalizeIdentifierNamesInCode(codeByType.add, errorContext)
// : codeByType.add,
// };
// const normalisedCodeByType = {
// del: codeByType.del
// ? normalizeIdentifierNamesInCodeV2(codeByType.del, errorContext)
// : codeByType.del,
// add: codeByType.add
// ? normalizeIdentifierNamesInCodeV2(codeByType.add, errorContext)
// : codeByType.add,
// };
let normalisedCodeByTypeV3;
let normalisedCodeByType = {
del: codeByType.del,
add: codeByType.add,
};
if (codeByType.del && codeByType.add) {
normalisedCodeByTypeV3 = {
del: normalizeIdentifierNamesInCodeV3(codeByType.del, errorContext),
add: normalizeIdentifierNamesInCodeV3(codeByType.add, errorContext),
};
normalisedCodeByType = {
del: normalisedCodeByTypeV3.del.mappedTokensString,
add: normalisedCodeByTypeV3.add.mappedTokensString,
};
}
const isNormalisedCodeEqual =
(normalisedCodeByType.del &&
normalisedCodeByType.add &&
normalisedCodeByType.del === normalisedCodeByType.add) ||
false;
// TODO: remove this debug logging
if (normalisedCodeByTypeV3) {
if (codeByType.del && codeByType.add && !isNormalisedCodeEqual) {
// Calculate a minimal diff of the un-joined changesByType arrays, after normalisation
// TODO: If we stick with the normalizeIdentifierNamesInCodeV3 tokenisation method, we could do this
// before even joining the arrays together for comparison (if we even need to bother joining
// them anymore when we refactor this code to create a minimal set of changes after normalisation?)
const normalisedDels = changesByType.del.map(
(code) =>
normalizeIdentifierNamesInCodeV3(code, errorContext)
.mappedTokensString
);
const normalisedAdds = changesByType.add.map(
(code) =>
normalizeIdentifierNamesInCodeV3(code, errorContext)
.mappedTokensString
);
const arrayDiff = diffArrays(normalisedDels, normalisedAdds);
console.error('[compareNormalizedCodeDiffs]', {
changesByType,
codeByType,
normalisedCodeByType,
isNormalisedCodeEqual,
normalisedCodeByTypeV3,
delIdentifierMap: normalisedCodeByTypeV3.del.identifierMap,
addIdentifierMap: normalisedCodeByTypeV3.add.identifierMap,
});
console.error('[compareNormalizedCodeDiffs::arrayDiff]', arrayDiff);
// console.error(
// '[compareNormalizedCodeDiffs::arrayDiffValues]',
// arrayDiff.map((d) => d.value)
// );
// TODO: Figure out how to use the results of arrayDiff to minimise the lines of changes we return for
// this group, to just the ones that have actually changed after identifiers are normalised
// TODO: explore whether we can simplify the code for doing this by changing the comparator function used
// by arrayDiff (or another of the jsDiff diff functions)
}
}
return {
changesByType,
codeByType,
normalisedCodeByType,
isNormalisedCodeEqual,
};
}
// TODO: I'm not sure if this function works properly at the moment.. as when I use it,
// I get much smaller/weirder results than with the original
// TODO: I think that's because we're including normal content in both added/deleted
// which means it gets isNormalisedCodeEqual set to true for context chunks,
// which I believe will then be filtered out at the end.
// When we comment out case 'normal', it gets the same result as the previous method, which is what we would expect
// TODO: realistically we probably only want to do it this way if we were including context within the
// chunk groups alongside added/deleted; which we're not currently doing in our main/normal way
function compareNormalizedCodeDiffsV2(changes, errorContext = {}) {
const changesByType = changes.reduce(
(acc, change) => {
const content = change.content.substring(1); // Extract content, trimming leading character (which is the diff type marker)
switch (change.type) {
case 'normal':
console.log('normal content', content);
acc.del.push(content);
acc.add.push(content);
break;
case 'del':
acc.del.push(content);
break;
case 'add':
acc.add.push(content);
break;
}
return acc;
},
{
del: [],
add: [],
}
);
const codeByType = {
del: changesByType.del ? changesByType.del.join('\n') : '',
add: changesByType.add ? changesByType.add.join('\n') : '',
};
// const normalisedCodeByType = {
// del: codeByType.del
// ? normalizeIdentifierNamesInCode(codeByType.del, errorContext)
// : codeByType.del,
// add: codeByType.add
// ? normalizeIdentifierNamesInCode(codeByType.add, errorContext)
// : codeByType.add,
// };
const normalisedCodeByType = {
del: codeByType.del
? normalizeIdentifierNamesInCodeV2(codeByType.del, errorContext)
: codeByType.del,
add: codeByType.add
? normalizeIdentifierNamesInCodeV2(codeByType.add, errorContext)
: codeByType.add,
};
const isNormalisedCodeEqual =
(normalisedCodeByType.del &&
normalisedCodeByType.add &&
normalisedCodeByType.del === normalisedCodeByType.add) ||
false;
return {
changesByType,
codeByType,
normalisedCodeByType,
isNormalisedCodeEqual,
};
}
/**
* Prepares the specified code for parsing by the AST parser by making minor fixes to prevent parsing errors.
*
* This is designed for assisting with parsing code snippets, not entire files.
*
* @param {string} code - The code to prepare for AST parsing.
* @returns {string} The prepared code.
*
* @TODO Figure out how to fix the following:
* - if statements that are missing their body
* - Partial object members that are missing their 'wrapper object'
* - Partial ternary expressions that are missing their 'foo ?' but have their 'bar : baz'
* - 'else' / 'else if' statements that are missing their 'if' condition
* - 'case:' statements that are missing their 'switch' condition
*/
function prepareCodeForASTParsing(code) {
let updatedCode = code;
// Remove newlines from code and collapse excess whitespace
// updatedCode = updatedCode.replace(/[\r\n]+/g, '');
updatedCode = updatedCode
.replace(/[\r\n]+/g, ' ') // Replace newlines with a single space
.replace(/\s\s+/g, ' ') // Collapse multiple spaces into one
.trim(); // Trim leading and trailing whitespace
// Fix members with missing left-hand side
if (updatedCode.trimStart().startsWith('.')) {
updatedCode = `FOO${updatedCode.trimStart()}`;
}
// TODO: Ternaries can currently fail when they need brackets balanced within them, eg:
// code: ' ? (en && "number" != typeof en && lM(Y, et, en)',
// preparedCode: 'true ? (en && "number" != typeof en && lM(Y, et, en) : false)'
// Fix ternaries with missing left/right-hand sides
if (updatedCode.trimStart().startsWith('?') && !updatedCode.includes(':')) {
updatedCode = `true ${updatedCode.trimStart()} : false`;
}
// Fix ternaries with missing left-hand side
// TODO: need to figure how to detect ternaries that are missing left-hand side but don't start with '?' as well
if (updatedCode.trimStart().startsWith('?')) {
updatedCode = `true ${updatedCode.trimStart()}`;
}
// Fix colons with missing left-hand side
if (updatedCode.trimStart().startsWith(':')) {
updatedCode = updatedCode.trimStart().slice(1);
}
// Fix 'else if' statements with missing body
// TODO: Not sure if this works currently, it didn't seem to improve our parsing error count
// if (
// (updatedCode.trimStart().startsWith('else if') ||
// updatedCode.trimStart().startsWith('} else if')) &&
// !updatedCode.includes('{')
// ) {
// updatedCode = `${updatedCode.trimEnd()} {}`;
// }
// Fix 'else if' statements with missing 'if'
if (updatedCode.trimStart().startsWith('else if')) {
updatedCode = `if (true) {} ${updatedCode.trimStart()}`;
}
if (updatedCode.trimStart().startsWith('} else if')) {
updatedCode = `if (true) { ${updatedCode.trimStart()}`;
}
// Fix 'if' statements with missing body
if (updatedCode.trimStart().startsWith('if') && !updatedCode.includes('{')) {
updatedCode = `${updatedCode} {}`;
}
// Fix 'case' statements with missing 'switch'
if (
updatedCode.trimStart().startsWith('case') &&
!updatedCode.includes('switch')
) {
updatedCode = `switch (true) { ${updatedCode.trim()} }`;
}
// Fix 'for' statements with missing body
if (updatedCode.trimStart().startsWith('for') && !updatedCode.includes('{')) {
updatedCode = `${updatedCode.trimEnd()} {}`;
}
// Remove the last character if it's a comma
if (updatedCode.trimEnd().endsWith(',')) {
updatedCode = updatedCode.trimEnd().slice(0, -1);
}
// Fix expressions with missing right-hand side
if (
updatedCode.trimEnd().endsWith('&&') ||
updatedCode.trimEnd().endsWith('||') ||
updatedCode.trimEnd().endsWith('=') ||
updatedCode.trimEnd().endsWith('+') ||
updatedCode.trimEnd().endsWith('-') ||
updatedCode.trimEnd().endsWith('*') ||
updatedCode.trimEnd().endsWith('/')
) {
updatedCode = `${updatedCode} true`;
}
// Fix partial object updates
// TODO: This isn't perfect, but it seems to work for at least some cases
const objectPropertyPattern = /\w+:\s*[\w().]+,?/;
if (
objectPropertyPattern.test(updatedCode) &&
!updatedCode.includes('{') &&
!updatedCode.includes('}')
) {
updatedCode = `{${updatedCode.trim()}}`;
}