Change next_proto member type.
[chromium-blink-merge.git] / tools / gn / ninja_build_writer.cc
blob9a5e2d68ac45bb0be98b9b286a4e1a7d0a607b9a
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.
5 #include "tools/gn/ninja_build_writer.h"
7 #include <fstream>
8 #include <map>
10 #include "base/command_line.h"
11 #include "base/files/file_util.h"
12 #include "base/path_service.h"
13 #include "base/process/process_handle.h"
14 #include "base/strings/string_util.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "build/build_config.h"
17 #include "tools/gn/build_settings.h"
18 #include "tools/gn/err.h"
19 #include "tools/gn/escape.h"
20 #include "tools/gn/filesystem_utils.h"
21 #include "tools/gn/input_file_manager.h"
22 #include "tools/gn/ninja_utils.h"
23 #include "tools/gn/scheduler.h"
24 #include "tools/gn/switches.h"
25 #include "tools/gn/target.h"
26 #include "tools/gn/trace.h"
28 #if defined(OS_WIN)
29 #include <windows.h>
30 #endif
32 namespace {
34 std::string GetSelfInvocationCommand(const BuildSettings* build_settings) {
35 base::FilePath executable;
36 PathService::Get(base::FILE_EXE, &executable);
38 CommandLine cmdline(executable.NormalizePathSeparatorsTo('/'));
39 cmdline.AppendArg("gen");
40 cmdline.AppendArg(build_settings->build_dir().value());
41 cmdline.AppendSwitchPath(std::string("--") + switches::kRoot,
42 build_settings->root_path());
43 // Successful automatic invocations shouldn't print output.
44 cmdline.AppendSwitch(std::string("-") + switches::kQuiet);
46 EscapeOptions escape_shell;
47 escape_shell.mode = ESCAPE_NINJA_COMMAND;
48 #if defined(OS_WIN)
49 // The command line code quoting varies by platform. We have one string,
50 // possibly with spaces, that we want to quote. The Windows command line
51 // quotes again, so we don't want quoting. The Posix one doesn't.
52 escape_shell.inhibit_quoting = true;
53 #endif
55 const CommandLine& our_cmdline = *CommandLine::ForCurrentProcess();
56 const CommandLine::SwitchMap& switches = our_cmdline.GetSwitches();
57 for (CommandLine::SwitchMap::const_iterator i = switches.begin();
58 i != switches.end(); ++i) {
59 // Only write arguments we haven't already written. Always skip "args"
60 // since those will have been written to the file and will be used
61 // implicitly in the future. Keeping --args would mean changes to the file
62 // would be ignored.
63 if (i->first != switches::kQuiet &&
64 i->first != switches::kRoot &&
65 i->first != switches::kArgs) {
66 std::string escaped_value =
67 EscapeString(FilePathToUTF8(i->second), escape_shell, NULL);
68 cmdline.AppendSwitchASCII(i->first, escaped_value);
72 #if defined(OS_WIN)
73 return base::WideToUTF8(cmdline.GetCommandLineString());
74 #else
75 return cmdline.GetCommandLineString();
76 #endif
79 } // namespace
81 NinjaBuildWriter::NinjaBuildWriter(
82 const BuildSettings* build_settings,
83 const std::vector<const Settings*>& all_settings,
84 const Toolchain* default_toolchain,
85 const std::vector<const Target*>& default_toolchain_targets,
86 std::ostream& out,
87 std::ostream& dep_out)
88 : build_settings_(build_settings),
89 all_settings_(all_settings),
90 default_toolchain_(default_toolchain),
91 default_toolchain_targets_(default_toolchain_targets),
92 out_(out),
93 dep_out_(dep_out),
94 path_output_(build_settings->build_dir(),
95 build_settings->root_path_utf8(), ESCAPE_NINJA) {
98 NinjaBuildWriter::~NinjaBuildWriter() {
101 bool NinjaBuildWriter::Run(Err* err) {
102 WriteNinjaRules();
103 WriteLinkPool();
104 WriteSubninjas();
105 return WritePhonyAndAllRules(err);
108 // static
109 bool NinjaBuildWriter::RunAndWriteFile(
110 const BuildSettings* build_settings,
111 const std::vector<const Settings*>& all_settings,
112 const Toolchain* default_toolchain,
113 const std::vector<const Target*>& default_toolchain_targets,
114 Err* err) {
115 ScopedTrace trace(TraceItem::TRACE_FILE_WRITE, "build.ninja");
117 base::FilePath ninja_file(build_settings->GetFullPath(
118 SourceFile(build_settings->build_dir().value() + "build.ninja")));
119 base::CreateDirectory(ninja_file.DirName());
121 std::ofstream file;
122 file.open(FilePathToUTF8(ninja_file).c_str(),
123 std::ios_base::out | std::ios_base::binary);
124 if (file.fail()) {
125 *err = Err(Location(), "Couldn't open build.ninja for writing");
126 return false;
129 std::ofstream depfile;
130 depfile.open((FilePathToUTF8(ninja_file) + ".d").c_str(),
131 std::ios_base::out | std::ios_base::binary);
132 if (depfile.fail()) {
133 *err = Err(Location(), "Couldn't open depfile for writing");
134 return false;
137 NinjaBuildWriter gen(build_settings, all_settings, default_toolchain,
138 default_toolchain_targets, file, depfile);
139 return gen.Run(err);
142 void NinjaBuildWriter::WriteNinjaRules() {
143 out_ << "rule gn\n";
144 out_ << " command = " << GetSelfInvocationCommand(build_settings_) << "\n";
145 out_ << " description = Regenerating ninja files\n\n";
147 // This rule will regenerate the ninja files when any input file has changed.
148 out_ << "build build.ninja: gn\n"
149 << " generator = 1\n"
150 << " depfile = build.ninja.d\n";
152 // Input build files. These go in the ".d" file. If we write them as
153 // dependencies in the .ninja file itself, ninja will expect the files to
154 // exist and will error if they don't. When files are listed in a depfile,
155 // missing files are ignored.
156 dep_out_ << "build.ninja:";
157 std::vector<base::FilePath> input_files;
158 g_scheduler->input_file_manager()->GetAllPhysicalInputFileNames(&input_files);
159 for (size_t i = 0; i < input_files.size(); i++)
160 dep_out_ << " " << FilePathToUTF8(input_files[i]);
162 // Other files read by the build.
163 std::vector<base::FilePath> other_files = g_scheduler->GetGenDependencies();
164 for (size_t i = 0; i < other_files.size(); i++)
165 dep_out_ << " " << FilePathToUTF8(other_files[i]);
167 out_ << std::endl;
170 void NinjaBuildWriter::WriteLinkPool() {
171 out_ << "pool link_pool\n"
172 << " depth = " << default_toolchain_->concurrent_links() << std::endl
173 << std::endl;
176 void NinjaBuildWriter::WriteSubninjas() {
177 for (size_t i = 0; i < all_settings_.size(); i++) {
178 out_ << "subninja ";
179 path_output_.WriteFile(out_, GetNinjaFileForToolchain(all_settings_[i]));
180 out_ << std::endl;
182 out_ << std::endl;
185 bool NinjaBuildWriter::WritePhonyAndAllRules(Err* err) {
186 std::string all_rules;
188 // Write phony rules for all uniquely-named targets in the default toolchain.
189 // Don't do other toolchains or we'll get naming conflicts, and if the name
190 // isn't unique, also skip it. The exception is for the toplevel targets
191 // which we also find.
192 std::map<std::string, int> small_name_count;
193 std::vector<const Target*> toplevel_targets;
194 base::hash_set<std::string> target_files;
195 for (size_t i = 0; i < default_toolchain_targets_.size(); i++) {
196 const Target* target = default_toolchain_targets_[i];
197 const Label& label = target->label();
198 small_name_count[label.name()]++;
200 // Look for targets with a name of the form
201 // dir = "//foo/", name = "foo"
202 // i.e. where the target name matches the top level directory. We will
203 // always write phony rules for these even if there is another target with
204 // the same short name.
205 const std::string& dir_string = label.dir().value();
206 if (dir_string.size() == label.name().size() + 3 && // Size matches.
207 dir_string[0] == '/' && dir_string[1] == '/' && // "//" at beginning.
208 dir_string[dir_string.size() - 1] == '/' && // "/" at end.
209 dir_string.compare(2, label.name().size(), label.name()) == 0)
210 toplevel_targets.push_back(target);
213 for (size_t i = 0; i < default_toolchain_targets_.size(); i++) {
214 const Target* target = default_toolchain_targets_[i];
215 const Label& label = target->label();
216 OutputFile target_file(target->dependency_output_file());
217 // The output files may have leading "./" so normalize those away.
218 NormalizePath(&target_file.value());
219 if (!target_files.insert(target_file.value()).second) {
220 *err = Err(Location(), "Duplicate rules for " + target_file.value());
221 return false;
224 // Write the long name "foo/bar:baz" for the target "//foo/bar:baz".
225 std::string long_name = label.GetUserVisibleName(false);
226 base::TrimString(long_name, "/", &long_name);
227 WritePhonyRule(target, target_file, long_name);
229 // Write the directory name with no target name if they match
230 // (e.g. "//foo/bar:bar" -> "foo/bar").
231 if (FindLastDirComponent(label.dir()) == label.name()) {
232 std::string medium_name = DirectoryWithNoLastSlash(label.dir());
233 base::TrimString(medium_name, "/", &medium_name);
234 // That may have generated a name the same as the short name of the
235 // target which we already wrote.
236 if (medium_name != label.name())
237 WritePhonyRule(target, target_file, medium_name);
240 // Write short names for ones which are unique.
241 if (small_name_count[label.name()] == 1)
242 WritePhonyRule(target, target_file, label.name());
244 if (!all_rules.empty())
245 all_rules.append(" $\n ");
246 all_rules.append(target_file.value());
249 // Pick up phony rules for the toplevel targets with non-unique names (which
250 // would have been skipped in the above loop).
251 for (size_t i = 0; i < toplevel_targets.size(); i++) {
252 if (small_name_count[toplevel_targets[i]->label().name()] > 1) {
253 const Target* target = toplevel_targets[i];
254 WritePhonyRule(target, target->dependency_output_file(),
255 target->label().name());
259 // Figure out if the BUILD file wants to declare a custom "default"
260 // target (rather than building 'all' by default). By convention
261 // we use group("default") but it doesn't have to be a group.
262 bool default_target_exists = false;
263 for (size_t i = 0; i < default_toolchain_targets_.size(); i++) {
264 const Label& label = default_toolchain_targets_[i]->label();
265 if (label.dir().value() == "//" && label.name() == "default")
266 default_target_exists = true;
269 if (!all_rules.empty()) {
270 out_ << "\nbuild all: phony " << all_rules << std::endl;
273 if (default_target_exists) {
274 out_ << "default default" << std::endl;
275 } else if (!all_rules.empty()) {
276 out_ << "default all" << std::endl;
279 return true;
282 void NinjaBuildWriter::WritePhonyRule(const Target* target,
283 const OutputFile& target_file,
284 const std::string& phony_name) {
285 if (target_file.value() == phony_name)
286 return; // No need for a phony rule.
288 EscapeOptions ninja_escape;
289 ninja_escape.mode = ESCAPE_NINJA;
291 // Escape for special chars Ninja will handle.
292 std::string escaped = EscapeString(phony_name, ninja_escape, NULL);
294 out_ << "build " << escaped << ": phony ";
295 path_output_.WriteFile(out_, target_file);
296 out_ << std::endl;