-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrepository.c
More file actions
73 lines (62 loc) · 1.59 KB
/
repository.c
File metadata and controls
73 lines (62 loc) · 1.59 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
#include "mvcs.h"
/* Create directory recursively */
int create_directory(const char *path) {
char tmp[MAX_PATH_LEN];
char *p = NULL;
size_t len;
snprintf(tmp, sizeof(tmp), "%s", path);
len = strlen(tmp);
if (tmp[len - 1] == '/') {
tmp[len - 1] = 0;
}
for (p = tmp + 1; *p; p++) {
if (*p == '/') {
*p = 0;
mkdir(tmp, 0755);
*p = '/';
}
}
mkdir(tmp, 0755);
return 0;
}
/* Check if file exists */
int file_exists(const char *path) {
return access(path, F_OK) == 0;
}
/* Check if path is a directory */
int is_directory(const char *path) {
struct stat st;
if (stat(path, &st) != 0) {
return 0;
}
return S_ISDIR(st.st_mode);
}
/* Initialize repository */
int mvcs_init(void) {
if (file_exists(MVCS_DIR)) {
fprintf(stderr, "Repository already exists\n");
return -1;
}
/* Create directory structure */
create_directory(MVCS_DIR);
create_directory(OBJECTS_DIR);
create_directory(REFS_DIR);
create_directory(REFS_HEADS_DIR);
/* Create HEAD file pointing to master */
FILE *f = fopen(HEAD_FILE, "w");
if (!f) {
perror("Failed to create HEAD");
return -1;
}
fprintf(f, "ref: refs/heads/master\n");
fclose(f);
/* Create empty index */
f = fopen(INDEX_FILE, "w");
if (f) fclose(f);
printf("Initialized empty MVCS repository in %s/\n", MVCS_DIR);
return 0;
}
/* Check if current directory is a repository */
int mvcs_is_repo(void) {
return file_exists(MVCS_DIR) && is_directory(MVCS_DIR);
}