Junio C Hamano | 415e96c | 2005-05-15 21:23:12 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (c) 2005, Junio C Hamano |
| 3 | */ |
| 4 | #include <signal.h> |
| 5 | #include "cache.h" |
| 6 | |
| 7 | static struct cache_file *cache_file_list; |
| 8 | |
| 9 | static void remove_lock_file(void) |
| 10 | { |
| 11 | while (cache_file_list) { |
| 12 | if (cache_file_list->lockfile[0]) |
| 13 | unlink(cache_file_list->lockfile); |
| 14 | cache_file_list = cache_file_list->next; |
| 15 | } |
| 16 | } |
| 17 | |
| 18 | static void remove_lock_file_on_signal(int signo) |
| 19 | { |
| 20 | remove_lock_file(); |
| 21 | } |
| 22 | |
| 23 | int hold_index_file_for_update(struct cache_file *cf, const char *path) |
| 24 | { |
Alex Riesen | d6e548d | 2005-10-05 14:58:11 | [diff] [blame] | 25 | int fd; |
Junio C Hamano | 415e96c | 2005-05-15 21:23:12 | [diff] [blame] | 26 | sprintf(cf->lockfile, "%s.lock", path); |
Alex Riesen | d6e548d | 2005-10-05 14:58:11 | [diff] [blame] | 27 | fd = open(cf->lockfile, O_RDWR | O_CREAT | O_EXCL, 0666); |
| 28 | if (fd >=0 && !cf->next) { |
| 29 | cf->next = cache_file_list; |
| 30 | cache_file_list = cf; |
Junio C Hamano | 415e96c | 2005-05-15 21:23:12 | [diff] [blame] | 31 | signal(SIGINT, remove_lock_file_on_signal); |
| 32 | atexit(remove_lock_file); |
| 33 | } |
Alex Riesen | d6e548d | 2005-10-05 14:58:11 | [diff] [blame] | 34 | return fd; |
Junio C Hamano | 415e96c | 2005-05-15 21:23:12 | [diff] [blame] | 35 | } |
| 36 | |
| 37 | int commit_index_file(struct cache_file *cf) |
| 38 | { |
| 39 | char indexfile[PATH_MAX]; |
| 40 | int i; |
| 41 | strcpy(indexfile, cf->lockfile); |
| 42 | i = strlen(indexfile) - 5; /* .lock */ |
| 43 | indexfile[i] = 0; |
| 44 | i = rename(cf->lockfile, indexfile); |
| 45 | cf->lockfile[0] = 0; |
| 46 | return i; |
| 47 | } |
| 48 | |
| 49 | void rollback_index_file(struct cache_file *cf) |
| 50 | { |
| 51 | if (cf->lockfile[0]) |
| 52 | unlink(cf->lockfile); |
| 53 | cf->lockfile[0] = 0; |
| 54 | } |
| 55 | |