Git fork
1#include "../git-compat-util.h"
2
3#include "system.h"
4#include "basics.h"
5#include "reftable-error.h"
6#include "../lockfile.h"
7#include "../tempfile.h"
8
9uint32_t reftable_rand(void)
10{
11 return git_rand(CSPRNG_BYTES_INSECURE);
12}
13
14int tmpfile_from_pattern(struct reftable_tmpfile *out, const char *pattern)
15{
16 struct tempfile *tempfile;
17
18 tempfile = mks_tempfile(pattern);
19 if (!tempfile)
20 return REFTABLE_IO_ERROR;
21
22 out->path = tempfile->filename.buf;
23 out->fd = tempfile->fd;
24 out->priv = tempfile;
25
26 return 0;
27}
28
29int tmpfile_close(struct reftable_tmpfile *t)
30{
31 struct tempfile *tempfile = t->priv;
32 int ret = close_tempfile_gently(tempfile);
33 t->fd = -1;
34 if (ret < 0)
35 return REFTABLE_IO_ERROR;
36 return 0;
37}
38
39int tmpfile_delete(struct reftable_tmpfile *t)
40{
41 struct tempfile *tempfile = t->priv;
42 int ret = delete_tempfile(&tempfile);
43 *t = REFTABLE_TMPFILE_INIT;
44 if (ret < 0)
45 return REFTABLE_IO_ERROR;
46 return 0;
47}
48
49int tmpfile_rename(struct reftable_tmpfile *t, const char *path)
50{
51 struct tempfile *tempfile = t->priv;
52 int ret = rename_tempfile(&tempfile, path);
53 *t = REFTABLE_TMPFILE_INIT;
54 if (ret < 0)
55 return REFTABLE_IO_ERROR;
56 return 0;
57}
58
59int flock_acquire(struct reftable_flock *l, const char *target_path,
60 long timeout_ms)
61{
62 struct lock_file *lockfile;
63 int err;
64
65 lockfile = reftable_malloc(sizeof(*lockfile));
66 if (!lockfile)
67 return REFTABLE_OUT_OF_MEMORY_ERROR;
68
69 err = hold_lock_file_for_update_timeout(lockfile, target_path, LOCK_NO_DEREF,
70 timeout_ms);
71 if (err < 0) {
72 reftable_free(lockfile);
73 if (errno == EEXIST)
74 return REFTABLE_LOCK_ERROR;
75 return REFTABLE_IO_ERROR;
76 }
77
78 l->fd = get_lock_file_fd(lockfile);
79 l->path = get_lock_file_path(lockfile);
80 l->priv = lockfile;
81
82 return 0;
83}
84
85int flock_close(struct reftable_flock *l)
86{
87 struct lock_file *lockfile = l->priv;
88 int ret;
89
90 if (!lockfile)
91 return REFTABLE_API_ERROR;
92
93 ret = close_lock_file_gently(lockfile);
94 l->fd = -1;
95 if (ret < 0)
96 return REFTABLE_IO_ERROR;
97
98 return 0;
99}
100
101int flock_release(struct reftable_flock *l)
102{
103 struct lock_file *lockfile = l->priv;
104 int ret;
105
106 if (!lockfile)
107 return 0;
108
109 ret = rollback_lock_file(lockfile);
110 reftable_free(lockfile);
111 *l = REFTABLE_FLOCK_INIT;
112 if (ret < 0)
113 return REFTABLE_IO_ERROR;
114
115 return 0;
116}
117
118int flock_commit(struct reftable_flock *l)
119{
120 struct lock_file *lockfile = l->priv;
121 int ret;
122
123 if (!lockfile)
124 return REFTABLE_API_ERROR;
125
126 ret = commit_lock_file(lockfile);
127 reftable_free(lockfile);
128 *l = REFTABLE_FLOCK_INIT;
129 if (ret < 0)
130 return REFTABLE_IO_ERROR;
131
132 return 0;
133}