blob: 44fa0eb505f523cbd6ea039f737d874326c1bd28 [file] [log] [blame]
[email protected]96ea63d2013-07-30 10:17:071// Copyright (c) 2013 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#include "tools/gn/filesystem_utils.h"
6
[email protected]ea3690c2013-09-23 17:59:227#include <algorithm>
8
thestig1ecdcf42014-09-12 05:09:149#include "base/files/file_util.h"
[email protected]96ea63d2013-07-30 10:17:0710#include "base/logging.h"
[email protected]f6b314d12013-08-23 21:07:4711#include "base/strings/string_util.h"
[email protected]96ea63d2013-07-30 10:17:0712#include "base/strings/utf_string_conversions.h"
13#include "build/build_config.h"
14#include "tools/gn/location.h"
[email protected]05b94b432013-11-22 22:09:5515#include "tools/gn/settings.h"
[email protected]96ea63d2013-07-30 10:17:0716#include "tools/gn/source_dir.h"
17
18namespace {
19
20enum DotDisposition {
21 // The given dot is just part of a filename and is not special.
22 NOT_A_DIRECTORY,
23
24 // The given dot is the current directory.
25 DIRECTORY_CUR,
26
27 // The given dot is the first of a double dot that should take us up one.
28 DIRECTORY_UP
29};
30
31// When we find a dot, this function is called with the character following
32// that dot to see what it is. The return value indicates what type this dot is
33// (see above). This code handles the case where the dot is at the end of the
34// input.
35//
36// |*consumed_len| will contain the number of characters in the input that
37// express what we found.
38DotDisposition ClassifyAfterDot(const std::string& path,
39 size_t after_dot,
40 size_t* consumed_len) {
41 if (after_dot == path.size()) {
42 // Single dot at the end.
43 *consumed_len = 1;
44 return DIRECTORY_CUR;
45 }
[email protected]858ceda2014-02-27 23:26:4046 if (IsSlash(path[after_dot])) {
[email protected]96ea63d2013-07-30 10:17:0747 // Single dot followed by a slash.
48 *consumed_len = 2; // Consume the slash
49 return DIRECTORY_CUR;
50 }
51
52 if (path[after_dot] == '.') {
53 // Two dots.
54 if (after_dot + 1 == path.size()) {
55 // Double dot at the end.
56 *consumed_len = 2;
57 return DIRECTORY_UP;
58 }
[email protected]858ceda2014-02-27 23:26:4059 if (IsSlash(path[after_dot + 1])) {
[email protected]96ea63d2013-07-30 10:17:0760 // Double dot folowed by a slash.
61 *consumed_len = 3;
62 return DIRECTORY_UP;
63 }
64 }
65
66 // The dots are followed by something else, not a directory.
67 *consumed_len = 1;
68 return NOT_A_DIRECTORY;
69}
70
[email protected]f6b314d12013-08-23 21:07:4771#if defined(OS_WIN)
72inline char NormalizeWindowsPathChar(char c) {
73 if (c == '/')
74 return '\\';
75 return base::ToLowerASCII(c);
76}
77
78// Attempts to do a case and slash-insensitive comparison of two 8-bit Windows
79// paths.
80bool AreAbsoluteWindowsPathsEqual(const base::StringPiece& a,
81 const base::StringPiece& b) {
82 if (a.size() != b.size())
83 return false;
84
85 // For now, just do a case-insensitive ASCII comparison. We could convert to
brettw8a800902015-07-10 18:28:3386 // UTF-16 and use ICU if necessary.
[email protected]f6b314d12013-08-23 21:07:4787 for (size_t i = 0; i < a.size(); i++) {
88 if (NormalizeWindowsPathChar(a[i]) != NormalizeWindowsPathChar(b[i]))
89 return false;
90 }
91 return true;
92}
93
94bool DoesBeginWindowsDriveLetter(const base::StringPiece& path) {
95 if (path.size() < 3)
96 return false;
97
98 // Check colon first, this will generally fail fastest.
99 if (path[1] != ':')
100 return false;
101
[email protected]92df9852014-05-15 21:52:35102 // Check drive letter.
brettwb3413062015-06-24 00:39:02103 if (!base::IsAsciiAlpha(path[0]))
[email protected]f6b314d12013-08-23 21:07:47104 return false;
105
[email protected]858ceda2014-02-27 23:26:40106 if (!IsSlash(path[2]))
[email protected]f6b314d12013-08-23 21:07:47107 return false;
108 return true;
109}
110#endif
111
[email protected]a623db1872014-02-19 19:11:17112// A wrapper around FilePath.GetComponents that works the way we need. This is
113// not super efficient since it does some O(n) transformations on the path. If
114// this is called a lot, we might want to optimize.
115std::vector<base::FilePath::StringType> GetPathComponents(
116 const base::FilePath& path) {
117 std::vector<base::FilePath::StringType> result;
118 path.GetComponents(&result);
119
120 if (result.empty())
121 return result;
122
123 // GetComponents will preserve the "/" at the beginning, which confuses us.
124 // We don't expect to have relative paths in this function.
125 // Don't use IsSeparator since we always want to allow backslashes.
126 if (result[0] == FILE_PATH_LITERAL("/") ||
127 result[0] == FILE_PATH_LITERAL("\\"))
128 result.erase(result.begin());
129
130#if defined(OS_WIN)
131 // On Windows, GetComponents will give us [ "C:", "/", "foo" ], and we
132 // don't want the slash in there. This doesn't support input like "C:foo"
133 // which means foo relative to the current directory of the C drive but
134 // that's basically legacy DOS behavior we don't need to support.
pkasting5c4699c22014-10-17 18:17:15135 if (result.size() >= 2 && result[1].size() == 1 &&
136 IsSlash(static_cast<char>(result[1][0])))
[email protected]a623db1872014-02-19 19:11:17137 result.erase(result.begin() + 1);
138#endif
139
140 return result;
141}
142
143// Provides the equivalent of == for filesystem strings, trying to do
144// approximately the right thing with case.
145bool FilesystemStringsEqual(const base::FilePath::StringType& a,
146 const base::FilePath::StringType& b) {
147#if defined(OS_WIN)
148 // Assume case-insensitive filesystems on Windows. We use the CompareString
149 // function to do a case-insensitive comparison based on the current locale
150 // (we don't want GN to depend on ICU which is large and requires data
151 // files). This isn't perfect, but getting this perfectly right is very
152 // difficult and requires I/O, and this comparison should cover 99.9999% of
153 // all cases.
154 //
155 // Note: The documentation for CompareString says it runs fastest on
156 // null-terminated strings with -1 passed for the length, so we do that here.
157 // There should not be embedded nulls in filesystem strings.
158 return ::CompareString(LOCALE_USER_DEFAULT, LINGUISTIC_IGNORECASE,
159 a.c_str(), -1, b.c_str(), -1) == CSTR_EQUAL;
160#else
161 // Assume case-sensitive filesystems on non-Windows.
162 return a == b;
163#endif
164}
165
brettw8d6e145e2016-08-02 21:38:59166// Helper function for computing subdirectories in the build directory
167// corresponding to absolute paths. This will try to resolve the absolute
168// path as a source-relative path first, and otherwise it creates a
169// special subdirectory for absolute paths to keep them from colliding with
170// other generated sources and outputs.
171void AppendFixedAbsolutePathSuffix(const BuildSettings* build_settings,
172 const SourceDir& source_dir,
173 OutputFile* result) {
174 const std::string& build_dir = build_settings->build_dir().value();
175
176 if (base::StartsWith(source_dir.value(), build_dir,
177 base::CompareCase::SENSITIVE)) {
178 size_t build_dir_size = build_dir.size();
179 result->value().append(&source_dir.value()[build_dir_size],
180 source_dir.value().size() - build_dir_size);
181 } else {
182 result->value().append("ABS_PATH");
183#if defined(OS_WIN)
184 // Windows absolute path contains ':' after drive letter. Remove it to
185 // avoid inserting ':' in the middle of path (eg. "ABS_PATH/C:/").
186 std::string src_dir_value = source_dir.value();
187 const auto colon_pos = src_dir_value.find(':');
188 if (colon_pos != std::string::npos)
189 src_dir_value.erase(src_dir_value.begin() + colon_pos);
190#else
191 const std::string& src_dir_value = source_dir.value();
192#endif
193 result->value().append(src_dir_value);
194 }
195}
196
[email protected]f6b314d12013-08-23 21:07:47197} // namespace
[email protected]96ea63d2013-07-30 10:17:07198
[email protected]1bcf0012013-09-19 21:13:32199std::string FilePathToUTF8(const base::FilePath::StringType& str) {
[email protected]96ea63d2013-07-30 10:17:07200#if defined(OS_WIN)
[email protected]6c3bf032013-12-25 19:37:03201 return base::WideToUTF8(str);
[email protected]96ea63d2013-07-30 10:17:07202#else
[email protected]1bcf0012013-09-19 21:13:32203 return str;
[email protected]96ea63d2013-07-30 10:17:07204#endif
205}
206
207base::FilePath UTF8ToFilePath(const base::StringPiece& sp) {
208#if defined(OS_WIN)
[email protected]6c3bf032013-12-25 19:37:03209 return base::FilePath(base::UTF8ToWide(sp));
[email protected]96ea63d2013-07-30 10:17:07210#else
211 return base::FilePath(sp.as_string());
212#endif
213}
214
215size_t FindExtensionOffset(const std::string& path) {
216 for (int i = static_cast<int>(path.size()); i >= 0; i--) {
[email protected]858ceda2014-02-27 23:26:40217 if (IsSlash(path[i]))
[email protected]96ea63d2013-07-30 10:17:07218 break;
219 if (path[i] == '.')
220 return i + 1;
221 }
222 return std::string::npos;
223}
224
225base::StringPiece FindExtension(const std::string* path) {
226 size_t extension_offset = FindExtensionOffset(*path);
227 if (extension_offset == std::string::npos)
228 return base::StringPiece();
229 return base::StringPiece(&path->data()[extension_offset],
230 path->size() - extension_offset);
231}
232
233size_t FindFilenameOffset(const std::string& path) {
234 for (int i = static_cast<int>(path.size()) - 1; i >= 0; i--) {
[email protected]858ceda2014-02-27 23:26:40235 if (IsSlash(path[i]))
[email protected]96ea63d2013-07-30 10:17:07236 return i + 1;
237 }
238 return 0; // No filename found means everything was the filename.
239}
240
241base::StringPiece FindFilename(const std::string* path) {
242 size_t filename_offset = FindFilenameOffset(*path);
243 if (filename_offset == 0)
244 return base::StringPiece(*path); // Everything is the file name.
245 return base::StringPiece(&(*path).data()[filename_offset],
246 path->size() - filename_offset);
247}
248
249base::StringPiece FindFilenameNoExtension(const std::string* path) {
250 if (path->empty())
251 return base::StringPiece();
252 size_t filename_offset = FindFilenameOffset(*path);
253 size_t extension_offset = FindExtensionOffset(*path);
254
255 size_t name_len;
256 if (extension_offset == std::string::npos)
257 name_len = path->size() - filename_offset;
258 else
259 name_len = extension_offset - filename_offset - 1;
260
261 return base::StringPiece(&(*path).data()[filename_offset], name_len);
262}
263
264void RemoveFilename(std::string* path) {
265 path->resize(FindFilenameOffset(*path));
266}
267
268bool EndsWithSlash(const std::string& s) {
[email protected]858ceda2014-02-27 23:26:40269 return !s.empty() && IsSlash(s[s.size() - 1]);
[email protected]96ea63d2013-07-30 10:17:07270}
271
272base::StringPiece FindDir(const std::string* path) {
273 size_t filename_offset = FindFilenameOffset(*path);
274 if (filename_offset == 0u)
275 return base::StringPiece();
276 return base::StringPiece(path->data(), filename_offset);
277}
278
[email protected]a3372c72014-04-28 22:39:26279base::StringPiece FindLastDirComponent(const SourceDir& dir) {
280 const std::string& dir_string = dir.value();
281
282 if (dir_string.empty())
283 return base::StringPiece();
284 int cur = static_cast<int>(dir_string.size()) - 1;
285 DCHECK(dir_string[cur] == '/');
286 int end = cur;
287 cur--; // Skip before the last slash.
288
289 for (; cur >= 0; cur--) {
290 if (dir_string[cur] == '/')
291 return base::StringPiece(&dir_string[cur + 1], end - cur - 1);
292 }
293 return base::StringPiece(&dir_string[0], end);
294}
295
brettw56affab2015-06-04 22:01:03296bool IsStringInOutputDir(const SourceDir& output_dir, const std::string& str) {
297 // This check will be wrong for all proper prefixes "e.g. "/output" will
298 // match "/out" but we don't really care since this is just a sanity check.
299 const std::string& dir_str = output_dir.value();
300 return str.compare(0, dir_str.length(), dir_str) == 0;
301}
302
303bool EnsureStringIsInOutputDir(const SourceDir& output_dir,
[email protected]96ea63d2013-07-30 10:17:07304 const std::string& str,
[email protected]0dfcae72014-08-19 22:52:16305 const ParseNode* origin,
[email protected]96ea63d2013-07-30 10:17:07306 Err* err) {
brettw56affab2015-06-04 22:01:03307 if (IsStringInOutputDir(output_dir, str))
[email protected]f0bbcdc22014-07-11 17:13:35308 return true; // Output directory is hardcoded.
309
[email protected]0dfcae72014-08-19 22:52:16310 *err = Err(origin, "File is not inside output directory.",
[email protected]f0bbcdc22014-07-11 17:13:35311 "The given file should be in the output directory. Normally you would "
312 "specify\n\"$target_out_dir/foo\" or "
313 "\"$target_gen_dir/foo\". I interpreted this as\n\""
314 + str + "\".");
315 return false;
[email protected]96ea63d2013-07-30 10:17:07316}
317
[email protected]ac1128e2013-08-23 00:26:56318bool IsPathAbsolute(const base::StringPiece& path) {
319 if (path.empty())
320 return false;
321
[email protected]858ceda2014-02-27 23:26:40322 if (!IsSlash(path[0])) {
[email protected]ac1128e2013-08-23 00:26:56323#if defined(OS_WIN)
324 // Check for Windows system paths like "C:\foo".
[email protected]858ceda2014-02-27 23:26:40325 if (path.size() > 2 && path[1] == ':' && IsSlash(path[2]))
[email protected]ac1128e2013-08-23 00:26:56326 return true;
327#endif
328 return false; // Doesn't begin with a slash, is relative.
329 }
330
[email protected]858ceda2014-02-27 23:26:40331 // Double forward slash at the beginning means source-relative (we don't
332 // allow backslashes for denoting this).
[email protected]ac1128e2013-08-23 00:26:56333 if (path.size() > 1 && path[1] == '/')
[email protected]858ceda2014-02-27 23:26:40334 return false;
[email protected]ac1128e2013-08-23 00:26:56335
336 return true;
337}
338
dpranke6d8fdaa2016-08-30 03:37:40339bool IsPathSourceAbsolute(const base::StringPiece& path) {
340 return (path.size() >= 2 && path[0] == '/' && path[1] == '/');
341}
342
[email protected]ac1128e2013-08-23 00:26:56343bool MakeAbsolutePathRelativeIfPossible(const base::StringPiece& source_root,
344 const base::StringPiece& path,
345 std::string* dest) {
346 DCHECK(IsPathAbsolute(source_root));
347 DCHECK(IsPathAbsolute(path));
348
349 dest->clear();
350
351 if (source_root.size() > path.size())
352 return false; // The source root is longer: the path can never be inside.
353
354#if defined(OS_WIN)
[email protected]858ceda2014-02-27 23:26:40355 // Source root should be canonical on Windows. Note that the initial slash
356 // must be forward slash, but that the other ones can be either forward or
357 // backward.
[email protected]ac1128e2013-08-23 00:26:56358 DCHECK(source_root.size() > 2 && source_root[0] != '/' &&
[email protected]858ceda2014-02-27 23:26:40359 source_root[1] == ':' && IsSlash(source_root[2]));
[email protected]f6b314d12013-08-23 21:07:47360
361 size_t after_common_index = std::string::npos;
362 if (DoesBeginWindowsDriveLetter(path)) {
363 // Handle "C:\foo"
364 if (AreAbsoluteWindowsPathsEqual(source_root,
365 path.substr(0, source_root.size())))
366 after_common_index = source_root.size();
367 else
368 return false;
369 } else if (path[0] == '/' && source_root.size() <= path.size() - 1 &&
370 DoesBeginWindowsDriveLetter(path.substr(1))) {
371 // Handle "/C:/foo"
372 if (AreAbsoluteWindowsPathsEqual(source_root,
373 path.substr(1, source_root.size())))
374 after_common_index = source_root.size() + 1;
375 else
376 return false;
377 } else {
378 return false;
379 }
380
381 // If we get here, there's a match and after_common_index identifies the
382 // part after it.
383
384 // The base may or may not have a trailing slash, so skip all slashes from
385 // the path after our prefix match.
386 size_t first_after_slash = after_common_index;
[email protected]858ceda2014-02-27 23:26:40387 while (first_after_slash < path.size() && IsSlash(path[first_after_slash]))
[email protected]f6b314d12013-08-23 21:07:47388 first_after_slash++;
389
390 dest->assign("//"); // Result is source root relative.
391 dest->append(&path.data()[first_after_slash],
392 path.size() - first_after_slash);
393 return true;
394
[email protected]ac1128e2013-08-23 00:26:56395#else
[email protected]f6b314d12013-08-23 21:07:47396
[email protected]ac1128e2013-08-23 00:26:56397 // On non-Windows this is easy. Since we know both are absolute, just do a
398 // prefix check.
399 if (path.substr(0, source_root.size()) == source_root) {
[email protected]ac1128e2013-08-23 00:26:56400 // The base may or may not have a trailing slash, so skip all slashes from
401 // the path after our prefix match.
402 size_t first_after_slash = source_root.size();
[email protected]858ceda2014-02-27 23:26:40403 while (first_after_slash < path.size() && IsSlash(path[first_after_slash]))
[email protected]ac1128e2013-08-23 00:26:56404 first_after_slash++;
405
[email protected]f6b314d12013-08-23 21:07:47406 dest->assign("//"); // Result is source root relative.
[email protected]ac1128e2013-08-23 00:26:56407 dest->append(&path.data()[first_after_slash],
408 path.size() - first_after_slash);
409 return true;
410 }
[email protected]ac1128e2013-08-23 00:26:56411 return false;
[email protected]f6b314d12013-08-23 21:07:47412#endif
[email protected]ac1128e2013-08-23 00:26:56413}
414
slan910ac442015-12-04 01:40:29415void NormalizePath(std::string* path, const base::StringPiece& source_root) {
tfarina9b636af2014-12-23 00:52:07416 char* pathbuf = path->empty() ? nullptr : &(*path)[0];
[email protected]96ea63d2013-07-30 10:17:07417
418 // top_index is the first character we can modify in the path. Anything
419 // before this indicates where the path is relative to.
420 size_t top_index = 0;
421 bool is_relative = true;
422 if (!path->empty() && pathbuf[0] == '/') {
423 is_relative = false;
424
425 if (path->size() > 1 && pathbuf[1] == '/') {
426 // Two leading slashes, this is a path into the source dir.
427 top_index = 2;
428 } else {
429 // One leading slash, this is a system-absolute path.
430 top_index = 1;
431 }
432 }
433
434 size_t dest_i = top_index;
435 for (size_t src_i = top_index; src_i < path->size(); /* nothing */) {
436 if (pathbuf[src_i] == '.') {
[email protected]858ceda2014-02-27 23:26:40437 if (src_i == 0 || IsSlash(pathbuf[src_i - 1])) {
[email protected]96ea63d2013-07-30 10:17:07438 // Slash followed by a dot, see if it's something special.
439 size_t consumed_len;
440 switch (ClassifyAfterDot(*path, src_i + 1, &consumed_len)) {
441 case NOT_A_DIRECTORY:
442 // Copy the dot to the output, it means nothing special.
443 pathbuf[dest_i++] = pathbuf[src_i++];
444 break;
445 case DIRECTORY_CUR:
446 // Current directory, just skip the input.
447 src_i += consumed_len;
448 break;
449 case DIRECTORY_UP:
450 // Back up over previous directory component. If we're already
451 // at the top, preserve the "..".
452 if (dest_i > top_index) {
453 // The previous char was a slash, remove it.
454 dest_i--;
455 }
456
457 if (dest_i == top_index) {
458 if (is_relative) {
459 // We're already at the beginning of a relative input, copy the
460 // ".." and continue. We need the trailing slash if there was
461 // one before (otherwise we're at the end of the input).
462 pathbuf[dest_i++] = '.';
463 pathbuf[dest_i++] = '.';
464 if (consumed_len == 3)
465 pathbuf[dest_i++] = '/';
466
467 // This also makes a new "root" that we can't delete by going
468 // up more levels. Otherwise "../.." would collapse to
469 // nothing.
470 top_index = dest_i;
slan910ac442015-12-04 01:40:29471 } else if (top_index == 2 && !source_root.empty()) {
472 // |path| was passed in as a source-absolute path. Prepend
473 // |source_root| to make |path| absolute. |source_root| must not
474 // end with a slash unless we are at root.
475 DCHECK(source_root.size() == 1u ||
476 !IsSlash(source_root[source_root.size() - 1u]));
477 size_t source_root_len = source_root.size();
478
479#if defined(OS_WIN)
480 // On Windows, if the source_root does not start with a slash,
481 // append one here for consistency.
482 if (!IsSlash(source_root[0])) {
483 path->insert(0, "/" + source_root.as_string());
484 source_root_len++;
485 } else {
486 path->insert(0, source_root.data(), source_root_len);
487 }
488
489 // Normalize slashes in source root portion.
490 for (size_t i = 0; i < source_root_len; ++i) {
491 if ((*path)[i] == '\\')
492 (*path)[i] = '/';
493 }
494#else
495 path->insert(0, source_root.data(), source_root_len);
496#endif
497
498 // |path| is now absolute, so |top_index| is 1. |dest_i| and
499 // |src_i| should be incremented to keep the same relative
500 // position. Comsume the leading "//" by decrementing |dest_i|.
501 top_index = 1;
502 pathbuf = &(*path)[0];
503 dest_i += source_root_len - 2;
504 src_i += source_root_len;
505
506 // Just find the previous slash or the beginning of input.
507 while (dest_i > 0 && !IsSlash(pathbuf[dest_i - 1]))
508 dest_i--;
[email protected]96ea63d2013-07-30 10:17:07509 }
slan910ac442015-12-04 01:40:29510 // Otherwise we're at the beginning of a system-absolute path, or
511 // a source-absolute path for which we don't know the absolute
512 // path. Don't allow ".." to go up another level, and just eat it.
[email protected]96ea63d2013-07-30 10:17:07513 } else {
514 // Just find the previous slash or the beginning of input.
[email protected]858ceda2014-02-27 23:26:40515 while (dest_i > 0 && !IsSlash(pathbuf[dest_i - 1]))
[email protected]96ea63d2013-07-30 10:17:07516 dest_i--;
517 }
518 src_i += consumed_len;
519 }
520 } else {
521 // Dot not preceeded by a slash, copy it literally.
522 pathbuf[dest_i++] = pathbuf[src_i++];
523 }
[email protected]858ceda2014-02-27 23:26:40524 } else if (IsSlash(pathbuf[src_i])) {
525 if (src_i > 0 && IsSlash(pathbuf[src_i - 1])) {
[email protected]96ea63d2013-07-30 10:17:07526 // Two slashes in a row, skip over it.
527 src_i++;
528 } else {
[email protected]858ceda2014-02-27 23:26:40529 // Just one slash, copy it, normalizing to foward slash.
530 pathbuf[dest_i] = '/';
531 dest_i++;
532 src_i++;
[email protected]96ea63d2013-07-30 10:17:07533 }
534 } else {
535 // Input nothing special, just copy it.
536 pathbuf[dest_i++] = pathbuf[src_i++];
537 }
538 }
539 path->resize(dest_i);
540}
541
542void ConvertPathToSystem(std::string* path) {
543#if defined(OS_WIN)
544 for (size_t i = 0; i < path->size(); i++) {
545 if ((*path)[i] == '/')
546 (*path)[i] = '\\';
547 }
548#endif
549}
550
zeuthen6f9c64562014-11-11 21:01:13551std::string MakeRelativePath(const std::string& input,
552 const std::string& dest) {
ohrn8808c5542015-02-10 10:18:38553#if defined(OS_WIN)
554 // Make sure that absolute |input| path starts with a slash if |dest| path
555 // does. Otherwise skipping common prefixes won't work properly. Ensure the
556 // same for |dest| path too.
557 if (IsPathAbsolute(input) && !IsSlash(input[0]) && IsSlash(dest[0])) {
558 std::string corrected_input(1, dest[0]);
559 corrected_input.append(input);
560 return MakeRelativePath(corrected_input, dest);
561 }
562 if (IsPathAbsolute(dest) && !IsSlash(dest[0]) && IsSlash(input[0])) {
563 std::string corrected_dest(1, input[0]);
564 corrected_dest.append(dest);
565 return MakeRelativePath(input, corrected_dest);
566 }
tmoniuszko01a402c2016-03-22 08:30:14567
568 // Make sure that both absolute paths use the same drive letter case.
569 if (IsPathAbsolute(input) && IsPathAbsolute(dest) && input.size() > 1 &&
570 dest.size() > 1) {
571 int letter_pos = base::IsAsciiAlpha(input[0]) ? 0 : 1;
572 if (input[letter_pos] != dest[letter_pos] &&
573 base::ToUpperASCII(input[letter_pos]) ==
574 base::ToUpperASCII(dest[letter_pos])) {
575 std::string corrected_input = input;
576 corrected_input[letter_pos] = dest[letter_pos];
577 return MakeRelativePath(corrected_input, dest);
578 }
579 }
ohrn8808c5542015-02-10 10:18:38580#endif
581
zeuthen6f9c64562014-11-11 21:01:13582 std::string ret;
[email protected]ea3690c2013-09-23 17:59:22583
584 // Skip the common prefixes of the source and dest as long as they end in
585 // a [back]slash.
zeuthen6f9c64562014-11-11 21:01:13586 size_t common_prefix_len = 0;
[email protected]ea3690c2013-09-23 17:59:22587 size_t max_common_length = std::min(input.size(), dest.size());
588 for (size_t i = common_prefix_len; i < max_common_length; i++) {
[email protected]858ceda2014-02-27 23:26:40589 if (IsSlash(input[i]) && IsSlash(dest[i]))
[email protected]ea3690c2013-09-23 17:59:22590 common_prefix_len = i + 1;
591 else if (input[i] != dest[i])
592 break;
593 }
594
595 // Invert the dest dir starting from the end of the common prefix.
[email protected]ea3690c2013-09-23 17:59:22596 for (size_t i = common_prefix_len; i < dest.size(); i++) {
[email protected]858ceda2014-02-27 23:26:40597 if (IsSlash(dest[i]))
[email protected]ea3690c2013-09-23 17:59:22598 ret.append("../");
599 }
600
601 // Append any remaining unique input.
602 ret.append(&input[common_prefix_len], input.size() - common_prefix_len);
603
604 // If the result is still empty, the paths are the same.
605 if (ret.empty())
606 ret.push_back('.');
607
608 return ret;
609}
[email protected]05b94b432013-11-22 22:09:55610
zeuthen6f9c64562014-11-11 21:01:13611std::string RebasePath(const std::string& input,
612 const SourceDir& dest_dir,
613 const base::StringPiece& source_root) {
614 std::string ret;
615 DCHECK(source_root.empty() || !source_root.ends_with("/"));
616
617 bool input_is_source_path = (input.size() >= 2 &&
618 input[0] == '/' && input[1] == '/');
619
620 if (!source_root.empty() &&
621 (!input_is_source_path || !dest_dir.is_source_absolute())) {
622 std::string input_full;
623 std::string dest_full;
624 if (input_is_source_path) {
625 source_root.AppendToString(&input_full);
626 input_full.push_back('/');
627 input_full.append(input, 2, std::string::npos);
628 } else {
629 input_full.append(input);
630 }
631 if (dest_dir.is_source_absolute()) {
632 source_root.AppendToString(&dest_full);
633 dest_full.push_back('/');
634 dest_full.append(dest_dir.value(), 2, std::string::npos);
635 } else {
636#if defined(OS_WIN)
637 // On Windows, SourceDir system-absolute paths start
638 // with /, e.g. "/C:/foo/bar".
639 const std::string& value = dest_dir.value();
640 if (value.size() > 2 && value[2] == ':')
641 dest_full.append(dest_dir.value().substr(1));
642 else
643 dest_full.append(dest_dir.value());
644#else
645 dest_full.append(dest_dir.value());
646#endif
647 }
648 bool remove_slash = false;
649 if (!EndsWithSlash(input_full)) {
650 input_full.push_back('/');
651 remove_slash = true;
652 }
653 ret = MakeRelativePath(input_full, dest_full);
654 if (remove_slash && ret.size() > 1)
655 ret.resize(ret.size() - 1);
656 return ret;
657 }
658
659 ret = MakeRelativePath(input, dest_dir.value());
660 return ret;
661}
662
[email protected]05b94b432013-11-22 22:09:55663std::string DirectoryWithNoLastSlash(const SourceDir& dir) {
664 std::string ret;
665
666 if (dir.value().empty()) {
667 // Just keep input the same.
668 } else if (dir.value() == "/") {
669 ret.assign("/.");
670 } else if (dir.value() == "//") {
671 ret.assign("//.");
672 } else {
673 ret.assign(dir.value());
674 ret.resize(ret.size() - 1);
675 }
676 return ret;
677}
678
[email protected]a623db1872014-02-19 19:11:17679SourceDir SourceDirForPath(const base::FilePath& source_root,
680 const base::FilePath& path) {
681 std::vector<base::FilePath::StringType> source_comp =
682 GetPathComponents(source_root);
683 std::vector<base::FilePath::StringType> path_comp =
684 GetPathComponents(path);
685
686 // See if path is inside the source root by looking for each of source root's
687 // components at the beginning of path.
688 bool is_inside_source;
scottmg865b9bb2014-12-02 10:48:29689 if (path_comp.size() < source_comp.size() || source_root.empty()) {
[email protected]a623db1872014-02-19 19:11:17690 // Too small to fit.
691 is_inside_source = false;
692 } else {
693 is_inside_source = true;
694 for (size_t i = 0; i < source_comp.size(); i++) {
695 if (!FilesystemStringsEqual(source_comp[i], path_comp[i])) {
696 is_inside_source = false;
697 break;
698 }
699 }
700 }
701
702 std::string result_str;
703 size_t initial_path_comp_to_use;
704 if (is_inside_source) {
705 // Construct a source-relative path beginning in // and skip all of the
706 // shared directories.
707 result_str = "//";
708 initial_path_comp_to_use = source_comp.size();
709 } else {
710 // Not inside source code, construct a system-absolute path.
711 result_str = "/";
712 initial_path_comp_to_use = 0;
713 }
714
715 for (size_t i = initial_path_comp_to_use; i < path_comp.size(); i++) {
716 result_str.append(FilePathToUTF8(path_comp[i]));
717 result_str.push_back('/');
718 }
719 return SourceDir(result_str);
720}
721
722SourceDir SourceDirForCurrentDirectory(const base::FilePath& source_root) {
723 base::FilePath cd;
[email protected]37b3c1992014-03-11 20:59:02724 base::GetCurrentDirectory(&cd);
[email protected]a623db1872014-02-19 19:11:17725 return SourceDirForPath(source_root, cd);
726}
727
[email protected]7380ca72014-05-13 16:56:20728std::string GetOutputSubdirName(const Label& toolchain_label, bool is_default) {
729 // The default toolchain has no subdir.
730 if (is_default)
731 return std::string();
732
733 // For now just assume the toolchain name is always a valid dir name. We may
734 // want to clean up the in the future.
735 return toolchain_label.name() + "/";
736}
737
tmoniuszko36deb392016-02-19 11:16:42738bool ContentsEqual(const base::FilePath& file_path, const std::string& data) {
739 // Compare file and stream sizes first. Quick and will save us some time if
740 // they are different sizes.
741 int64_t file_size;
742 if (!base::GetFileSize(file_path, &file_size) ||
743 static_cast<size_t>(file_size) != data.size()) {
744 return false;
745 }
746
747 std::string file_data;
748 file_data.resize(file_size);
749 if (!base::ReadFileToString(file_path, &file_data))
750 return false;
751
752 return file_data == data;
753}
754
755bool WriteFileIfChanged(const base::FilePath& file_path,
756 const std::string& data,
757 Err* err) {
758 if (ContentsEqual(file_path, data))
759 return true;
760
dpranke6d8fdaa2016-08-30 03:37:40761 return WriteFile(file_path, data, err);
762}
763
764bool WriteFile(const base::FilePath& file_path, const std::string& data,
765 Err* err) {
tmoniuszko36deb392016-02-19 11:16:42766 // Create the directory if necessary.
767 if (!base::CreateDirectory(file_path.DirName())) {
768 if (err) {
769 *err =
770 Err(Location(), "Unable to create directory.",
771 "I was using \"" + FilePathToUTF8(file_path.DirName()) + "\".");
772 }
773 return false;
774 }
775
776 int size = static_cast<int>(data.size());
777 bool write_success = false;
778
779#if defined(OS_WIN)
780 // On Windows, provide a custom implementation of base::WriteFile. Sometimes
781 // the base version fails, especially on the bots. The guess is that Windows
782 // Defender or other antivirus programs still have the file open (after
783 // checking for the read) when the write happens immediately after. This
784 // version opens with FILE_SHARE_READ (normally not what you want when
785 // replacing the entire contents of the file) which lets us continue even if
786 // another program has the file open for reading. See http://crbug.com/468437
787 base::win::ScopedHandle file(::CreateFile(file_path.value().c_str(),
788 GENERIC_WRITE, FILE_SHARE_READ,
789 NULL, CREATE_ALWAYS, 0, NULL));
790 if (file.IsValid()) {
791 DWORD written;
792 BOOL result = ::WriteFile(file.Get(), data.c_str(), size, &written, NULL);
793 if (result) {
794 if (static_cast<int>(written) == size) {
795 write_success = true;
796 } else {
797 // Didn't write all the bytes.
798 LOG(ERROR) << "wrote" << written << " bytes to "
799 << base::UTF16ToUTF8(file_path.value()) << " expected "
800 << size;
801 }
802 } else {
803 // WriteFile failed.
804 PLOG(ERROR) << "writing file " << base::UTF16ToUTF8(file_path.value())
805 << " failed";
806 }
807 } else {
808 PLOG(ERROR) << "CreateFile failed for path "
809 << base::UTF16ToUTF8(file_path.value());
810 }
811#else
812 write_success = base::WriteFile(file_path, data.c_str(), size) == size;
813#endif
814
815 if (!write_success && err) {
816 *err = Err(Location(), "Unable to write file.",
817 "I was writing \"" + FilePathToUTF8(file_path) + "\".");
818 }
819
820 return write_success;
821}
822
brettw8d6e145e2016-08-02 21:38:59823BuildDirContext::BuildDirContext(const Target* target)
824 : BuildDirContext(target->settings()) {
[email protected]05b94b432013-11-22 22:09:55825}
826
brettw8d6e145e2016-08-02 21:38:59827BuildDirContext::BuildDirContext(const Settings* settings)
828 : BuildDirContext(settings->build_settings(),
829 settings->toolchain_label(),
830 settings->is_default()) {
[email protected]7380ca72014-05-13 16:56:20831}
832
brettw8d6e145e2016-08-02 21:38:59833BuildDirContext::BuildDirContext(const Scope* execution_scope)
834 : BuildDirContext(execution_scope->settings()) {
[email protected]0dfcae72014-08-19 22:52:16835}
[email protected]05b94b432013-11-22 22:09:55836
brettw8d6e145e2016-08-02 21:38:59837BuildDirContext::BuildDirContext(const Scope* execution_scope,
838 const Label& toolchain_label)
839 : BuildDirContext(execution_scope->settings()->build_settings(),
840 toolchain_label,
841 execution_scope->settings()->default_toolchain_label() ==
842 toolchain_label) {
843}
844
845BuildDirContext::BuildDirContext(const BuildSettings* in_build_settings,
846 const Label& in_toolchain_label,
847 bool in_is_default_toolchain)
848 : build_settings(in_build_settings),
849 toolchain_label(in_toolchain_label),
850 is_default_toolchain(in_is_default_toolchain) {
851}
852
853SourceDir GetBuildDirAsSourceDir(const BuildDirContext& context,
854 BuildDirType type) {
855 return GetBuildDirAsOutputFile(context, type).AsSourceDir(
856 context.build_settings);
857}
858
859OutputFile GetBuildDirAsOutputFile(const BuildDirContext& context,
860 BuildDirType type) {
861 OutputFile result(GetOutputSubdirName(context.toolchain_label,
862 context.is_default_toolchain));
863 DCHECK(result.value().empty() || result.value().back() == '/');
864
865 if (type == BuildDirType::GEN)
866 result.value().append("gen/");
867 else if (type == BuildDirType::OBJ)
868 result.value().append("obj/");
[email protected]0dfcae72014-08-19 22:52:16869 return result;
[email protected]05b94b432013-11-22 22:09:55870}
871
brettw8d6e145e2016-08-02 21:38:59872SourceDir GetSubBuildDirAsSourceDir(const BuildDirContext& context,
873 const SourceDir& source_dir,
874 BuildDirType type) {
875 return GetSubBuildDirAsOutputFile(context, source_dir, type)
876 .AsSourceDir(context.build_settings);
[email protected]7380ca72014-05-13 16:56:20877}
878
brettw8d6e145e2016-08-02 21:38:59879OutputFile GetSubBuildDirAsOutputFile(const BuildDirContext& context,
880 const SourceDir& source_dir,
881 BuildDirType type) {
882 DCHECK(type != BuildDirType::TOOLCHAIN_ROOT);
883 OutputFile result = GetBuildDirAsOutputFile(context, type);
[email protected]05b94b432013-11-22 22:09:55884
[email protected]e9bf4fc2014-06-19 16:50:52885 if (source_dir.is_source_absolute()) {
886 // The source dir is source-absolute, so we trim off the two leading
887 // slashes to append to the toolchain object directory.
[email protected]0dfcae72014-08-19 22:52:16888 result.value().append(&source_dir.value()[2],
889 source_dir.value().size() - 2);
zeuthen6f9c64562014-11-11 21:01:13890 } else {
brettw3dab5fe2015-06-29 23:00:15891 // System-absolute.
brettw8d6e145e2016-08-02 21:38:59892 AppendFixedAbsolutePathSuffix(context.build_settings, source_dir, &result);
[email protected]e9bf4fc2014-06-19 16:50:52893 }
[email protected]0dfcae72014-08-19 22:52:16894 return result;
[email protected]05b94b432013-11-22 22:09:55895}
896
brettw8d6e145e2016-08-02 21:38:59897SourceDir GetBuildDirForTargetAsSourceDir(const Target* target,
898 BuildDirType type) {
899 return GetSubBuildDirAsSourceDir(
900 BuildDirContext(target), target->label().dir(), type);
brettw6aeaa45a2015-08-25 23:43:27901}
902
brettw8d6e145e2016-08-02 21:38:59903OutputFile GetBuildDirForTargetAsOutputFile(const Target* target,
904 BuildDirType type) {
905 return GetSubBuildDirAsOutputFile(
906 BuildDirContext(target), target->label().dir(), type);
[email protected]0dfcae72014-08-19 22:52:16907}
[email protected]05b94b432013-11-22 22:09:55908
brettw8d6e145e2016-08-02 21:38:59909SourceDir GetScopeCurrentBuildDirAsSourceDir(const Scope* scope,
910 BuildDirType type) {
911 if (type == BuildDirType::TOOLCHAIN_ROOT)
912 return GetBuildDirAsSourceDir(BuildDirContext(scope), type);
913 return GetSubBuildDirAsSourceDir(
914 BuildDirContext(scope), scope->GetSourceDir(), type);
[email protected]05b94b432013-11-22 22:09:55915}