blob: 613b64232955e79305fc45e4a14198f691d7d1d9 [file] [log] [blame]
Marco Poletti6669c692022-04-07 14:42:56 -07001// Part of the Crubit project, under the Apache License v2.0 with LLVM
2// Exceptions. See /LICENSE for license information.
3// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
4
5#include "common/file_io.h"
6
Marco Polettib5239c92022-05-11 09:46:05 -07007#include "llvm/Support/MemoryBuffer.h"
Lukasz Anforowiczcec7a8a2022-04-27 10:24:51 -07008#include "llvm/Support/raw_ostream.h"
Marco Poletti6669c692022-04-07 14:42:56 -07009
10namespace crubit {
11
Marco Polettib5239c92022-05-11 09:46:05 -070012absl::StatusOr<std::string> GetFileContents(absl::string_view path) {
13 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> err_or_buffer =
14 llvm::MemoryBuffer::getFileOrSTDIN(path.data(), /* IsText= */ true);
15 if (std::error_code err = err_or_buffer.getError()) {
16 return absl::Status(absl::StatusCode::kInternal, err.message());
17 }
18
19 return std::string((*err_or_buffer)->getBuffer());
20}
21
Marco Poletti6669c692022-04-07 14:42:56 -070022absl::Status SetFileContents(absl::string_view path,
23 absl::string_view contents) {
24 std::error_code error_code;
25 llvm::raw_fd_ostream stream(path, error_code);
26 if (error_code) {
27 return absl::Status(absl::StatusCode::kInternal, error_code.message());
28 }
29 stream << contents;
30 stream.close();
31 if (stream.has_error()) {
32 return absl::Status(absl::StatusCode::kInternal, stream.error().message());
33 }
34 return absl::OkStatus();
35}
36
37} // namespace crubit