Bazel client: mock out read/write calls
Make blaze::ReadFileDescriptor(int fd, ...) and
blaze::WriteFile(int fd, ...) platform-independent
by mocking out the read(2) and write(2) calls.
Also rename ReadFileDescriptor to ReadFrom and
introduce a new WriteTo method that encapsulates
WriteFile's prior logic.
In particular these functions now take a
read_func/write_func function argument instead of
a file descriptor, so the read(2)/write(2) calls
can be mocked out.
This allows us to use these functions on Windows
too, where read(2)/write(2) are not implemented,
and we can inject a different
read_func/write_func.
See https://github.com/bazelbuild/bazel/issues/2107
--
MOS_MIGRATED_REVID=140195973
diff --git a/src/main/cpp/blaze_util.h b/src/main/cpp/blaze_util.h
index 06c75ed..cdef849 100644
--- a/src/main/cpp/blaze_util.h
+++ b/src/main/cpp/blaze_util.h
@@ -21,6 +21,7 @@
#include <sys/types.h>
+#include <functional>
#include <sstream>
#include <string>
#include <vector>
@@ -52,11 +53,12 @@
bool ReadFile(const std::string &filename, std::string *content,
int max_size = 0);
-// Replaces 'content' with contents of file descriptor 'fd'.
-// If `max_size` is positive, the method reads at most that many bytes; if it
-// otherwise the method reads the whole file.
+// Replaces 'content' with data read from a source using `read_func`.
+// If `max_size` is positive, the method reads at most that many bytes;
+// otherwise the method reads everything.
// Returns false on error. Can be called from a signal handler.
-bool ReadFileDescriptor(int fd, std::string *content, int max_size = 0);
+bool ReadFrom(const std::function<int(void *, int)> &read_func,
+ std::string *content, int max_size = 0);
// Writes 'content' into file 'filename', and makes it executable.
// Returns false on failure, sets errno.
@@ -66,6 +68,11 @@
// Returns false on failure, sets errno.
bool WriteFile(const void* data, size_t size, const std::string &filename);
+// Writes `size` bytes from `data` into a destination using `write_func`.
+// Returns false on failure, sets errno.
+bool WriteTo(const std::function<int(const void *, size_t)> &write_func,
+ const void *data, size_t size);
+
// Unlinks the file given by 'file_path'.
// Returns true on success. In case of failure sets errno.
bool UnlinkPath(const std::string &file_path);