-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstorage.cc
79 lines (62 loc) · 2.06 KB
/
storage.cc
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
#include <string>
#include <vector>
#include "atl/file.h"
#include "atl/optional.h"
#include "atl/status.h"
#include "atl/statusor.h"
#include "atl/string.h"
#include "serializer.h"
#include "storage.h"
#include "worklog.h"
namespace worklog {
atl::StatusOr<Log> Storage::LoadById(int id) {
std::string log_path =
atl::JoinStr("/", config_.logs_dir, std::to_string(id));
if (!atl::FileExists(log_path)) {
return atl::Status(atl::error::NOT_FOUND,
"The work log does not exist under: " + log_path);
}
atl::Optional<std::string> content = atl::FileReadContent(log_path);
if (!content) {
return atl::Status(atl::error::INTERNAL,
"Failed to read content from: " + log_path);
}
Log log = hs_.Unserialize(content.value());
log.id = id;
return log;
}
atl::Status Storage::Save(Log& log) {
if (log.id > 0) {
return atl::Status(atl::error::INVALID_ARGUMENT,
"Worklog has an id, please use Update");
}
atl::Optional<int> next_id_value = NextId(config_);
if (!next_id_value) {
return atl::Status(atl::error::INTERNAL, "Failed to generate a new id");
}
int next_id = next_id_value.value();
log.id = next_id;
std::string log_path =
atl::JoinStr("/", config_.logs_dir, std::to_string(log.id));
if (atl::FileExists(log_path)) {
return atl::Status(atl::error::INTERNAL,
"A worklog does already exist under: " + log_path);
}
atl::FileWriteContent(log_path, hs_.Serialize(log));
return atl::Status();
}
atl::Status Storage::Update(const Log& log) {
if (log.id <= 0) {
return atl::Status(atl::error::INVALID_ARGUMENT,
"Worklog has no id, please use Save");
}
std::string log_path =
atl::JoinStr("/", config_.logs_dir, std::to_string(log.id));
if (!atl::FileExists(log_path)) {
return atl::Status(atl::error::INTERNAL,
"A worklog does not yet exist under: " + log_path);
}
atl::FileWriteContent(log_path, hs_.Serialize(log));
return atl::Status();
}
} // namespace worklog