Fourth batch
[git/raj.git] / t / helper / test-oidmap.c
blob0acf99931ee176982d61078dc0e2d882377c05fd
1 #include "test-tool.h"
2 #include "cache.h"
3 #include "oidmap.h"
4 #include "strbuf.h"
6 /* key is an oid and value is a name (could be a refname for example) */
7 struct test_entry {
8 struct oidmap_entry entry;
9 char name[FLEX_ARRAY];
12 #define DELIM " \t\r\n"
15 * Read stdin line by line and print result of commands to stdout:
17 * hash oidkey -> sha1hash(oidkey)
18 * put oidkey namevalue -> NULL / old namevalue
19 * get oidkey -> NULL / namevalue
20 * remove oidkey -> NULL / old namevalue
21 * iterate -> oidkey1 namevalue1\noidkey2 namevalue2\n...
24 int cmd__oidmap(int argc, const char **argv)
26 struct strbuf line = STRBUF_INIT;
27 struct oidmap map = OIDMAP_INIT;
29 setup_git_directory();
31 /* init oidmap */
32 oidmap_init(&map, 0);
34 /* process commands from stdin */
35 while (strbuf_getline(&line, stdin) != EOF) {
36 char *cmd, *p1 = NULL, *p2 = NULL;
37 struct test_entry *entry;
38 struct object_id oid;
40 /* break line into command and up to two parameters */
41 cmd = strtok(line.buf, DELIM);
42 /* ignore empty lines */
43 if (!cmd || *cmd == '#')
44 continue;
46 p1 = strtok(NULL, DELIM);
47 if (p1)
48 p2 = strtok(NULL, DELIM);
50 if (!strcmp("put", cmd) && p1 && p2) {
52 if (get_oid(p1, &oid)) {
53 printf("Unknown oid: %s\n", p1);
54 continue;
57 /* create entry with oid_key = p1, name_value = p2 */
58 FLEX_ALLOC_STR(entry, name, p2);
59 oidcpy(&entry->entry.oid, &oid);
61 /* add / replace entry */
62 entry = oidmap_put(&map, entry);
64 /* print and free replaced entry, if any */
65 puts(entry ? entry->name : "NULL");
66 free(entry);
68 } else if (!strcmp("get", cmd) && p1) {
70 if (get_oid(p1, &oid)) {
71 printf("Unknown oid: %s\n", p1);
72 continue;
75 /* lookup entry in oidmap */
76 entry = oidmap_get(&map, &oid);
78 /* print result */
79 puts(entry ? entry->name : "NULL");
81 } else if (!strcmp("remove", cmd) && p1) {
83 if (get_oid(p1, &oid)) {
84 printf("Unknown oid: %s\n", p1);
85 continue;
88 /* remove entry from oidmap */
89 entry = oidmap_remove(&map, &oid);
91 /* print result and free entry*/
92 puts(entry ? entry->name : "NULL");
93 free(entry);
95 } else if (!strcmp("iterate", cmd)) {
97 struct oidmap_iter iter;
98 oidmap_iter_init(&map, &iter);
99 while ((entry = oidmap_iter_next(&iter)))
100 printf("%s %s\n", oid_to_hex(&entry->entry.oid), entry->name);
102 } else {
104 printf("Unknown command %s\n", cmd);
109 strbuf_release(&line);
110 oidmap_free(&map, 1);
111 return 0;