forked from facebook/watchman
-
Notifications
You must be signed in to change notification settings - Fork 0
/
state.c
127 lines (97 loc) · 2.28 KB
/
state.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
/* Copyright 2012-present Facebook, Inc.
* Licensed under the Apache License, Version 2.0 */
#include "watchman.h"
static pthread_mutex_t state_lock = PTHREAD_MUTEX_INITIALIZER;
bool w_state_load(void)
{
json_t *state = NULL;
bool result = false;
json_error_t err;
if (dont_save_state) {
return true;
}
state = json_load_file(watchman_state_file, 0, &err);
if (!state) {
w_log(W_LOG_ERR, "failed to parse json from %s: %s\n",
watchman_state_file,
err.text);
goto out;
}
if (!w_root_load_state(state)) {
goto out;
}
result = true;
out:
if (state) {
json_decref(state);
}
return result;
}
#if defined(HAVE_MKOSTEMP) && defined(sun)
// Not guaranteed to be defined in stdlib.h
extern int mkostemp(char *, int);
#endif
int w_mkstemp(char *templ)
{
int fd;
#ifdef HAVE_MKOSTEMP
fd = mkostemp(templ, O_CLOEXEC);
#else
fd = mkstemp(templ);
#endif
if (fd == -1) {
return -1;
}
w_set_cloexec(fd);
return fd;
}
bool w_state_save(void)
{
json_t *state;
w_jbuffer_t buffer;
int fd = -1;
char tmpname[WATCHMAN_NAME_MAX];
bool result = false;
if (dont_save_state) {
return true;
}
pthread_mutex_lock(&state_lock);
state = json_object();
if (!w_json_buffer_init(&buffer)) {
w_log(W_LOG_ERR, "save_state: failed to init json buffer\n");
goto out;
}
snprintf(tmpname, sizeof(tmpname), "%sXXXXXX",
watchman_state_file);
fd = w_mkstemp(tmpname);
if (fd == -1) {
w_log(W_LOG_ERR, "save_state: unable to create temporary file: %s\n",
strerror(errno));
goto out;
}
json_object_set_new(state, "version", json_string(PACKAGE_VERSION));
/* now ask the different subsystems to fill out the state */
if (!w_root_save_state(state)) {
goto out;
}
/* we've prepared what we're going to save, so write it out */
w_json_buffer_write(&buffer, fd, state, JSON_INDENT(4));
/* atomically replace the old contents */
result = rename(tmpname, watchman_state_file) == 0;
out:
if (state) {
json_decref(state);
}
w_json_buffer_free(&buffer);
if (fd != -1) {
if (!result) {
// If we didn't succeed, remove our temporary file
unlink(tmpname);
}
close(fd);
}
pthread_mutex_unlock(&state_lock);
return result;
}
/* vim:ts=2:sw=2:et:
*/