ccls/src/cache.cc

77 lines
2.1 KiB
C++
Raw Normal View History

2017-04-09 02:24:32 +00:00
#include "cache.h"
#include "indexer.h"
#include "language_server_api.h"
2017-09-22 01:14:57 +00:00
#include "platform.h"
#include <loguru/loguru.hpp>
2017-04-09 02:24:32 +00:00
#include <algorithm>
namespace {
2017-12-02 05:07:30 +00:00
std::string GetCachedBaseFileName(Config* config,
const std::string& source_file,
bool create_dir = false) {
assert(!config->cacheDirectory.empty());
std::string cache_file;
size_t len = config->projectRoot.size();
if (StartsWith(source_file, config->projectRoot)) {
cache_file = EscapeFileName(config->projectRoot) + '/' +
EscapeFileName(source_file.substr(len));
} else
cache_file = EscapeFileName(source_file);
return config->cacheDirectory + cache_file;
2017-04-09 02:24:32 +00:00
}
} // namespace
std::unique_ptr<IndexFile> LoadCachedIndex(Config* config,
const std::string& filename) {
if (!config->enableCacheRead)
return nullptr;
2017-04-22 07:42:57 +00:00
optional<std::string> file_content = ReadContent(
2017-12-02 05:07:30 +00:00
GetCachedBaseFileName(config, filename) + ".json");
if (!file_content)
2017-04-09 02:24:32 +00:00
return nullptr;
return Deserialize(filename, *file_content, IndexFile::kCurrentVersion);
2017-04-09 02:24:32 +00:00
}
optional<std::string> LoadCachedFileContents(Config* config,
2017-04-22 07:42:57 +00:00
const std::string& filename) {
if (!config->enableCacheRead)
2017-04-21 17:00:36 +00:00
return nullopt;
2017-12-02 05:07:30 +00:00
return ReadContent(GetCachedBaseFileName(config, filename));
}
2017-09-22 01:14:57 +00:00
void WriteToCache(Config* config, IndexFile& file) {
if (!config->enableCacheWrite)
return;
2017-04-22 07:42:57 +00:00
std::string cache_basename =
2017-12-02 05:07:30 +00:00
GetCachedBaseFileName(config, file.path);
if (file.file_contents_.empty()) {
LOG_S(ERROR) << "No cached file contents; performing potentially stale "
<< "file-copy for " << file.path;
CopyFileTo(cache_basename, file.path);
} else {
std::ofstream cache_content;
cache_content.open(cache_basename);
assert(cache_content.good());
cache_content << file.file_contents_;
cache_content.close();
}
std::string indexed_content = Serialize(file);
2017-04-09 02:24:32 +00:00
std::ofstream cache;
cache.open(cache_basename + ".json");
2017-04-09 02:24:32 +00:00
assert(cache.good());
cache << indexed_content;
cache.close();
2017-04-19 00:05:14 +00:00
}