forked from facebook/watchman
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstate.c
104 lines (79 loc) · 1.95 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
/* 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;
}
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 = 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:
*/