hash-ll.h: split out of hash.h to remove dependency on repository.h
[alt-git.git] / t / helper / test-oidmap.c
blobbba4099f65ff5d648815cd3ab63bed5e8fd498cf
1 #include "test-tool.h"
2 #include "hex.h"
3 #include "object-name.h"
4 #include "oidmap.h"
5 #include "repository.h"
6 #include "setup.h"
7 #include "strbuf.h"
9 /* key is an oid and value is a name (could be a refname for example) */
10 struct test_entry {
11 struct oidmap_entry entry;
12 char name[FLEX_ARRAY];
15 #define DELIM " \t\r\n"
18 * Read stdin line by line and print result of commands to stdout:
20 * hash oidkey -> sha1hash(oidkey)
21 * put oidkey namevalue -> NULL / old namevalue
22 * get oidkey -> NULL / namevalue
23 * remove oidkey -> NULL / old namevalue
24 * iterate -> oidkey1 namevalue1\noidkey2 namevalue2\n...
27 int cmd__oidmap(int argc, const char **argv)
29 struct strbuf line = STRBUF_INIT;
30 struct oidmap map = OIDMAP_INIT;
32 setup_git_directory();
34 /* init oidmap */
35 oidmap_init(&map, 0);
37 /* process commands from stdin */
38 while (strbuf_getline(&line, stdin) != EOF) {
39 char *cmd, *p1 = NULL, *p2 = NULL;
40 struct test_entry *entry;
41 struct object_id oid;
43 /* break line into command and up to two parameters */
44 cmd = strtok(line.buf, DELIM);
45 /* ignore empty lines */
46 if (!cmd || *cmd == '#')
47 continue;
49 p1 = strtok(NULL, DELIM);
50 if (p1)
51 p2 = strtok(NULL, DELIM);
53 if (!strcmp("put", cmd) && p1 && p2) {
55 if (repo_get_oid(the_repository, p1, &oid)) {
56 printf("Unknown oid: %s\n", p1);
57 continue;
60 /* create entry with oid_key = p1, name_value = p2 */
61 FLEX_ALLOC_STR(entry, name, p2);
62 oidcpy(&entry->entry.oid, &oid);
64 /* add / replace entry */
65 entry = oidmap_put(&map, entry);
67 /* print and free replaced entry, if any */
68 puts(entry ? entry->name : "NULL");
69 free(entry);
71 } else if (!strcmp("get", cmd) && p1) {
73 if (repo_get_oid(the_repository, p1, &oid)) {
74 printf("Unknown oid: %s\n", p1);
75 continue;
78 /* lookup entry in oidmap */
79 entry = oidmap_get(&map, &oid);
81 /* print result */
82 puts(entry ? entry->name : "NULL");
84 } else if (!strcmp("remove", cmd) && p1) {
86 if (repo_get_oid(the_repository, p1, &oid)) {
87 printf("Unknown oid: %s\n", p1);
88 continue;
91 /* remove entry from oidmap */
92 entry = oidmap_remove(&map, &oid);
94 /* print result and free entry*/
95 puts(entry ? entry->name : "NULL");
96 free(entry);
98 } else if (!strcmp("iterate", cmd)) {
100 struct oidmap_iter iter;
101 oidmap_iter_init(&map, &iter);
102 while ((entry = oidmap_iter_next(&iter)))
103 printf("%s %s\n", oid_to_hex(&entry->entry.oid), entry->name);
105 } else {
107 printf("Unknown command %s\n", cmd);
112 strbuf_release(&line);
113 oidmap_free(&map, 1);
114 return 0;