blob: a1ed6c1d5699db27ea6d6a4df7b3a84c0e53f3a9 [file] [log] [blame]
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001/*
2 * Copyright 2016 Google Inc. All rights reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17// clang-format off
18// Dont't remove `format off`, it prevent reordering of win-includes.
Austin Schuh272c6132020-11-14 16:37:52 -080019
20#if defined(__MINGW32__) || defined(__MINGW64__) || defined(__CYGWIN__) || \
21 defined(__QNXNTO__)
22# define _POSIX_C_SOURCE 200809L
23# define _XOPEN_SOURCE 700L
24#endif
25
Austin Schuhe89fa2d2019-08-14 20:24:23 -070026#ifdef _WIN32
27# ifndef WIN32_LEAN_AND_MEAN
28# define WIN32_LEAN_AND_MEAN
29# endif
30# ifndef NOMINMAX
31# define NOMINMAX
32# endif
33# ifdef _MSC_VER
34# include <crtdbg.h>
35# endif
36# include <windows.h> // Must be included before <direct.h>
37# include <direct.h>
38# include <winbase.h>
39# undef interface // This is also important because of reasons
Austin Schuhe89fa2d2019-08-14 20:24:23 -070040#endif
41// clang-format on
42
Austin Schuhe89fa2d2019-08-14 20:24:23 -070043#include "flatbuffers/util.h"
44
45#include <sys/stat.h>
James Kuszmaul8e62b022022-03-22 09:33:25 -070046
Austin Schuhe89fa2d2019-08-14 20:24:23 -070047#include <clocale>
Austin Schuh272c6132020-11-14 16:37:52 -080048#include <cstdlib>
James Kuszmaul8e62b022022-03-22 09:33:25 -070049#include <functional>
Austin Schuhe89fa2d2019-08-14 20:24:23 -070050#include <fstream>
51
James Kuszmaul8e62b022022-03-22 09:33:25 -070052#include "flatbuffers/base.h"
53
Austin Schuhe89fa2d2019-08-14 20:24:23 -070054namespace flatbuffers {
55
56bool FileExistsRaw(const char *name) {
57 std::ifstream ifs(name);
58 return ifs.good();
59}
60
61bool LoadFileRaw(const char *name, bool binary, std::string *buf) {
62 if (DirExists(name)) return false;
63 std::ifstream ifs(name, binary ? std::ifstream::binary : std::ifstream::in);
64 if (!ifs.is_open()) return false;
65 if (binary) {
66 // The fastest way to read a file into a string.
67 ifs.seekg(0, std::ios::end);
68 auto size = ifs.tellg();
69 (*buf).resize(static_cast<size_t>(size));
70 ifs.seekg(0, std::ios::beg);
71 ifs.read(&(*buf)[0], (*buf).size());
72 } else {
73 // This is slower, but works correctly on all platforms for text files.
74 std::ostringstream oss;
75 oss << ifs.rdbuf();
76 *buf = oss.str();
77 }
78 return !ifs.bad();
79}
80
81static LoadFileFunction g_load_file_function = LoadFileRaw;
82static FileExistsFunction g_file_exists_function = FileExistsRaw;
83
84bool LoadFile(const char *name, bool binary, std::string *buf) {
85 FLATBUFFERS_ASSERT(g_load_file_function);
86 return g_load_file_function(name, binary, buf);
87}
88
89bool FileExists(const char *name) {
90 FLATBUFFERS_ASSERT(g_file_exists_function);
91 return g_file_exists_function(name);
92}
93
94bool DirExists(const char *name) {
95 // clang-format off
96
97 #ifdef _WIN32
98 #define flatbuffers_stat _stat
99 #define FLATBUFFERS_S_IFDIR _S_IFDIR
100 #else
101 #define flatbuffers_stat stat
102 #define FLATBUFFERS_S_IFDIR S_IFDIR
103 #endif
104 // clang-format on
105 struct flatbuffers_stat file_info;
106 if (flatbuffers_stat(name, &file_info) != 0) return false;
107 return (file_info.st_mode & FLATBUFFERS_S_IFDIR) != 0;
108}
109
110LoadFileFunction SetLoadFileFunction(LoadFileFunction load_file_function) {
111 LoadFileFunction previous_function = g_load_file_function;
112 g_load_file_function = load_file_function ? load_file_function : LoadFileRaw;
113 return previous_function;
114}
115
116FileExistsFunction SetFileExistsFunction(
117 FileExistsFunction file_exists_function) {
118 FileExistsFunction previous_function = g_file_exists_function;
119 g_file_exists_function =
120 file_exists_function ? file_exists_function : FileExistsRaw;
121 return previous_function;
122}
123
124bool SaveFile(const char *name, const char *buf, size_t len, bool binary) {
125 std::ofstream ofs(name, binary ? std::ofstream::binary : std::ofstream::out);
126 if (!ofs.is_open()) return false;
127 ofs.write(buf, len);
128 return !ofs.bad();
129}
130
131// We internally store paths in posix format ('/'). Paths supplied
132// by the user should go through PosixPath to ensure correct behavior
133// on Windows when paths are string-compared.
134
135static const char kPathSeparatorWindows = '\\';
136static const char *PathSeparatorSet = "\\/"; // Intentionally no ':'
137
138std::string StripExtension(const std::string &filepath) {
139 size_t i = filepath.find_last_of('.');
140 return i != std::string::npos ? filepath.substr(0, i) : filepath;
141}
142
143std::string GetExtension(const std::string &filepath) {
144 size_t i = filepath.find_last_of('.');
145 return i != std::string::npos ? filepath.substr(i + 1) : "";
146}
147
148std::string StripPath(const std::string &filepath) {
149 size_t i = filepath.find_last_of(PathSeparatorSet);
150 return i != std::string::npos ? filepath.substr(i + 1) : filepath;
151}
152
153std::string StripFileName(const std::string &filepath) {
154 size_t i = filepath.find_last_of(PathSeparatorSet);
155 return i != std::string::npos ? filepath.substr(0, i) : "";
156}
157
158std::string ConCatPathFileName(const std::string &path,
159 const std::string &filename) {
160 std::string filepath = path;
161 if (filepath.length()) {
James Kuszmaul8e62b022022-03-22 09:33:25 -0700162 char &filepath_last_character = filepath.back();
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700163 if (filepath_last_character == kPathSeparatorWindows) {
164 filepath_last_character = kPathSeparator;
165 } else if (filepath_last_character != kPathSeparator) {
166 filepath += kPathSeparator;
167 }
168 }
169 filepath += filename;
170 // Ignore './' at the start of filepath.
171 if (filepath[0] == '.' && filepath[1] == kPathSeparator) {
172 filepath.erase(0, 2);
173 }
174 return filepath;
175}
176
177std::string PosixPath(const char *path) {
178 std::string p = path;
179 std::replace(p.begin(), p.end(), '\\', '/');
180 return p;
181}
James Kuszmaul8e62b022022-03-22 09:33:25 -0700182std::string PosixPath(const std::string &path) {
183 return PosixPath(path.c_str());
184}
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700185
186void EnsureDirExists(const std::string &filepath) {
187 auto parent = StripFileName(filepath);
188 if (parent.length()) EnsureDirExists(parent);
189 // clang-format off
190
191 #ifdef _WIN32
192 (void)_mkdir(filepath.c_str());
193 #else
194 mkdir(filepath.c_str(), S_IRWXU|S_IRGRP|S_IXGRP);
195 #endif
196 // clang-format on
197}
198
199std::string AbsolutePath(const std::string &filepath) {
200 // clang-format off
201
202 #ifdef FLATBUFFERS_NO_ABSOLUTE_PATH_RESOLUTION
203 return filepath;
204 #else
205 #ifdef _WIN32
206 char abs_path[MAX_PATH];
207 return GetFullPathNameA(filepath.c_str(), MAX_PATH, abs_path, nullptr)
208 #else
Austin Schuh272c6132020-11-14 16:37:52 -0800209 char *abs_path_temp = realpath(filepath.c_str(), nullptr);
210 bool success = abs_path_temp != nullptr;
211 std::string abs_path;
212 if(success) {
213 abs_path = abs_path_temp;
214 free(abs_path_temp);
215 }
216 return success
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700217 #endif
218 ? abs_path
219 : filepath;
220 #endif // FLATBUFFERS_NO_ABSOLUTE_PATH_RESOLUTION
221 // clang-format on
222}
223
James Kuszmaul8e62b022022-03-22 09:33:25 -0700224std::string RelativeToRootPath(const std::string &project,
225 const std::string &filepath) {
226 std::string absolute_project = PosixPath(AbsolutePath(project));
227 if (absolute_project.back() != '/') absolute_project += "/";
228 std::string absolute_filepath = PosixPath(AbsolutePath(filepath));
229
230 // Find the first character where they disagree.
231 // The previous directory is the lowest common ancestor;
232 const char *a = absolute_project.c_str();
233 const char *b = absolute_filepath.c_str();
234 size_t common_prefix_len = 0;
235 while (*a != '\0' && *b != '\0' && *a == *b) {
236 if (*a == '/') common_prefix_len = a - absolute_project.c_str();
237 a++;
238 b++;
239 }
240 // the number of ../ to prepend to b depends on the number of remaining
241 // directories in A.
242 const char *suffix = absolute_project.c_str() + common_prefix_len;
243 size_t num_up = 0;
244 while (*suffix != '\0')
245 if (*suffix++ == '/') num_up++;
246 num_up--; // last one is known to be '/'.
247 std::string result = "//";
248 for (size_t i = 0; i < num_up; i++) result += "../";
249 result += absolute_filepath.substr(common_prefix_len + 1);
250
251 return result;
252}
253
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700254// Locale-independent code.
255#if defined(FLATBUFFERS_LOCALE_INDEPENDENT) && \
256 (FLATBUFFERS_LOCALE_INDEPENDENT > 0)
257
258// clang-format off
259// Allocate locale instance at startup of application.
260ClassicLocale ClassicLocale::instance_;
261
262#ifdef _MSC_VER
263 ClassicLocale::ClassicLocale()
264 : locale_(_create_locale(LC_ALL, "C")) {}
265 ClassicLocale::~ClassicLocale() { _free_locale(locale_); }
266#else
267 ClassicLocale::ClassicLocale()
268 : locale_(newlocale(LC_ALL, "C", nullptr)) {}
269 ClassicLocale::~ClassicLocale() { freelocale(locale_); }
270#endif
271// clang-format on
272
273#endif // !FLATBUFFERS_LOCALE_INDEPENDENT
274
275std::string RemoveStringQuotes(const std::string &s) {
276 auto ch = *s.c_str();
James Kuszmaul8e62b022022-03-22 09:33:25 -0700277 return ((s.size() >= 2) && (ch == '\"' || ch == '\'') && (ch == s.back()))
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700278 ? s.substr(1, s.length() - 2)
279 : s;
280}
281
282bool SetGlobalTestLocale(const char *locale_name, std::string *_value) {
283 const auto the_locale = setlocale(LC_ALL, locale_name);
284 if (!the_locale) return false;
285 if (_value) *_value = std::string(the_locale);
286 return true;
287}
288
289bool ReadEnvironmentVariable(const char *var_name, std::string *_value) {
Austin Schuh272c6132020-11-14 16:37:52 -0800290#ifdef _MSC_VER
291 __pragma(warning(disable : 4996)); // _CRT_SECURE_NO_WARNINGS
292#endif
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700293 auto env_str = std::getenv(var_name);
294 if (!env_str) return false;
295 if (_value) *_value = std::string(env_str);
296 return true;
297}
298
299void SetupDefaultCRTReportMode() {
300 // clang-format off
301
302 #ifdef _MSC_VER
303 // By default, send all reports to STDOUT to prevent CI hangs.
304 // Enable assert report box [Abort|Retry|Ignore] if a debugger is present.
305 const int dbg_mode = (_CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG) |
306 (IsDebuggerPresent() ? _CRTDBG_MODE_WNDW : 0);
307 (void)dbg_mode; // release mode fix
308 // CrtDebug reports to _CRT_WARN channel.
309 _CrtSetReportMode(_CRT_WARN, dbg_mode);
310 _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDOUT);
311 // The assert from <assert.h> reports to _CRT_ERROR channel
312 _CrtSetReportMode(_CRT_ERROR, dbg_mode);
313 _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDOUT);
314 // Internal CRT assert channel?
315 _CrtSetReportMode(_CRT_ASSERT, dbg_mode);
316 _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDOUT);
317 #endif
318
319 // clang-format on
320}
321
James Kuszmaul8e62b022022-03-22 09:33:25 -0700322namespace {
323
324static std::string ToCamelCase(const std::string &input, bool first) {
325 std::string s;
326 for (size_t i = 0; i < input.length(); i++) {
327 if (!i && first)
328 s += CharToUpper(input[i]);
329 else if (input[i] == '_' && i + 1 < input.length())
330 s += CharToUpper(input[++i]);
331 else
332 s += input[i];
333 }
334 return s;
335}
336
337static std::string ToSnakeCase(const std::string &input, bool screaming) {
338 std::string s;
339 for (size_t i = 0; i < input.length(); i++) {
340 if (i == 0) {
341 s += screaming ? CharToUpper(input[i]) : CharToLower(input[i]);
342 } else if (input[i] == '_') {
343 s += '_';
344 } else if (!islower(input[i])) {
345 // Prevent duplicate underscores for Upper_Snake_Case strings
346 // and UPPERCASE strings.
347 if (islower(input[i - 1])) { s += '_'; }
348 s += screaming ? CharToUpper(input[i]) : CharToLower(input[i]);
349 } else {
350 s += screaming ? CharToUpper(input[i]) : input[i];
351 }
352 }
353 return s;
354}
355
356static std::string ToAll(const std::string &input,
357 std::function<char(const char)> transform) {
358 std::string s;
359 for (size_t i = 0; i < input.length(); i++) { s += transform(input[i]); }
360 return s;
361}
362
363static std::string CamelToSnake(const std::string &input) {
364 std::string s;
365 for (size_t i = 0; i < input.length(); i++) {
366 if (i == 0) {
367 s += CharToLower(input[i]);
368 } else if (input[i] == '_') {
369 s += '_';
370 } else if (!islower(input[i])) {
371 // Prevent duplicate underscores for Upper_Snake_Case strings
372 // and UPPERCASE strings.
373 if (islower(input[i - 1])) { s += '_'; }
374 s += CharToLower(input[i]);
375 } else {
376 s += input[i];
377 }
378 }
379 return s;
380}
381
382static std::string DasherToSnake(const std::string &input) {
383 std::string s;
384 for (size_t i = 0; i < input.length(); i++) {
385 if (input[i] == '-') {
386 s += "_";
387 } else {
388 s += input[i];
389 }
390 }
391 return s;
392}
393
394static std::string ToDasher(const std::string &input) {
395 std::string s;
396 char p = 0;
397 for (size_t i = 0; i < input.length(); i++) {
398 char const &c = input[i];
399 if (c == '_') {
400 if (i > 0 && p != kPathSeparator &&
401 // The following is a special case to ignore digits after a _. This is
402 // because ThisExample3 would be converted to this_example_3 in the
403 // CamelToSnake conversion, and then dasher would do this-example-3,
404 // but it expects this-example3.
405 !(i + 1 < input.length() && isdigit(input[i + 1])))
406 s += "-";
407 } else {
408 s += c;
409 }
410 p = c;
411 }
412 return s;
413}
414
415} // namespace
416
417std::string ConvertCase(const std::string &input, Case output_case,
418 Case input_case) {
419 if (output_case == Case::kKeep) return input;
420 // The output cases expect snake_case inputs, so if we don't have that input
421 // format, try to convert to snake_case.
422 switch (input_case) {
423 case Case::kLowerCamel:
424 case Case::kUpperCamel:
425 return ConvertCase(CamelToSnake(input), output_case);
426 case Case::kDasher: return ConvertCase(DasherToSnake(input), output_case);
427 case Case::kKeep: printf("WARNING: Converting from kKeep case.\n"); break;
428 default:
429 case Case::kSnake:
430 case Case::kScreamingSnake:
431 case Case::kAllLower:
432 case Case::kAllUpper: break;
433 }
434
435 switch (output_case) {
436 case Case::kUpperCamel: return ToCamelCase(input, true);
437 case Case::kLowerCamel: return ToCamelCase(input, false);
438 case Case::kSnake: return input;
439 case Case::kScreamingSnake: return ToSnakeCase(input, true);
440 case Case::kAllUpper: return ToAll(input, CharToUpper);
441 case Case::kAllLower: return ToAll(input, CharToLower);
442 case Case::kDasher: return ToDasher(input);
443 default:
444 case Case::kUnknown: return input;
445 }
446}
447
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700448} // namespace flatbuffers