Marco Poletti | 6669c69 | 2022-04-07 14:42:56 -0700 | [diff] [blame] | 1 | // 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 Poletti | b5239c9 | 2022-05-11 09:46:05 -0700 | [diff] [blame] | 7 | #include "llvm/Support/MemoryBuffer.h" |
Lukasz Anforowicz | cec7a8a | 2022-04-27 10:24:51 -0700 | [diff] [blame] | 8 | #include "llvm/Support/raw_ostream.h" |
Marco Poletti | 6669c69 | 2022-04-07 14:42:56 -0700 | [diff] [blame] | 9 | |
| 10 | namespace crubit { |
| 11 | |
Marco Poletti | b5239c9 | 2022-05-11 09:46:05 -0700 | [diff] [blame] | 12 | absl::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 Poletti | 6669c69 | 2022-04-07 14:42:56 -0700 | [diff] [blame] | 22 | absl::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 |