• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2008 Google Inc.  All rights reserved.
3 //
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file or at
6 // https://developers.google.com/open-source/licenses/bsd
7 
8 // Author: kenton@google.com (Kenton Varda)
9 // emulates google3/file/base/file.cc
10 
11 #include "google/protobuf/testing/file.h"
12 
13 #include <stdio.h>
14 #include <sys/stat.h>
15 #include <sys/types.h>
16 #ifdef _MSC_VER
17 #define WIN32_LEAN_AND_MEAN  // yeah, right
18 #include <windows.h>         // Find*File().  :(
19 // #include <direct.h>
20 #else
21 #include <dirent.h>
22 #include <unistd.h>
23 #endif
24 #include <errno.h>
25 
26 #include "absl/log/absl_check.h"
27 #include "absl/log/absl_log.h"
28 #include "absl/strings/str_cat.h"
29 #include "absl/strings/string_view.h"
30 #include "google/protobuf/io/io_win32.h"
31 #include "google/protobuf/stubs/status_macros.h"
32 
33 // Needs to be last.
34 #include "google/protobuf/port_def.inc"  // NOLINT
35 
36 namespace google {
37 namespace protobuf {
38 
39 #ifdef _WIN32
40 // Windows doesn't have symbolic links.
41 #define lstat stat
42 // DO NOT include <io.h>, instead create functions in io_win32.{h,cc} and import
43 // them like we do below.
44 #endif
45 
46 #ifdef _WIN32
47 using google::protobuf::io::win32::access;
48 using google::protobuf::io::win32::chdir;
49 using google::protobuf::io::win32::fopen;
50 using google::protobuf::io::win32::mkdir;
51 using google::protobuf::io::win32::stat;
52 #endif
53 
Exists(const std::string & name)54 bool File::Exists(const std::string& name) {
55   return access(name.c_str(), F_OK) == 0;
56 }
57 
ReadFileToString(const std::string & name,std::string * output,bool text_mode)58 absl::Status File::ReadFileToString(const std::string& name,
59                                     std::string* output, bool text_mode) {
60   char buffer[1024];
61   FILE* file = fopen(name.c_str(), text_mode ? "rt" : "rb");
62   if (file == nullptr) return absl::NotFoundError("Could not open file");
63 
64   while (true) {
65     size_t n = fread(buffer, 1, sizeof(buffer), file);
66     if (n <= 0) break;
67     output->append(buffer, n);
68   }
69 
70   int error = ferror(file);
71   if (fclose(file) != 0) return absl::InternalError("Failed to close file");
72   if (error != 0) return absl::InternalError("Error parsing file");
73   return absl::OkStatus();
74 }
75 
ReadFileToStringOrDie(const std::string & name,std::string * output)76 void File::ReadFileToStringOrDie(const std::string& name, std::string* output) {
77   ABSL_CHECK_OK(ReadFileToString(name, output)) << "Could not read: " << name;
78 }
79 
WriteStringToFile(absl::string_view contents,const std::string & name)80 absl::Status File::WriteStringToFile(absl::string_view contents,
81                                      const std::string& name) {
82   FILE* file = fopen(name.c_str(), "wb");
83   if (file == nullptr) {
84     return absl::InternalError(
85         absl::StrCat("fopen(", name, ", \"wb\"): ", strerror(errno)));
86   }
87 
88   if (fwrite(contents.data(), 1, contents.size(), file) != contents.size()) {
89     fclose(file);
90     return absl::InternalError(
91         absl::StrCat("fwrite(", name, "): ", strerror(errno)));
92   }
93 
94   if (fclose(file) != 0) {
95     return absl::InternalError("Failed to close file");
96   }
97   return absl::OkStatus();
98 }
99 
WriteStringToFileOrDie(absl::string_view contents,const std::string & name)100 void File::WriteStringToFileOrDie(absl::string_view contents,
101                                   const std::string& name) {
102   FILE* file = fopen(name.c_str(), "wb");
103   ABSL_CHECK(file != nullptr)
104       << "fopen(" << name << ", \"wb\"): " << strerror(errno);
105   ABSL_CHECK_EQ(fwrite(contents.data(), 1, contents.size(), file),
106                 contents.size())
107       << "fwrite(" << name << "): " << strerror(errno);
108   ABSL_CHECK(fclose(file) == 0)
109       << "fclose(" << name << "): " << strerror(errno);
110 }
111 
CreateDir(const std::string & name,int mode)112 absl::Status File::CreateDir(const std::string& name, int mode) {
113   if (!name.empty()) {
114     ABSL_CHECK(name[name.size() - 1] != '.');
115   }
116   if (mkdir(name.c_str(), mode) != 0) {
117     return absl::InternalError("Failed to create directory");
118   }
119   return absl::OkStatus();
120 }
121 
RecursivelyCreateDir(const std::string & path,int mode)122 absl::Status File::RecursivelyCreateDir(const std::string& path, int mode) {
123   if (CreateDir(path, mode).ok()) return absl::OkStatus();
124 
125   if (Exists(path)) return absl::AlreadyExistsError("Path already exists");
126 
127   // Try creating the parent.
128   std::string::size_type slashpos = path.find_last_of('/');
129   if (slashpos == std::string::npos) {
130     return absl::FailedPreconditionError("No parent given");
131   }
132 
133   RETURN_IF_ERROR(RecursivelyCreateDir(path.substr(0, slashpos), mode));
134   return CreateDir(path, mode);
135 }
136 
DeleteRecursively(const std::string & name,void * dummy1,void * dummy2)137 void File::DeleteRecursively(const std::string& name, void* dummy1,
138                              void* dummy2) {
139   if (name.empty()) return;
140 
141   // We don't care too much about error checking here since this is only used
142   // in tests to delete temporary directories that are under /tmp anyway.
143 
144 #ifdef _MSC_VER
145   // This interface is so weird.
146   WIN32_FIND_DATAA find_data;
147   HANDLE find_handle =
148       FindFirstFileA(absl::StrCat(name, "/*").c_str(), &find_data);
149   if (find_handle == INVALID_HANDLE_VALUE) {
150     // Just delete it, whatever it is.
151     DeleteFileA(name.c_str());
152     RemoveDirectoryA(name.c_str());
153     return;
154   }
155 
156   do {
157     std::string entry_name = find_data.cFileName;
158     if (entry_name != "." && entry_name != "..") {
159       std::string path = absl::StrCat(name, "/", entry_name);
160       if (find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
161         DeleteRecursively(path, NULL, NULL);
162         RemoveDirectoryA(path.c_str());
163       } else {
164         DeleteFileA(path.c_str());
165       }
166     }
167   } while(FindNextFileA(find_handle, &find_data));
168   FindClose(find_handle);
169 
170   RemoveDirectoryA(name.c_str());
171 #else
172   // Use opendir()!  Yay!
173   // lstat = Don't follow symbolic links.
174   struct stat stats;
175   if (lstat(name.c_str(), &stats) != 0) return;
176 
177   if (S_ISDIR(stats.st_mode)) {
178     DIR* dir = opendir(name.c_str());
179     if (dir != NULL) {
180       while (true) {
181         struct dirent* entry = readdir(dir);
182         if (entry == NULL) break;
183         std::string entry_name = entry->d_name;
184         if (entry_name != "." && entry_name != "..") {
185           DeleteRecursively(absl::StrCat(name, "/", entry_name), NULL, NULL);
186         }
187       }
188     }
189 
190     closedir(dir);
191     rmdir(name.c_str());
192 
193   } else if (S_ISREG(stats.st_mode)) {
194     remove(name.c_str());
195   }
196 #endif
197 }
198 
ChangeWorkingDirectory(const std::string & new_working_directory)199 bool File::ChangeWorkingDirectory(const std::string& new_working_directory) {
200   return chdir(new_working_directory.c_str()) == 0;
201 }
202 
203 }  // namespace protobuf
204 }  // namespace google
205 
206 #include "google/protobuf/port_undef.inc"  // NOLINT
207