-
Notifications
You must be signed in to change notification settings - Fork 15
/
map.c
106 lines (90 loc) · 2.06 KB
/
map.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
// Map a container to a key. Use an empty container to delete a key.
//
// Example:
//
// $ plash build -f alpine
// 342
//
// $ plash map myfavorite 342
//
// $ plash map myfavorite
// 342
//
// $ plash build --from-map myfavorite
// 342
//
// $ plash map myfavorite ''
//
// $ plash map myfavorite
// $
#define USAGE "usage: plash map KEY [ IMAGE_ID ]\n"
#define _GNU_SOURCE
#include <assert.h>
#include <errno.h>
#include <libgen.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <plash.h>
char *plash_data;
void get(char const *linkpath) {
char *nodepath;
nodepath = realpath(linkpath, NULL);
if (nodepath == NULL) {
if (errno == ENOENT)
return;
pl_fatal("realpath");
}
puts(basename(nodepath));
}
void del(char const *linkpath) {
if (unlink(linkpath) == -1) {
if (errno == ENOENT)
return;
pl_fatal("unlink");
}
}
void set(char const *linkpath, char *container_id) {
char *nodepath;
nodepath = plash("nodepath", container_id);
if (chdir(plash("mkdtemp")) == -1)
pl_fatal("chdir");
if (asprintf(&nodepath, "..%s", nodepath + strlen(plash_data)) == -1)
pl_fatal("asprintf");
if (symlink(nodepath, "link") == -1)
pl_fatal("symlink");
if (rename("link", linkpath) == -1)
pl_fatal("rename");
}
int map_main(int argc, char *argv[]) {
char *linkpath;
if (argc < 2) {
{
fputs(USAGE, stderr);
return EXIT_FAILURE;
}
}
plash_data = plash("data");
assert(plash_data);
assert(plash_data[0] == '/');
// validate map key
if (!argv[1][0])
pl_fatal("empty map name not allowed");
else if (strchr(argv[1], '/') != NULL)
pl_fatal("'/' not allowed in map name");
// the location of the symlink for this map key
if (asprintf(&linkpath, "%s/map/%s", plash_data, argv[1]) == -1)
pl_fatal("asprintf");
if (argc == 2) {
get(linkpath);
} else if (argc == 3 && !argv[2][0]) {
del(linkpath);
} else if (argc == 3) {
set(linkpath, argv[2]);
} else {
fputs(USAGE, stderr);
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}