Files
codeql/swift/extractor/infra/file/TargetFile.h
Paolo Tranquilli 521e6235b5 Swift: use std::filesystem and picoSHA2
This replaces usages of `llvm::fs` and string manipulation with
`std::filesystem`, also replacing `std::string` with
`std::filesystem::path` where it made sense.

Moreover MD5 hashing used in macOS file remapping was replaced by
SHA256 hashing using a small header-only SHA256 C++ library with an
MIT license, https://github.com/okdshin/PicoSHA2.

File contents hashing was relocated to the newly created `file` library
for later planned reuse.
2022-10-26 13:23:44 +02:00

50 lines
1.4 KiB
C++

#pragma once
#include <string>
#include <fstream>
#include <optional>
#include <cerrno>
#include <filesystem>
namespace codeql {
// Only the first process trying to create a `TargetFile` for a given `target` is allowed to do
// so, all others will have `create` return `std::nullopt`.
// The content streamed to the `TargetFile` is written to `workingDir/target`, and is moved onto
// `targetDir/target` on destruction.
class TargetFile {
std::filesystem::path workingPath;
std::filesystem::path targetPath;
std::ofstream out;
public:
static std::optional<TargetFile> create(const std::filesystem::path& target,
const std::filesystem::path& targetDir,
const std::filesystem::path& workingDir);
~TargetFile() { commit(); }
TargetFile(TargetFile&& other) = default;
// move assignment deleted as non-trivial and not needed
TargetFile& operator=(TargetFile&& other) = delete;
template <typename T>
TargetFile& operator<<(T&& value) {
errno = 0;
out << value;
checkOutput("write to file");
return *this;
}
private:
TargetFile(const std::filesystem::path& target,
const std::filesystem::path& targetDir,
const std::filesystem::path& workingDir);
bool init();
void checkOutput(const char* action);
void commit();
};
} // namespace codeql