blob: aabc23aa405980cb3224e3276883d5810ec7d1de [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
Austin Schuh2dd86a92022-09-14 21:19:23 -070020#include <cstring>
Austin Schuh272c6132020-11-14 16:37:52 -080021#if defined(__MINGW32__) || defined(__MINGW64__) || defined(__CYGWIN__) || \
22 defined(__QNXNTO__)
23# define _POSIX_C_SOURCE 200809L
24# define _XOPEN_SOURCE 700L
25#endif
26
Austin Schuh2dd86a92022-09-14 21:19:23 -070027#if defined(_WIN32) || defined(__MINGW32__) || defined(__MINGW64__) || defined(__CYGWIN__)
Austin Schuhe89fa2d2019-08-14 20:24:23 -070028# ifndef WIN32_LEAN_AND_MEAN
29# define WIN32_LEAN_AND_MEAN
30# endif
31# ifndef NOMINMAX
32# define NOMINMAX
33# endif
34# ifdef _MSC_VER
35# include <crtdbg.h>
36# endif
37# include <windows.h> // Must be included before <direct.h>
Austin Schuh2dd86a92022-09-14 21:19:23 -070038# ifndef __CYGWIN__
39# include <direct.h>
40# endif
Austin Schuhe89fa2d2019-08-14 20:24:23 -070041# include <winbase.h>
42# undef interface // This is also important because of reasons
Austin Schuhe89fa2d2019-08-14 20:24:23 -070043#endif
44// clang-format on
45
Austin Schuhe89fa2d2019-08-14 20:24:23 -070046#include "flatbuffers/util.h"
47
48#include <sys/stat.h>
James Kuszmaul8e62b022022-03-22 09:33:25 -070049
Austin Schuhe89fa2d2019-08-14 20:24:23 -070050#include <clocale>
Austin Schuh272c6132020-11-14 16:37:52 -080051#include <cstdlib>
Austin Schuhe89fa2d2019-08-14 20:24:23 -070052#include <fstream>
Austin Schuh2dd86a92022-09-14 21:19:23 -070053#include <functional>
Austin Schuhe89fa2d2019-08-14 20:24:23 -070054
James Kuszmaul8e62b022022-03-22 09:33:25 -070055#include "flatbuffers/base.h"
56
Austin Schuhe89fa2d2019-08-14 20:24:23 -070057namespace flatbuffers {
58
Austin Schuh2dd86a92022-09-14 21:19:23 -070059namespace {
60
61static bool FileExistsRaw(const char *name) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -070062 std::ifstream ifs(name);
63 return ifs.good();
64}
65
Austin Schuh2dd86a92022-09-14 21:19:23 -070066static bool LoadFileRaw(const char *name, bool binary, std::string *buf) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -070067 if (DirExists(name)) return false;
68 std::ifstream ifs(name, binary ? std::ifstream::binary : std::ifstream::in);
69 if (!ifs.is_open()) return false;
70 if (binary) {
71 // The fastest way to read a file into a string.
72 ifs.seekg(0, std::ios::end);
73 auto size = ifs.tellg();
74 (*buf).resize(static_cast<size_t>(size));
75 ifs.seekg(0, std::ios::beg);
76 ifs.read(&(*buf)[0], (*buf).size());
77 } else {
78 // This is slower, but works correctly on all platforms for text files.
79 std::ostringstream oss;
80 oss << ifs.rdbuf();
81 *buf = oss.str();
82 }
83 return !ifs.bad();
84}
85
Austin Schuh2dd86a92022-09-14 21:19:23 -070086LoadFileFunction g_load_file_function = LoadFileRaw;
87FileExistsFunction g_file_exists_function = FileExistsRaw;
88
89static std::string ToCamelCase(const std::string &input, bool first) {
90 std::string s;
91 for (size_t i = 0; i < input.length(); i++) {
92 if (!i && first)
93 s += CharToUpper(input[i]);
94 else if (input[i] == '_' && i + 1 < input.length())
95 s += CharToUpper(input[++i]);
96 else
97 s += input[i];
98 }
99 return s;
100}
101
102static std::string ToSnakeCase(const std::string &input, bool screaming) {
103 std::string s;
104 for (size_t i = 0; i < input.length(); i++) {
105 if (i == 0) {
106 s += screaming ? CharToUpper(input[i]) : CharToLower(input[i]);
107 } else if (input[i] == '_') {
108 s += '_';
109 } else if (!islower(input[i])) {
110 // Prevent duplicate underscores for Upper_Snake_Case strings
111 // and UPPERCASE strings.
James Kuszmaul3b15b0c2022-11-08 14:03:16 -0800112 if (islower(input[i - 1]) || (isdigit(input[i-1]) && !isdigit(input[i]))) { s += '_'; }
Austin Schuh2dd86a92022-09-14 21:19:23 -0700113 s += screaming ? CharToUpper(input[i]) : CharToLower(input[i]);
114 } else {
115 s += screaming ? CharToUpper(input[i]) : input[i];
116 }
117 }
118 return s;
119}
120
121std::string ToAll(const std::string &input,
122 std::function<char(const char)> transform) {
123 std::string s;
124 for (size_t i = 0; i < input.length(); i++) { s += transform(input[i]); }
125 return s;
126}
127
128std::string CamelToSnake(const std::string &input) {
129 std::string s;
130 for (size_t i = 0; i < input.length(); i++) {
131 if (i == 0) {
132 s += CharToLower(input[i]);
133 } else if (input[i] == '_') {
134 s += '_';
135 } else if (!islower(input[i])) {
136 // Prevent duplicate underscores for Upper_Snake_Case strings
137 // and UPPERCASE strings.
James Kuszmaul3b15b0c2022-11-08 14:03:16 -0800138 if (islower(input[i - 1]) || (isdigit(input[i-1]) && !isdigit(input[i]))) { s += '_'; }
Austin Schuh2dd86a92022-09-14 21:19:23 -0700139 s += CharToLower(input[i]);
140 } else {
141 s += input[i];
142 }
143 }
144 return s;
145}
146
147std::string DasherToSnake(const std::string &input) {
148 std::string s;
149 for (size_t i = 0; i < input.length(); i++) {
150 if (input[i] == '-') {
151 s += "_";
152 } else {
153 s += input[i];
154 }
155 }
156 return s;
157}
158
159std::string ToDasher(const std::string &input) {
160 std::string s;
161 char p = 0;
162 for (size_t i = 0; i < input.length(); i++) {
163 char const &c = input[i];
164 if (c == '_') {
165 if (i > 0 && p != kPathSeparator &&
166 // The following is a special case to ignore digits after a _. This is
167 // because ThisExample3 would be converted to this_example_3 in the
168 // CamelToSnake conversion, and then dasher would do this-example-3,
169 // but it expects this-example3.
170 !(i + 1 < input.length() && isdigit(input[i + 1])))
171 s += "-";
172 } else {
173 s += c;
174 }
175 p = c;
176 }
177 return s;
178}
179
180
181// Converts foo_bar_123baz_456 to foo_bar123_baz456
182std::string SnakeToSnake2(const std::string &s) {
183 if (s.length() <= 1) return s;
184 std::string result;
185 result.reserve(s.size());
186 for (size_t i = 0; i < s.length() - 1; i++) {
187 if (s[i] == '_' && isdigit(s[i + 1])) {
188 continue; // Move the `_` until after the digits.
189 }
190
191 result.push_back(s[i]);
192
193 if (isdigit(s[i]) && isalpha(s[i + 1]) && islower(s[i + 1])) {
194 result.push_back('_');
195 }
196 }
197 result.push_back(s.back());
198
199 return result;
200}
201
202} // namespace
203
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700204
205bool LoadFile(const char *name, bool binary, std::string *buf) {
206 FLATBUFFERS_ASSERT(g_load_file_function);
207 return g_load_file_function(name, binary, buf);
208}
209
210bool FileExists(const char *name) {
211 FLATBUFFERS_ASSERT(g_file_exists_function);
212 return g_file_exists_function(name);
213}
214
215bool DirExists(const char *name) {
216 // clang-format off
217
218 #ifdef _WIN32
219 #define flatbuffers_stat _stat
220 #define FLATBUFFERS_S_IFDIR _S_IFDIR
221 #else
222 #define flatbuffers_stat stat
223 #define FLATBUFFERS_S_IFDIR S_IFDIR
224 #endif
225 // clang-format on
226 struct flatbuffers_stat file_info;
227 if (flatbuffers_stat(name, &file_info) != 0) return false;
228 return (file_info.st_mode & FLATBUFFERS_S_IFDIR) != 0;
229}
230
231LoadFileFunction SetLoadFileFunction(LoadFileFunction load_file_function) {
232 LoadFileFunction previous_function = g_load_file_function;
233 g_load_file_function = load_file_function ? load_file_function : LoadFileRaw;
234 return previous_function;
235}
236
237FileExistsFunction SetFileExistsFunction(
238 FileExistsFunction file_exists_function) {
239 FileExistsFunction previous_function = g_file_exists_function;
240 g_file_exists_function =
241 file_exists_function ? file_exists_function : FileExistsRaw;
242 return previous_function;
243}
244
245bool SaveFile(const char *name, const char *buf, size_t len, bool binary) {
246 std::ofstream ofs(name, binary ? std::ofstream::binary : std::ofstream::out);
247 if (!ofs.is_open()) return false;
248 ofs.write(buf, len);
249 return !ofs.bad();
250}
251
252// We internally store paths in posix format ('/'). Paths supplied
253// by the user should go through PosixPath to ensure correct behavior
254// on Windows when paths are string-compared.
255
256static const char kPathSeparatorWindows = '\\';
257static const char *PathSeparatorSet = "\\/"; // Intentionally no ':'
258
259std::string StripExtension(const std::string &filepath) {
260 size_t i = filepath.find_last_of('.');
261 return i != std::string::npos ? filepath.substr(0, i) : filepath;
262}
263
264std::string GetExtension(const std::string &filepath) {
265 size_t i = filepath.find_last_of('.');
266 return i != std::string::npos ? filepath.substr(i + 1) : "";
267}
268
269std::string StripPath(const std::string &filepath) {
270 size_t i = filepath.find_last_of(PathSeparatorSet);
271 return i != std::string::npos ? filepath.substr(i + 1) : filepath;
272}
273
274std::string StripFileName(const std::string &filepath) {
275 size_t i = filepath.find_last_of(PathSeparatorSet);
276 return i != std::string::npos ? filepath.substr(0, i) : "";
277}
278
Austin Schuh2dd86a92022-09-14 21:19:23 -0700279std::string StripPrefix(const std::string &filepath,
280 const std::string &prefix_to_remove) {
281 if (!strncmp(filepath.c_str(), prefix_to_remove.c_str(),
282 prefix_to_remove.size())) {
283 return filepath.substr(prefix_to_remove.size());
284 }
285 return filepath;
286}
287
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700288std::string ConCatPathFileName(const std::string &path,
289 const std::string &filename) {
290 std::string filepath = path;
291 if (filepath.length()) {
James Kuszmaul8e62b022022-03-22 09:33:25 -0700292 char &filepath_last_character = filepath.back();
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700293 if (filepath_last_character == kPathSeparatorWindows) {
294 filepath_last_character = kPathSeparator;
295 } else if (filepath_last_character != kPathSeparator) {
296 filepath += kPathSeparator;
297 }
298 }
299 filepath += filename;
300 // Ignore './' at the start of filepath.
301 if (filepath[0] == '.' && filepath[1] == kPathSeparator) {
302 filepath.erase(0, 2);
303 }
304 return filepath;
305}
306
307std::string PosixPath(const char *path) {
308 std::string p = path;
309 std::replace(p.begin(), p.end(), '\\', '/');
310 return p;
311}
James Kuszmaul8e62b022022-03-22 09:33:25 -0700312std::string PosixPath(const std::string &path) {
313 return PosixPath(path.c_str());
314}
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700315
316void EnsureDirExists(const std::string &filepath) {
317 auto parent = StripFileName(filepath);
318 if (parent.length()) EnsureDirExists(parent);
319 // clang-format off
320
321 #ifdef _WIN32
322 (void)_mkdir(filepath.c_str());
323 #else
324 mkdir(filepath.c_str(), S_IRWXU|S_IRGRP|S_IXGRP);
325 #endif
326 // clang-format on
327}
328
329std::string AbsolutePath(const std::string &filepath) {
330 // clang-format off
331
332 #ifdef FLATBUFFERS_NO_ABSOLUTE_PATH_RESOLUTION
333 return filepath;
334 #else
Austin Schuh2dd86a92022-09-14 21:19:23 -0700335 #if defined(_WIN32) || defined(__MINGW32__) || defined(__MINGW64__) || defined(__CYGWIN__)
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700336 char abs_path[MAX_PATH];
337 return GetFullPathNameA(filepath.c_str(), MAX_PATH, abs_path, nullptr)
338 #else
Austin Schuh272c6132020-11-14 16:37:52 -0800339 char *abs_path_temp = realpath(filepath.c_str(), nullptr);
340 bool success = abs_path_temp != nullptr;
341 std::string abs_path;
342 if(success) {
343 abs_path = abs_path_temp;
344 free(abs_path_temp);
345 }
346 return success
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700347 #endif
348 ? abs_path
349 : filepath;
350 #endif // FLATBUFFERS_NO_ABSOLUTE_PATH_RESOLUTION
351 // clang-format on
352}
353
James Kuszmaul8e62b022022-03-22 09:33:25 -0700354std::string RelativeToRootPath(const std::string &project,
355 const std::string &filepath) {
356 std::string absolute_project = PosixPath(AbsolutePath(project));
357 if (absolute_project.back() != '/') absolute_project += "/";
358 std::string absolute_filepath = PosixPath(AbsolutePath(filepath));
359
360 // Find the first character where they disagree.
361 // The previous directory is the lowest common ancestor;
362 const char *a = absolute_project.c_str();
363 const char *b = absolute_filepath.c_str();
364 size_t common_prefix_len = 0;
365 while (*a != '\0' && *b != '\0' && *a == *b) {
366 if (*a == '/') common_prefix_len = a - absolute_project.c_str();
367 a++;
368 b++;
369 }
370 // the number of ../ to prepend to b depends on the number of remaining
371 // directories in A.
372 const char *suffix = absolute_project.c_str() + common_prefix_len;
373 size_t num_up = 0;
374 while (*suffix != '\0')
375 if (*suffix++ == '/') num_up++;
376 num_up--; // last one is known to be '/'.
377 std::string result = "//";
378 for (size_t i = 0; i < num_up; i++) result += "../";
379 result += absolute_filepath.substr(common_prefix_len + 1);
380
381 return result;
382}
383
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700384// Locale-independent code.
385#if defined(FLATBUFFERS_LOCALE_INDEPENDENT) && \
386 (FLATBUFFERS_LOCALE_INDEPENDENT > 0)
387
388// clang-format off
389// Allocate locale instance at startup of application.
390ClassicLocale ClassicLocale::instance_;
391
392#ifdef _MSC_VER
393 ClassicLocale::ClassicLocale()
394 : locale_(_create_locale(LC_ALL, "C")) {}
395 ClassicLocale::~ClassicLocale() { _free_locale(locale_); }
396#else
397 ClassicLocale::ClassicLocale()
398 : locale_(newlocale(LC_ALL, "C", nullptr)) {}
399 ClassicLocale::~ClassicLocale() { freelocale(locale_); }
400#endif
401// clang-format on
402
403#endif // !FLATBUFFERS_LOCALE_INDEPENDENT
404
405std::string RemoveStringQuotes(const std::string &s) {
406 auto ch = *s.c_str();
James Kuszmaul8e62b022022-03-22 09:33:25 -0700407 return ((s.size() >= 2) && (ch == '\"' || ch == '\'') && (ch == s.back()))
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700408 ? s.substr(1, s.length() - 2)
409 : s;
410}
411
412bool SetGlobalTestLocale(const char *locale_name, std::string *_value) {
413 const auto the_locale = setlocale(LC_ALL, locale_name);
414 if (!the_locale) return false;
415 if (_value) *_value = std::string(the_locale);
416 return true;
417}
418
419bool ReadEnvironmentVariable(const char *var_name, std::string *_value) {
Austin Schuh272c6132020-11-14 16:37:52 -0800420#ifdef _MSC_VER
421 __pragma(warning(disable : 4996)); // _CRT_SECURE_NO_WARNINGS
422#endif
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700423 auto env_str = std::getenv(var_name);
424 if (!env_str) return false;
425 if (_value) *_value = std::string(env_str);
426 return true;
427}
428
James Kuszmaul8e62b022022-03-22 09:33:25 -0700429std::string ConvertCase(const std::string &input, Case output_case,
430 Case input_case) {
431 if (output_case == Case::kKeep) return input;
432 // The output cases expect snake_case inputs, so if we don't have that input
433 // format, try to convert to snake_case.
434 switch (input_case) {
435 case Case::kLowerCamel:
436 case Case::kUpperCamel:
437 return ConvertCase(CamelToSnake(input), output_case);
438 case Case::kDasher: return ConvertCase(DasherToSnake(input), output_case);
439 case Case::kKeep: printf("WARNING: Converting from kKeep case.\n"); break;
440 default:
441 case Case::kSnake:
442 case Case::kScreamingSnake:
443 case Case::kAllLower:
444 case Case::kAllUpper: break;
445 }
446
447 switch (output_case) {
448 case Case::kUpperCamel: return ToCamelCase(input, true);
449 case Case::kLowerCamel: return ToCamelCase(input, false);
450 case Case::kSnake: return input;
451 case Case::kScreamingSnake: return ToSnakeCase(input, true);
452 case Case::kAllUpper: return ToAll(input, CharToUpper);
453 case Case::kAllLower: return ToAll(input, CharToLower);
454 case Case::kDasher: return ToDasher(input);
Austin Schuh2dd86a92022-09-14 21:19:23 -0700455 case Case::kSnake2: return SnakeToSnake2(input);
James Kuszmaul8e62b022022-03-22 09:33:25 -0700456 default:
457 case Case::kUnknown: return input;
458 }
459}
460
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700461} // namespace flatbuffers