1 // Copyright 2020 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef TOOLS_GN_FILE_WRITER_H_ 6 #define TOOLS_GN_FILE_WRITER_H_ 7 8 #include <string_view> 9 10 #include "util/build_config.h" 11 12 #if defined(OS_WIN) 13 #include "base/win/scoped_handle.h" 14 #else 15 #include "base/files/scoped_file.h" 16 #endif 17 18 #include <string> 19 20 namespace base { 21 class FilePath; 22 } 23 24 // Convenience class to write data to a file. This is used to work around two 25 // limitations of base::WriteFile, i.e.: 26 // 27 // - base::WriteFile() doesn't allow multiple writes to the target file. 28 // 29 // 30 // - Windows-specific issues created by anti-virus programs required opening 31 // the file differently (see http://crbug.com/468437). 32 // 33 // Usage is: 34 // 1) Create instance. 35 // 2) Call Create() to create the file. 36 // 3) Call Write() one or more times to write data to it. 37 // 4) Call Close(), or the destructor, to close the file. 38 // 39 // As soon as one method fails, all other calls will return false, this allows 40 // simplified error checking as in: 41 // 42 // FileWriter writer; 43 // writer.Create(<some_path>); 44 // writer.Write(<some_data>); 45 // writer.Write(<some_more_data>); 46 // if (!writer.Close()) { 47 // ... error happened in one of the above calls. 48 // } 49 // 50 class FileWriter { 51 public: 52 FileWriter() = default; 53 ~FileWriter(); 54 55 // Create output file. Return true on success, false otherwise. 56 bool Create(const base::FilePath& file_path); 57 58 // Append |data| to the output file. Return true on success, or false on 59 // failure or if any previous Create() or Write() call failed. 60 bool Write(std::string_view data); 61 62 // Close the file. Return true on success, or false on failure or if 63 // any previous Create() or Write() call failed. 64 bool Close(); 65 66 private: 67 #if defined(OS_WIN) 68 base::win::ScopedHandle file_; 69 std::string file_path_; 70 #else 71 base::ScopedFD fd_; 72 #endif 73 bool valid_ = true; 74 }; 75 76 #endif // TOOLS_GN_FILE_WRITER_H_ 77