-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrefs.c
More file actions
78 lines (63 loc) · 1.7 KB
/
refs.c
File metadata and controls
78 lines (63 loc) · 1.7 KB
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
#include "mvcs.h"
/* Update a reference */
int update_ref(const char *ref, const unsigned char *hash) {
char path[MAX_PATH_LEN];
char hash_hex[HASH_HEX_SIZE];
hash_to_hex(hash, hash_hex);
if (strncmp(ref, "refs/", 5) == 0) {
sprintf(path, ".mvcs/%s", ref);
} else {
sprintf(path, "%s", ref);
}
/* Create parent directory if needed */
char dir[MAX_PATH_LEN];
strcpy(dir, path);
char *last_slash = strrchr(dir, '/');
if (last_slash) {
*last_slash = '\0';
create_directory(dir);
}
FILE *f = fopen(path, "w");
if (!f) return -1;
fprintf(f, "%s\n", hash_hex);
fclose(f);
return 0;
}
/* Read a reference */
int read_ref(const char *ref, unsigned char *hash) {
char path[MAX_PATH_LEN];
if (strncmp(ref, "refs/", 5) == 0) {
sprintf(path, ".mvcs/%s", ref);
} else {
sprintf(path, "%s", ref);
}
FILE *f = fopen(path, "r");
if (!f) return -1;
char hash_hex[HASH_HEX_SIZE];
if (fgets(hash_hex, sizeof(hash_hex), f) == NULL) {
fclose(f);
return -1;
}
fclose(f);
return hex_to_hash(hash_hex, hash);
}
/* Get current HEAD commit */
int get_head(unsigned char *hash) {
FILE *f = fopen(HEAD_FILE, "r");
if (!f) return -1;
char line[256];
if (fgets(line, sizeof(line), f) == NULL) {
fclose(f);
return -1;
}
fclose(f);
/* Check if HEAD is symbolic ref */
if (strncmp(line, "ref: ", 5) == 0) {
char ref[256];
sscanf(line + 5, "%s", ref);
return read_ref(ref, hash);
} else {
/* Direct hash */
return hex_to_hash(line, hash);
}
}