Raw
1 #include "git-compat-util.h"
2 #include "abspath.h"
3 #include "chdir-notify.h"
4 #include "list.h"
5 #include "path.h"
6 #include "strbuf.h"
7 #include "trace.h"
8
9 struct chdir_notify_entry {
10 const char *name;
11 chdir_notify_callback cb;
12 void *data;
13 struct list_head list;
14 };
15 static LIST_HEAD(chdir_notify_entries);
16
17 void chdir_notify_register(const char *name,
18 chdir_notify_callback cb,
19 void *data)
20 {
21 struct chdir_notify_entry *e = xmalloc(sizeof(*e));
22 e->name = name;
23 e->cb = cb;
24 e->data = data;
25 list_add_tail(&e->list, &chdir_notify_entries);
26 }
27
28 void chdir_notify_unregister(const char *name, chdir_notify_callback cb,
29 void *data)
30 {
31 struct list_head *pos, *p;
32
33 list_for_each_safe(pos, p, &chdir_notify_entries) {
34 struct chdir_notify_entry *e =
35 list_entry(pos, struct chdir_notify_entry, list);
36
37 if (e->cb != cb || e->data != data || !e->name != !name ||
38 (e->name && strcmp(e->name, name)))
39 continue;
40
41 list_del(pos);
42 free(e);
43 }
44 }
45
46 static void reparent_cb(const char *name,
47 const char *old_cwd,
48 const char *new_cwd,
49 void *data)
50 {
51 char **path = data;
52 char *tmp = *path;
53
54 if (!tmp)
55 return;
56
57 *path = reparent_relative_path(old_cwd, new_cwd, tmp);
58 free(tmp);
59
60 if (name) {
61 trace_printf_key(&trace_setup_key,
62 "setup: reparent %s to '%s'",
63 name, *path);
64 }
65 }
66
67 void chdir_notify_reparent(const char *name, char **path)
68 {
69 chdir_notify_register(name, reparent_cb, path);
70 }
71
72 int chdir_notify(const char *new_cwd)
73 {
74 struct strbuf old_cwd = STRBUF_INIT;
75 struct list_head *pos;
76
77 if (strbuf_getcwd(&old_cwd) < 0)
78 return -1;
79 if (chdir(new_cwd) < 0) {
80 int saved_errno = errno;
81 strbuf_release(&old_cwd);
82 errno = saved_errno;
83 return -1;
84 }
85
86 trace_printf_key(&trace_setup_key,
87 "setup: chdir from '%s' to '%s'",
88 old_cwd.buf, new_cwd);
89
90 list_for_each(pos, &chdir_notify_entries) {
91 struct chdir_notify_entry *e =
92 list_entry(pos, struct chdir_notify_entry, list);
93 e->cb(e->name, old_cwd.buf, new_cwd, e->data);
94 }
95
96 strbuf_release(&old_cwd);
97 return 0;
98 }
99
100 char *reparent_relative_path(const char *old_cwd,
101 const char *new_cwd,
102 const char *path)
103 {
104 char *ret, *full;
105
106 if (is_absolute_path(path))
107 return xstrdup(path);
108
109 full = xstrfmt("%s/%s", old_cwd, path);
110 ret = xstrdup(remove_leading_path(full, new_cwd));
111 free(full);
112
113 return ret;
114 }