2 * Copyright (c) 2005, Junio C Hamano
6 static struct lock_file *lock_file_list;
7 static const char *alternate_index_output;
9 static void remove_lock_file(void)
13 while (lock_file_list) {
14 if (lock_file_list->owner == me &&
15 lock_file_list->filename[0])
16 unlink(lock_file_list->filename);
17 lock_file_list = lock_file_list->next;
21 static void remove_lock_file_on_signal(int signo)
24 signal(SIGINT, SIG_DFL);
28 static int lock_file(struct lock_file *lk, const char *path)
33 if ((!lstat(path, &st)) && S_ISLNK(st.st_mode)) {
35 static char target[PATH_MAX];
36 sz = readlink(path, target, sizeof(target));
38 warning("Cannot readlink %s", path);
39 else if (target[0] != '/')
40 warning("Cannot lock target of relative symlink %s", path);
44 sprintf(lk->filename, "%s.lock", path);
45 fd = open(lk->filename, O_RDWR | O_CREAT | O_EXCL, 0666);
47 if (!lock_file_list) {
48 signal(SIGINT, remove_lock_file_on_signal);
49 atexit(remove_lock_file);
53 lk->next = lock_file_list;
57 if (adjust_shared_perm(lk->filename))
58 return error("cannot fix permission bits on %s",
66 int hold_lock_file_for_update(struct lock_file *lk, const char *path, int die_on_error)
68 int fd = lock_file(lk, path);
69 if (fd < 0 && die_on_error)
70 die("unable to create '%s.lock': %s", path, strerror(errno));
74 int commit_lock_file(struct lock_file *lk)
76 char result_file[PATH_MAX];
78 strcpy(result_file, lk->filename);
79 i = strlen(result_file) - 5; /* .lock */
81 i = rename(lk->filename, result_file);
86 int hold_locked_index(struct lock_file *lk, int die_on_error)
88 return hold_lock_file_for_update(lk, get_index_file(), die_on_error);
91 void set_alternate_index_output(const char *name)
93 alternate_index_output = name;
96 int commit_locked_index(struct lock_file *lk)
98 if (alternate_index_output) {
99 int result = rename(lk->filename, alternate_index_output);
104 return commit_lock_file(lk);
107 void rollback_lock_file(struct lock_file *lk)
110 unlink(lk->filename);