Merge commit 'e8760cde01299817daae26c9ad074b776bbd8f88'
[git/mingw.git] / lockfile.c
blob934e1c7de06483447fcc3cb1f4a22801bbfbb2b5
1 /*
2 * Copyright (c) 2005, Junio C Hamano
3 */
4 #include "cache.h"
6 static struct lock_file *lock_file_list;
7 static const char *alternate_index_output;
9 static void remove_lock_file(void)
11 while (lock_file_list) {
12 if (lock_file_list->filename[0]) {
13 close(lock_file_list->fd);
14 unlink(lock_file_list->filename);
16 lock_file_list = lock_file_list->next;
20 static void remove_lock_file_on_signal(int signo)
22 remove_lock_file();
23 signal(SIGINT, SIG_DFL);
24 raise(signo);
27 static int lock_file(struct lock_file *lk, const char *path)
29 sprintf(lk->filename, "%s.lock", path);
30 lk->fd = open(lk->filename, O_RDWR | O_CREAT | O_EXCL, 0666);
31 if (0 <= lk->fd) {
32 if (!lk->on_list) {
33 lk->next = lock_file_list;
34 lock_file_list = lk;
35 lk->on_list = 1;
37 if (lock_file_list) {
38 signal(SIGINT, remove_lock_file_on_signal);
39 atexit(remove_lock_file);
41 if (adjust_shared_perm(lk->filename))
42 return error("cannot fix permission bits on %s",
43 lk->filename);
45 else
46 lk->filename[0] = 0;
47 return lk->fd;
50 int hold_lock_file_for_update(struct lock_file *lk, const char *path, int die_on_error)
52 int fd = lock_file(lk, path);
53 if (fd < 0 && die_on_error)
54 die("unable to create '%s.lock': %s", path, strerror(errno));
55 return fd;
58 int commit_lock_file(struct lock_file *lk)
60 char result_file[PATH_MAX];
61 int i;
62 close(lk->fd);
63 strcpy(result_file, lk->filename);
64 i = strlen(result_file) - 5; /* .lock */
65 result_file[i] = 0;
66 unlink(result_file);
67 i = rename(lk->filename, result_file);
68 lk->filename[0] = 0;
69 return i;
72 int hold_locked_index(struct lock_file *lk, int die_on_error)
74 return hold_lock_file_for_update(lk, get_index_file(), die_on_error);
77 void set_alternate_index_output(const char *name)
79 alternate_index_output = name;
82 int commit_locked_index(struct lock_file *lk)
84 if (alternate_index_output) {
85 int result = rename(lk->filename, alternate_index_output);
86 lk->filename[0] = 0;
87 return result;
89 else
90 return commit_lock_file(lk);
93 void rollback_lock_file(struct lock_file *lk)
95 if (lk->filename[0]) {
96 close(lk->fd);
97 unlink(lk->filename);
99 lk->filename[0] = 0;