The seventh batch
[git.git] / reftable / system.c
blobadf8e4d30b823c7d13a58c8e7ed050412ed08cf1
1 #include "system.h"
2 #include "basics.h"
3 #include "reftable-error.h"
4 #include "../lockfile.h"
5 #include "../tempfile.h"
7 int tmpfile_from_pattern(struct reftable_tmpfile *out, const char *pattern)
9 struct tempfile *tempfile;
11 tempfile = mks_tempfile(pattern);
12 if (!tempfile)
13 return REFTABLE_IO_ERROR;
15 out->path = tempfile->filename.buf;
16 out->fd = tempfile->fd;
17 out->priv = tempfile;
19 return 0;
22 int tmpfile_close(struct reftable_tmpfile *t)
24 struct tempfile *tempfile = t->priv;
25 int ret = close_tempfile_gently(tempfile);
26 t->fd = -1;
27 if (ret < 0)
28 return REFTABLE_IO_ERROR;
29 return 0;
32 int tmpfile_delete(struct reftable_tmpfile *t)
34 struct tempfile *tempfile = t->priv;
35 int ret = delete_tempfile(&tempfile);
36 *t = REFTABLE_TMPFILE_INIT;
37 if (ret < 0)
38 return REFTABLE_IO_ERROR;
39 return 0;
42 int tmpfile_rename(struct reftable_tmpfile *t, const char *path)
44 struct tempfile *tempfile = t->priv;
45 int ret = rename_tempfile(&tempfile, path);
46 *t = REFTABLE_TMPFILE_INIT;
47 if (ret < 0)
48 return REFTABLE_IO_ERROR;
49 return 0;
52 int flock_acquire(struct reftable_flock *l, const char *target_path,
53 long timeout_ms)
55 struct lock_file *lockfile;
56 int err;
58 lockfile = reftable_malloc(sizeof(*lockfile));
59 if (!lockfile)
60 return REFTABLE_OUT_OF_MEMORY_ERROR;
62 err = hold_lock_file_for_update_timeout(lockfile, target_path, LOCK_NO_DEREF,
63 timeout_ms);
64 if (err < 0) {
65 reftable_free(lockfile);
66 if (errno == EEXIST)
67 return REFTABLE_LOCK_ERROR;
68 return -1;
71 l->fd = get_lock_file_fd(lockfile);
72 l->path = get_lock_file_path(lockfile);
73 l->priv = lockfile;
75 return 0;
78 int flock_close(struct reftable_flock *l)
80 struct lock_file *lockfile = l->priv;
81 int ret;
83 if (!lockfile)
84 return REFTABLE_API_ERROR;
86 ret = close_lock_file_gently(lockfile);
87 l->fd = -1;
88 if (ret < 0)
89 return REFTABLE_IO_ERROR;
91 return 0;
94 int flock_release(struct reftable_flock *l)
96 struct lock_file *lockfile = l->priv;
97 int ret;
99 if (!lockfile)
100 return 0;
102 ret = rollback_lock_file(lockfile);
103 reftable_free(lockfile);
104 *l = REFTABLE_FLOCK_INIT;
105 if (ret < 0)
106 return REFTABLE_IO_ERROR;
108 return 0;
111 int flock_commit(struct reftable_flock *l)
113 struct lock_file *lockfile = l->priv;
114 int ret;
116 if (!lockfile)
117 return REFTABLE_API_ERROR;
119 ret = commit_lock_file(lockfile);
120 reftable_free(lockfile);
121 *l = REFTABLE_FLOCK_INIT;
122 if (ret < 0)
123 return REFTABLE_IO_ERROR;
125 return 0;