-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinker.c
111 lines (101 loc) · 2.24 KB
/
linker.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
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
/*
* Copyright 2016, Clemens Fruhwirth <[email protected]>
* Recursively symlinks the content of a source dir into a target dir.
*
*/
#define _GNU_SOURCE
#include <dirent.h>
#include <unistd.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <stdlib.h>
int is_dir(char *path) {
struct stat buf;
int rc = stat(path, &buf);
if(rc == 0) {
if(S_ISDIR(buf.st_mode)) {
return 1;
} else {
return 0;
}
} else if(errno == ENOENT) {
return 0;
} else {
perror("stat error");
exit(-1);
}
}
int exists(char *path) {
struct stat buf;
int rc = stat(path, &buf);
if(rc == 0) {
return 1;
} else if(errno == ENOENT) {
return 0;
} else {
perror("stat error");
exit(-1);
}
}
/**
* Same as asprintf(buf, ..) except that buf is returned.
*/
char *aasprintf(const char *fmt, ...) {
va_list args; char *buf; int rc;
va_start(args, fmt);
rc = vasprintf(&buf, fmt, args);
if(rc < 0) {
perror("vasprintf");
exit(-1);
}
va_end(args);
return buf;
}
void symlinkx(char *sourcePath, char *targetPath) {
int rc;
printf("%s -> %s\n", sourcePath, targetPath);
rc = symlink(sourcePath, targetPath);
if(rc < 0) {
perror("symlink");
}
}
void link_source(char *source, char *target) {
DIR *dp;
struct dirent *ep;
dp = opendir(source);
if(dp != NULL) {
while(ep = readdir(dp)) {
if(!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
continue;
char *sourcePath = aasprintf("%s/%s", source, ep->d_name);
char *targetPath = aasprintf("%s/%s", target, ep->d_name);
if(is_dir(sourcePath)) {
if(exists(targetPath)) {
if(is_dir(targetPath)) {
link_source(sourcePath, targetPath);
} else {
printf("%s exists but isn't a directory as %s.\n", targetPath, sourcePath);
}
} else {
symlinkx(sourcePath, targetPath);
}
} else {
symlinkx(sourcePath, targetPath);
}
free(sourcePath);
free(targetPath);
}
closedir(dp);
} else perror ("Couldn't open the directory");
}
void main(int argc, char **argv) {
if(argc < 3) {
fprintf(stderr, "Usage: linker <sourcedir> <targetdir>\n");
exit(-1);
}
link_source(argv[1], argv[2]);
}