feat(diff): implemented the myers diff algorithm with longest common subsequence and printing the diff
This commit is contained in:
parent
f7043cc03a
commit
190aa7cc76
4 changed files with 167 additions and 7 deletions
65
include/utilities.h
Normal file
65
include/utilities.h
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
#ifndef UTILITIES_H
|
||||
#define UTILITIES_H
|
||||
|
||||
#include "file.h"
|
||||
#include "action_list.h"
|
||||
|
||||
#define RESET "\033[0m"
|
||||
#define RED_BG "\033[41m"
|
||||
#define GREEN_BG "\033[42m"
|
||||
#define BLACK_FG "\033[30m"
|
||||
|
||||
void visualize_diff(File* old_version, File* new_version, ActionList* actions) {
|
||||
int* deleted_lines = calloc(old_version->lines, sizeof(int));
|
||||
int* inserted_lines = calloc(new_version->lines, sizeof(int));
|
||||
|
||||
if (!deleted_lines || !inserted_lines) {
|
||||
free(deleted_lines);
|
||||
free(inserted_lines);
|
||||
return;
|
||||
}
|
||||
|
||||
for (uint64_t i = 0; i < actions->len; i++) {
|
||||
if (actions->actions[i].type == DELETE) {
|
||||
deleted_lines[actions->actions[i].line_original] = 1;
|
||||
} else if (actions->actions[i].type == INSERT) {
|
||||
inserted_lines[actions->actions[i].line_changed] = 1;
|
||||
}
|
||||
}
|
||||
|
||||
uint64_t old_idx = 0, new_idx = 0;
|
||||
|
||||
while (old_idx < old_version->lines || new_idx < new_version->lines) {
|
||||
// DELETE
|
||||
if (old_idx < old_version->lines && deleted_lines[old_idx]) {
|
||||
printf("%s%s%4ld | %s%s\n", RED_BG, BLACK_FG, old_idx+1, old_version->content[old_idx], RESET);
|
||||
old_idx++;
|
||||
}
|
||||
// INSERT
|
||||
else if (new_idx < new_version->lines && inserted_lines[new_idx]) {
|
||||
printf("%s%s %4ld | %s%s\n", GREEN_BG, BLACK_FG, new_idx+1, new_version->content[new_idx], RESET);
|
||||
new_idx++;
|
||||
}
|
||||
// STAYS
|
||||
else if (old_idx < old_version->lines && new_idx < new_version->lines) {
|
||||
printf("%4ld %4ld | %s\n", old_idx+1, new_idx+1, old_version->content[old_idx]);
|
||||
old_idx++;
|
||||
new_idx++;
|
||||
}
|
||||
// DELETE
|
||||
else if (old_idx < old_version->lines) {
|
||||
printf("%s%s%4ld | %s%s\n", RED_BG, BLACK_FG, old_idx+1, old_version->content[old_idx], RESET);
|
||||
old_idx++;
|
||||
}
|
||||
// INSERT
|
||||
else if (new_idx < new_version->lines) {
|
||||
printf("%s%s %4ld | %s%s\n", GREEN_BG, BLACK_FG, new_idx+1, new_version->content[new_idx], RESET);
|
||||
new_idx++;
|
||||
}
|
||||
}
|
||||
|
||||
free(deleted_lines);
|
||||
free(inserted_lines);
|
||||
}
|
||||
|
||||
#endif // UTILITIES_H
|
||||
Loading…
Add table
Add a link
Reference in a new issue