/
index.c
83 lines (73 loc) · 1.93 KB
/
index.c
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
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "index.h"
#include "path.h"
void add_to_index(char *hash, char *path) {
int filecheck = index_file_check(hash,path);
if(!filecheck)
return;
char *indexpath = get_repo_troll_dir();
int repo_path_len = strlen(indexpath) - 7;
indexpath = (char *) realloc(indexpath, strlen(indexpath) + 5);
strcat(indexpath, "index");
if(filecheck > 0) {
FILE *findex = fopen(indexpath, "r+");
free(indexpath);
fseek(findex, 0, SEEK_SET);
char str[256];
int line = 1;
while(fgets(str, 256, findex)) {
if(line == filecheck) {
fseek(findex, -strlen(str), SEEK_CUR);
fwrite(hash, 40, 1, findex);
fseek(findex, 1, SEEK_CUR);
fwrite(path, strlen(path), 1, findex);
fclose(findex);
return;
}
line++;
}
fclose(findex);
}
int indexfd = open(indexpath, O_RDWR);
free(indexpath);
lseek(indexfd, 0, SEEK_END);
char *fullpath = realpath(path, NULL);
char *relpath = fullpath + repo_path_len;
write(indexfd, hash, 40);
write(indexfd, " ", 1);
write(indexfd, relpath, strlen(relpath));
write(indexfd, "\n", 1);
close(indexfd);
free(fullpath);
}
/*
* Returns 0 if exact file is found,
* The line of the file in index if found with different hash,
* or -1 if file is not found in .troll/index
*/
int index_file_check(char *hash, char *path) {
char *indexpath = get_repo_troll_dir();
indexpath = (char *) realloc(indexpath, strlen(indexpath) + 5);
strcat(indexpath, "index");
FILE *findex = fopen(indexpath, "r");
free(indexpath);
fseek(findex, 0, SEEK_SET);
char str[256];
int line = 1;
while(fgets(str, 256, findex)) {
if(strstr(str,hash)) {
return 0;
}
if(strstr(str,path)) {
return line;
}
line++;
}
fclose(findex);
return -1;
}