Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / tools / gn / setup.cc
1 // 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/setup.h"
6
7 #include <stdlib.h>
8
9 #include <algorithm>
10 #include <sstream>
11
12 #include "base/bind.h"
13 #include "base/command_line.h"
14 #include "base/file_util.h"
15 #include "base/files/file_path.h"
16 #include "base/process/launch.h"
17 #include "base/strings/string_split.h"
18 #include "base/strings/string_util.h"
19 #include "base/strings/utf_string_conversions.h"
20 #include "build/build_config.h"
21 #include "tools/gn/filesystem_utils.h"
22 #include "tools/gn/header_checker.h"
23 #include "tools/gn/input_file.h"
24 #include "tools/gn/parse_tree.h"
25 #include "tools/gn/parser.h"
26 #include "tools/gn/source_dir.h"
27 #include "tools/gn/source_file.h"
28 #include "tools/gn/standard_out.h"
29 #include "tools/gn/tokenizer.h"
30 #include "tools/gn/trace.h"
31 #include "tools/gn/value.h"
32
33 #if defined(OS_WIN)
34 #include <windows.h>
35 #endif
36
37 extern const char kDotfile_Help[] =
38     ".gn file\n"
39     "\n"
40     "  When gn starts, it will search the current directory and parent\n"
41     "  directories for a file called \".gn\". This indicates the source root.\n"
42     "  You can override this detection by using the --root command-line\n"
43     "  argument\n"
44     "\n"
45     "  The .gn file in the source root will be executed. The syntax is the\n"
46     "  same as a buildfile, but with very limited build setup-specific\n"
47     "  meaning.\n"
48     "\n"
49     "  If you specify --root, by default GN will look for the file .gn in\n"
50     "  that directory. If you want to specify a different file, you can\n"
51     "  additionally pass --dotfile:\n"
52     "\n"
53     "    gn gen out/Debug --root=/home/build --dotfile=/home/my_gn_file.gn\n"
54     "\n"
55     "Variables\n"
56     "\n"
57     "  buildconfig [required]\n"
58     "      Label of the build config file. This file will be used to set up\n"
59     "      the build file execution environment for each toolchain.\n"
60     "\n"
61     "  root [optional]\n"
62     "      Label of the root build target. The GN build will start by loading\n"
63     "      the build file containing this target name. This defaults to\n"
64     "      \"//:\" which will cause the file //BUILD.gn to be loaded.\n"
65     "\n"
66     "  secondary_source [optional]\n"
67     "      Label of an alternate directory tree to find input files. When\n"
68     "      searching for a BUILD.gn file (or the build config file discussed\n"
69     "      above), the file fill first be looked for in the source root.\n"
70     "      If it's not found, the secondary source root will be checked\n"
71     "      (which would contain a parallel directory hierarchy).\n"
72     "\n"
73     "      This behavior is intended to be used when BUILD.gn files can't be\n"
74     "      checked in to certain source directories for whatever reason.\n"
75     "\n"
76     "      The secondary source root must be inside the main source tree.\n"
77     "\n"
78     "Example .gn file contents\n"
79     "\n"
80     "  buildconfig = \"//build/config/BUILDCONFIG.gn\"\n"
81     "\n"
82     "  root = \"//:root\"\n"
83     "\n"
84     "  secondary_source = \"//build/config/temporary_buildfiles/\"\n";
85
86 namespace {
87
88 // More logging.
89 const char kSwitchVerbose[] = "v";
90
91 // Set build args.
92 const char kSwitchArgs[] = "args";
93
94 // Set root dir.
95 const char kSwitchRoot[] = "root";
96
97 // Set dotfile name.
98 const char kSwitchDotfile[] = "dotfile";
99
100 // Enable timing.
101 const char kTimeSwitch[] = "time";
102
103 const char kTracelogSwitch[] = "tracelog";
104
105 const base::FilePath::CharType kGnFile[] = FILE_PATH_LITERAL(".gn");
106
107 base::FilePath FindDotFile(const base::FilePath& current_dir) {
108   base::FilePath try_this_file = current_dir.Append(kGnFile);
109   if (base::PathExists(try_this_file))
110     return try_this_file;
111
112   base::FilePath with_no_slash = current_dir.StripTrailingSeparators();
113   base::FilePath up_one_dir = with_no_slash.DirName();
114   if (up_one_dir == current_dir)
115     return base::FilePath();  // Got to the top.
116
117   return FindDotFile(up_one_dir);
118 }
119
120 // Called on any thread. Post the item to the builder on the main thread.
121 void ItemDefinedCallback(base::MessageLoop* main_loop,
122                          scoped_refptr<Builder> builder,
123                          scoped_ptr<Item> item) {
124   DCHECK(item);
125   main_loop->PostTask(FROM_HERE, base::Bind(&Builder::ItemDefined, builder,
126                                             base::Passed(&item)));
127 }
128
129 void DecrementWorkCount() {
130   g_scheduler->DecrementWorkCount();
131 }
132
133 }  // namespace
134
135 // CommonSetup -----------------------------------------------------------------
136
137 const char CommonSetup::kBuildArgFileName[] = "args.gn";
138
139 CommonSetup::CommonSetup()
140     : build_settings_(),
141       loader_(new LoaderImpl(&build_settings_)),
142       builder_(new Builder(loader_.get())),
143       root_build_file_("//BUILD.gn"),
144       check_for_bad_items_(true),
145       check_for_unused_overrides_(true),
146       check_public_headers_(false) {
147   loader_->set_complete_callback(base::Bind(&DecrementWorkCount));
148 }
149
150 CommonSetup::CommonSetup(const CommonSetup& other)
151     : build_settings_(other.build_settings_),
152       loader_(new LoaderImpl(&build_settings_)),
153       builder_(new Builder(loader_.get())),
154       root_build_file_(other.root_build_file_),
155       check_for_bad_items_(other.check_for_bad_items_),
156       check_for_unused_overrides_(other.check_for_unused_overrides_),
157       check_public_headers_(other.check_public_headers_) {
158   loader_->set_complete_callback(base::Bind(&DecrementWorkCount));
159 }
160
161 CommonSetup::~CommonSetup() {
162 }
163
164 void CommonSetup::RunPreMessageLoop() {
165   // Load the root build file.
166   loader_->Load(root_build_file_, Label());
167
168   // Will be decremented with the loader is drained.
169   g_scheduler->IncrementWorkCount();
170 }
171
172 bool CommonSetup::RunPostMessageLoop() {
173   Err err;
174   if (check_for_bad_items_) {
175     if (!builder_->CheckForBadItems(&err)) {
176       err.PrintToStdout();
177       return false;
178     }
179   }
180
181   if (check_for_unused_overrides_) {
182     if (!build_settings_.build_args().VerifyAllOverridesUsed(&err)) {
183       // TODO(brettw) implement a system of warnings. Until we have a better
184       // system, print the error but don't return failure.
185       err.PrintToStdout();
186       return true;
187     }
188   }
189
190   if (check_public_headers_) {
191     std::vector<const Target*> targets = builder_->GetAllResolvedTargets();
192     scoped_refptr<HeaderChecker> header_checker(
193         new HeaderChecker(&build_settings_, targets));
194
195     std::vector<Err> header_errors;
196     header_checker->Run(&header_errors);
197     for (size_t i = 0; i < header_errors.size(); i++) {
198       if (i > 0)
199         OutputString("___________________\n", DECORATION_YELLOW);
200       header_errors[i].PrintToStdout();
201     }
202     if (!header_errors.empty())
203       return false;
204   }
205
206   // Write out tracing and timing if requested.
207   const CommandLine* cmdline = CommandLine::ForCurrentProcess();
208   if (cmdline->HasSwitch(kTimeSwitch))
209     PrintLongHelp(SummarizeTraces());
210   if (cmdline->HasSwitch(kTracelogSwitch))
211     SaveTraces(cmdline->GetSwitchValuePath(kTracelogSwitch));
212
213   return true;
214 }
215
216 // Setup -----------------------------------------------------------------------
217
218 Setup::Setup()
219     : CommonSetup(),
220       empty_settings_(&empty_build_settings_, std::string()),
221       dotfile_scope_(&empty_settings_),
222       fill_arguments_(true) {
223   empty_settings_.set_toolchain_label(Label());
224   build_settings_.set_item_defined_callback(
225       base::Bind(&ItemDefinedCallback, scheduler_.main_loop(), builder_));
226
227   // The scheduler's main loop wasn't created when the Loader was created, so
228   // we need to set it now.
229   loader_->set_main_loop(scheduler_.main_loop());
230 }
231
232 Setup::~Setup() {
233 }
234
235 bool Setup::DoSetup(const std::string& build_dir) {
236   CommandLine* cmdline = CommandLine::ForCurrentProcess();
237
238   scheduler_.set_verbose_logging(cmdline->HasSwitch(kSwitchVerbose));
239   if (cmdline->HasSwitch(kTimeSwitch) ||
240       cmdline->HasSwitch(kTracelogSwitch))
241     EnableTracing();
242
243   ScopedTrace setup_trace(TraceItem::TRACE_SETUP, "DoSetup");
244
245   if (!FillSourceDir(*cmdline))
246     return false;
247   if (!RunConfigFile())
248     return false;
249   if (!FillOtherConfig(*cmdline))
250     return false;
251   if (!FillBuildDir(build_dir))  // Must be after FillSourceDir to resolve.
252     return false;
253   if (fill_arguments_) {
254     if (!FillArguments(*cmdline))
255       return false;
256   }
257   FillPythonPath();
258
259   return true;
260 }
261
262 bool Setup::Run() {
263   RunPreMessageLoop();
264   if (!scheduler_.Run())
265     return false;
266   return RunPostMessageLoop();
267 }
268
269 Scheduler* Setup::GetScheduler() {
270   return &scheduler_;
271 }
272
273 SourceFile Setup::GetBuildArgFile() const {
274   return SourceFile(build_settings_.build_dir().value() + kBuildArgFileName);
275 }
276
277 bool Setup::FillArguments(const CommandLine& cmdline) {
278   // Add a dependency on the build arguments file. If this changes, we want
279   // to re-generated the build.
280   g_scheduler->AddGenDependency(build_settings_.GetFullPath(GetBuildArgFile()));
281
282   // Use the args on the command line if specified, and save them. Do this even
283   // if the list is empty (this means clear any defaults).
284   if (cmdline.HasSwitch(kSwitchArgs)) {
285     if (!FillArgsFromCommandLine(cmdline.GetSwitchValueASCII(kSwitchArgs)))
286       return false;
287     SaveArgsToFile();
288     return true;
289   }
290
291   // No command line args given, use the arguments from the build dir (if any).
292   return FillArgsFromFile();
293 }
294
295 bool Setup::FillArgsFromCommandLine(const std::string& args) {
296   args_input_file_.reset(new InputFile(SourceFile()));
297   args_input_file_->SetContents(args);
298   args_input_file_->set_friendly_name("the command-line \"--args\"");
299   return FillArgsFromArgsInputFile();
300 }
301
302 bool Setup::FillArgsFromFile() {
303   ScopedTrace setup_trace(TraceItem::TRACE_SETUP, "Load args file");
304
305   SourceFile build_arg_source_file = GetBuildArgFile();
306   base::FilePath build_arg_file =
307       build_settings_.GetFullPath(build_arg_source_file);
308
309   std::string contents;
310   if (!base::ReadFileToString(build_arg_file, &contents))
311     return true;  // File doesn't exist, continue with default args.
312   if (contents.empty())
313     return true;  // Empty file, do nothing.
314
315   args_input_file_.reset(new InputFile(build_arg_source_file));
316   args_input_file_->SetContents(contents);
317   args_input_file_->set_friendly_name(
318       "build arg file (use \"gn args <out_dir>\" to edit)");
319
320   setup_trace.Done();  // Only want to count the load as part of the trace.
321   return FillArgsFromArgsInputFile();
322 }
323
324 bool Setup::FillArgsFromArgsInputFile() {
325   ScopedTrace setup_trace(TraceItem::TRACE_SETUP, "Parse args");
326
327   Err err;
328   args_tokens_ = Tokenizer::Tokenize(args_input_file_.get(), &err);
329   if (err.has_error()) {
330     err.PrintToStdout();
331     return false;
332   }
333
334   args_root_ = Parser::Parse(args_tokens_, &err);
335   if (err.has_error()) {
336     err.PrintToStdout();
337     return false;
338   }
339
340   Scope arg_scope(&empty_settings_);
341   args_root_->AsBlock()->ExecuteBlockInScope(&arg_scope, &err);
342   if (err.has_error()) {
343     err.PrintToStdout();
344     return false;
345   }
346
347   // Save the result of the command args.
348   Scope::KeyValueMap overrides;
349   arg_scope.GetCurrentScopeValues(&overrides);
350   build_settings_.build_args().AddArgOverrides(overrides);
351   return true;
352 }
353
354 bool Setup::SaveArgsToFile() {
355   ScopedTrace setup_trace(TraceItem::TRACE_SETUP, "Save args file");
356
357   Scope::KeyValueMap args = build_settings_.build_args().GetAllOverrides();
358
359   std::ostringstream stream;
360   for (Scope::KeyValueMap::const_iterator i = args.begin();
361        i != args.end(); ++i) {
362     stream << i->first.as_string() << " = " << i->second.ToString(true);
363     stream << std::endl;
364   }
365
366   // For the first run, the build output dir might not be created yet, so do
367   // that so we can write a file into it. Ignore errors, we'll catch the error
368   // when we try to write a file to it below.
369   base::FilePath build_arg_file =
370       build_settings_.GetFullPath(GetBuildArgFile());
371   base::CreateDirectory(build_arg_file.DirName());
372
373   std::string contents = stream.str();
374 #if defined(OS_WIN)
375   // Use Windows lineendings for this file since it will often open in
376   // Notepad which can't handle Unix ones.
377   ReplaceSubstringsAfterOffset(&contents, 0, "\n", "\r\n");
378 #endif
379   if (base::WriteFile(build_arg_file, contents.c_str(),
380       static_cast<int>(contents.size())) == -1) {
381     Err(Location(), "Args file could not be written.",
382       "The file is \"" + FilePathToUTF8(build_arg_file) +
383         "\"").PrintToStdout();
384     return false;
385   }
386
387   return true;
388 }
389
390 bool Setup::FillSourceDir(const CommandLine& cmdline) {
391   // Find the .gn file.
392   base::FilePath root_path;
393
394   // Prefer the command line args to the config file.
395   base::FilePath relative_root_path = cmdline.GetSwitchValuePath(kSwitchRoot);
396   if (!relative_root_path.empty()) {
397     root_path = base::MakeAbsoluteFilePath(relative_root_path);
398     if (root_path.empty()) {
399       Err(Location(), "Root source path not found.",
400           "The path \"" + FilePathToUTF8(relative_root_path) +
401           "\" doesn't exist.").PrintToStdout();
402       return false;
403     }
404
405     // When --root is specified, an alternate --dotfile can also be set.
406     // --dotfile should be a real file path and not a "//foo" source-relative
407     // path.
408     base::FilePath dot_file_path = cmdline.GetSwitchValuePath(kSwitchDotfile);
409     if (dot_file_path.empty()) {
410       dotfile_name_ = root_path.Append(kGnFile);
411     } else {
412       dotfile_name_ = base::MakeAbsoluteFilePath(dot_file_path);
413       if (dotfile_name_.empty()) {
414         Err(Location(), "Could not load dotfile.",
415             "The file \"" + FilePathToUTF8(dot_file_path) +
416             "\" cound't be loaded.").PrintToStdout();
417         return false;
418       }
419     }
420   } else {
421     // In the default case, look for a dotfile and that also tells us where the
422     // source root is.
423     base::FilePath cur_dir;
424     base::GetCurrentDirectory(&cur_dir);
425     dotfile_name_ = FindDotFile(cur_dir);
426     if (dotfile_name_.empty()) {
427       Err(Location(), "Can't find source root.",
428           "I could not find a \".gn\" file in the current directory or any "
429           "parent,\nand the --root command-line argument was not specified.")
430           .PrintToStdout();
431       return false;
432     }
433     root_path = dotfile_name_.DirName();
434   }
435
436   if (scheduler_.verbose_logging())
437     scheduler_.Log("Using source root", FilePathToUTF8(root_path));
438   build_settings_.SetRootPath(root_path);
439
440   return true;
441 }
442
443 bool Setup::FillBuildDir(const std::string& build_dir) {
444   SourceDir resolved =
445       SourceDirForCurrentDirectory(build_settings_.root_path()).
446           ResolveRelativeDir(build_dir);
447   if (resolved.is_null()) {
448     Err(Location(), "Couldn't resolve build directory.",
449         "The build directory supplied (\"" + build_dir + "\") was not valid.").
450         PrintToStdout();
451     return false;
452   }
453
454   if (scheduler_.verbose_logging())
455     scheduler_.Log("Using build dir", resolved.value());
456   build_settings_.SetBuildDir(resolved);
457   return true;
458 }
459
460 void Setup::FillPythonPath() {
461   // Trace this since it tends to be a bit slow on Windows.
462   ScopedTrace setup_trace(TraceItem::TRACE_SETUP, "Fill Python Path");
463 #if defined(OS_WIN)
464   // Find Python on the path so we can use the absolute path in the build.
465   const base::char16 kGetPython[] =
466       L"cmd.exe /c python -c \"import sys; print sys.executable\"";
467   std::string python_path;
468   if (base::GetAppOutput(kGetPython, &python_path)) {
469     base::TrimWhitespaceASCII(python_path, base::TRIM_ALL, &python_path);
470     if (scheduler_.verbose_logging())
471       scheduler_.Log("Found python", python_path);
472   } else {
473     scheduler_.Log("WARNING", "Could not find python on path, using "
474         "just \"python.exe\"");
475     python_path = "python.exe";
476   }
477   build_settings_.set_python_path(base::FilePath(base::UTF8ToUTF16(python_path))
478                                       .NormalizePathSeparatorsTo('/'));
479 #else
480   build_settings_.set_python_path(base::FilePath("python"));
481 #endif
482 }
483
484 bool Setup::RunConfigFile() {
485   if (scheduler_.verbose_logging())
486     scheduler_.Log("Got dotfile", FilePathToUTF8(dotfile_name_));
487
488   dotfile_input_file_.reset(new InputFile(SourceFile("//.gn")));
489   if (!dotfile_input_file_->Load(dotfile_name_)) {
490     Err(Location(), "Could not load dotfile.",
491         "The file \"" + FilePathToUTF8(dotfile_name_) + "\" cound't be loaded")
492         .PrintToStdout();
493     return false;
494   }
495
496   Err err;
497   dotfile_tokens_ = Tokenizer::Tokenize(dotfile_input_file_.get(), &err);
498   if (err.has_error()) {
499     err.PrintToStdout();
500     return false;
501   }
502
503   dotfile_root_ = Parser::Parse(dotfile_tokens_, &err);
504   if (err.has_error()) {
505     err.PrintToStdout();
506     return false;
507   }
508
509   dotfile_root_->AsBlock()->ExecuteBlockInScope(&dotfile_scope_, &err);
510   if (err.has_error()) {
511     err.PrintToStdout();
512     return false;
513   }
514
515   return true;
516 }
517
518 bool Setup::FillOtherConfig(const CommandLine& cmdline) {
519   Err err;
520
521   // Secondary source path, read from the config file if present.
522   // Read from the config file if present.
523   const Value* secondary_value =
524       dotfile_scope_.GetValue("secondary_source", true);
525   if (secondary_value) {
526     if (!secondary_value->VerifyTypeIs(Value::STRING, &err)) {
527       err.PrintToStdout();
528       return false;
529     }
530     build_settings_.SetSecondarySourcePath(
531         SourceDir(secondary_value->string_value()));
532   }
533
534   // Root build file.
535   const Value* root_value = dotfile_scope_.GetValue("root", true);
536   if (root_value) {
537     if (!root_value->VerifyTypeIs(Value::STRING, &err)) {
538       err.PrintToStdout();
539       return false;
540     }
541
542     Label root_target_label =
543         Label::Resolve(SourceDir("//"), Label(), *root_value, &err);
544     if (err.has_error()) {
545       err.PrintToStdout();
546       return false;
547     }
548
549     root_build_file_ = Loader::BuildFileForLabel(root_target_label);
550   }
551
552   // Build config file.
553   const Value* build_config_value =
554       dotfile_scope_.GetValue("buildconfig", true);
555   if (!build_config_value) {
556     Err(Location(), "No build config file.",
557         "Your .gn file (\"" + FilePathToUTF8(dotfile_name_) + "\")\n"
558         "didn't specify a \"buildconfig\" value.").PrintToStdout();
559     return false;
560   } else if (!build_config_value->VerifyTypeIs(Value::STRING, &err)) {
561     err.PrintToStdout();
562     return false;
563   }
564   build_settings_.set_build_config_file(
565       SourceFile(build_config_value->string_value()));
566
567   return true;
568 }
569
570 // DependentSetup --------------------------------------------------------------
571
572 DependentSetup::DependentSetup(Setup* derive_from)
573     : CommonSetup(*derive_from),
574       scheduler_(derive_from->GetScheduler()) {
575   build_settings_.set_item_defined_callback(
576       base::Bind(&ItemDefinedCallback, scheduler_->main_loop(), builder_));
577 }
578
579 DependentSetup::DependentSetup(DependentSetup* derive_from)
580     : CommonSetup(*derive_from),
581       scheduler_(derive_from->GetScheduler()) {
582   build_settings_.set_item_defined_callback(
583       base::Bind(&ItemDefinedCallback, scheduler_->main_loop(), builder_));
584 }
585
586 DependentSetup::~DependentSetup() {
587 }
588
589 Scheduler* DependentSetup::GetScheduler() {
590   return scheduler_;
591 }
592
593 void DependentSetup::RunPreMessageLoop() {
594   CommonSetup::RunPreMessageLoop();
595 }
596
597 bool DependentSetup::RunPostMessageLoop() {
598   return CommonSetup::RunPostMessageLoop();
599 }
600