at commit a0189536

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 chdir_notify_callback cb;
11 void *data;
12 struct list_head list;
13 };
14 static LIST_HEAD(chdir_notify_entries);
15
16 void chdir_notify_register(chdir_notify_callback cb,
17 void *data)
18 {
19 struct chdir_notify_entry *e = xmalloc(sizeof(*e));
20 e->cb = cb;
21 e->data = data;
22 list_add_tail(&e->list, &chdir_notify_entries);
23 }
24
25 void chdir_notify_unregister(chdir_notify_callback cb,
26 void *data)
27 {
28 struct list_head *pos, *p;
29
30 list_for_each_safe(pos, p, &chdir_notify_entries) {
31 struct chdir_notify_entry *e =
32 list_entry(pos, struct chdir_notify_entry, list);
33
34 if (e->cb != cb || e->data != data)
35 continue;
36
37 list_del(pos);
38 free(e);
39 }
40 }
41
42 int chdir_notify(const char *new_cwd)
43 {
44 struct strbuf old_cwd = STRBUF_INIT;
45 struct list_head *pos;
46
47 if (strbuf_getcwd(&old_cwd) < 0)
48 return -1;
49 if (chdir(new_cwd) < 0) {
50 int saved_errno = errno;
51 strbuf_release(&old_cwd);
52 errno = saved_errno;
53 return -1;
54 }
55
56 trace_printf_key(&trace_setup_key,
57 "setup: chdir from '%s' to '%s'",
58 old_cwd.buf, new_cwd);
59
60 list_for_each(pos, &chdir_notify_entries) {
61 struct chdir_notify_entry *e =
62 list_entry(pos, struct chdir_notify_entry, list);
63 e->cb(old_cwd.buf, new_cwd, e->data);
64 }
65
66 strbuf_release(&old_cwd);
67 return 0;
68 }
69
70 char *reparent_relative_path(const char *old_cwd,
71 const char *new_cwd,
72 const char *path)
73 {
74 char *ret, *full;
75
76 if (is_absolute_path(path))
77 return xstrdup(path);
78
79 full = xstrfmt("%s/%s", old_cwd, path);
80 ret = xstrdup(remove_leading_path(full, new_cwd));
81 free(full);
82
83 return ret;
84 }