]> git.tdb.fi Git - builder.git/blob - source/buildercli.cpp
Allow overriding tool commands on the command line
[builder.git] / source / buildercli.cpp
1 #include <msp/core/getopt.h>
2 #include <msp/fs/dir.h>
3 #include <msp/fs/stat.h>
4 #include <msp/io/print.h>
5 #include <msp/strings/format.h>
6 #include <msp/strings/utils.h>
7 #include "analyzer.h"
8 #include "buildercli.h"
9 #include "filetarget.h"
10 #include "sourcepackage.h"
11 #include "tool.h"
12 #include "toolchain.h"
13
14 using namespace std;
15 using namespace Msp;
16
17 BuilderCLI::BuilderCLI(int argc, char **argv):
18         analyzer(0),
19         build(false),
20         clean(0),
21         dry_run(false),
22         help(false),
23         show_progress(false),
24         build_file("Build"),
25         jobs(1),
26         conf_all(false),
27         conf_only(false),
28         build_all(false),
29         create_makefile(false)
30 {
31         string analyze_mode;
32         string work_dir;
33         bool full_paths = false;
34         unsigned max_depth = 4;
35         string prefix;
36         string tempdir;
37         string arch;
38         bool no_externals = false;
39         unsigned verbose = 1;
40         bool silent = false;
41         list<string> log_channels;
42         string build_type;
43
44         GetOpt getopt;
45         getopt.add_option('a', "analyze",    analyze_mode,  GetOpt::REQUIRED_ARG).set_help("Perform dependency analysis.", "MODE");
46         getopt.add_option('b', "build",      build,         GetOpt::NO_ARG).set_help("Perform build even if also doing something else.");
47         getopt.add_option('c', "clean",      clean,         GetOpt::NO_ARG).set_help("Clean buildable targets.");
48         getopt.add_option('f', "file",       build_file,    GetOpt::REQUIRED_ARG).set_help("Read build instructions from FILE.", "FILE");
49         getopt.add_option('h', "help",       help,          GetOpt::NO_ARG).set_help("Print this message.");
50         getopt.add_option('j', "jobs",       jobs,          GetOpt::REQUIRED_ARG).set_help("Run up to NUM tasks in parallel.", "NUM");
51         getopt.add_option('l', "log",        log_channels,  GetOpt::REQUIRED_ARG).set_help("Enable listed log channels.", "LIST");
52         getopt.add_option('n', "dry-run",    dry_run,       GetOpt::NO_ARG).set_help("Show what would be done without actually doing it.");
53         getopt.add_option('s', "silent",     silent,        GetOpt::NO_ARG).set_help("Don't print any messages other than errors.");
54         getopt.add_option('t', "build-type", build_type,    GetOpt::REQUIRED_ARG).set_help("Set build type.", "TYPE");
55         getopt.add_option('v', "verbose",    verbose,       GetOpt::NO_ARG).set_help("Print more information about what's going on.");
56         getopt.add_option('x', "no-externals",no_externals, GetOpt::NO_ARG).set_help("Do not load external source packages.");
57         getopt.add_option('A', "conf-all",   conf_all,      GetOpt::NO_ARG).set_help("Apply configuration to all packages.");
58         getopt.add_option('B', "build-all",  build_all,     GetOpt::NO_ARG).set_help("Build all targets unconditionally.");
59         getopt.add_option('C', "chdir",      work_dir,      GetOpt::REQUIRED_ARG).set_help("Change to DIR before doing anything else.", "DIR");
60         getopt.add_option('P', "progress",   show_progress, GetOpt::NO_ARG).set_help("Display progress while building.");
61         getopt.add_option('W', "what-if",    what_if,       GetOpt::REQUIRED_ARG).set_help("Pretend that FILE has changed.", "FILE");
62         getopt.add_option(     "arch",       arch,          GetOpt::REQUIRED_ARG).set_help("Build for architecture ARCH.", "ARCH");
63         getopt.add_option(     "conf-only",  conf_only,     GetOpt::NO_ARG).set_help("Stop after configuring packages.");
64         getopt.add_option(     "full-paths", full_paths,    GetOpt::NO_ARG).set_help("Output full paths in analysis.");
65         getopt.add_option(     "max-depth",  max_depth,     GetOpt::REQUIRED_ARG).set_help("Show up to NUM levels in analysis.", "NUM");
66         getopt.add_option(     "prefix",     prefix,        GetOpt::REQUIRED_ARG).set_help("Install things to DIR.", "DIR");
67         getopt.add_option(     "tempdir",    tempdir,       GetOpt::REQUIRED_ARG).set_help("Store temporary files in DIR.", "DIR");
68         getopt.add_argument("target", cmdline_targets, GetOpt::OPTIONAL_ARG).set_help("Target(s) to build");
69         getopt(argc, argv);
70
71         if(help)
72         {
73                 helpmsg = "Usage:\n  ";
74                 helpmsg += getopt.generate_usage(argv[0], true);
75                 helpmsg += "\n\n";
76                 helpmsg += getopt.generate_help();
77         }
78
79         if(silent)
80                 --verbose;
81         if(verbose>=1)
82         {
83                 logger.enable_channel("summary");
84                 logger.enable_channel("tasks");
85         }
86         if(verbose>=2)
87         {
88                 logger.enable_channel("environment");
89                 logger.enable_channel("packages");
90                 logger.enable_channel("commands");
91         }
92         if(verbose>=3)
93         {
94                 logger.enable_channel("files");
95                 logger.enable_channel("auxcommands");
96         }
97         for(list<string>::const_iterator i=log_channels.begin(); i!=log_channels.end(); ++i)
98         {
99                 vector<string> parts = split(*i, ',');
100                 for(vector<string>::const_iterator j=parts.begin(); j!=parts.end(); ++j)
101                         logger.enable_channel(*j);
102         }
103         builder.set_logger(&logger);
104
105         if(!analyze_mode.empty())
106         {
107                 analyzer = new Analyzer(builder);
108
109                 if(analyze_mode=="deps")
110                         analyzer->set_mode(Analyzer::DEPS);
111                 else if(analyze_mode=="alldeps")
112                         analyzer->set_mode(Analyzer::ALLDEPS);
113                 else if(analyze_mode=="rebuild")
114                         analyzer->set_mode(Analyzer::REBUILD);
115                 else if(analyze_mode=="rdeps")
116                         analyzer->set_mode(Analyzer::RDEPS);
117                 else
118                         throw usage_error("Invalid analyze mode");
119
120                 analyzer->set_max_depth(max_depth);
121                 analyzer->set_full_paths(full_paths);
122         }
123         else if(!clean && !create_makefile)
124                 build = true;
125
126         for(NameList::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); )
127         {
128                 string::size_type equal = i->find('=');
129                 if(equal!=string::npos)
130                 {
131                         cmdline_options.insert(Config::InputOptions::value_type(i->substr(0, equal), i->substr(equal+1)));
132                         cmdline_targets.erase(i++);
133                 }
134                 else
135                         ++i;
136         }
137
138         if(!work_dir.empty())
139                 FS::chdir(work_dir);
140
141         cwd = FS::getcwd();
142
143         PackageManager &package_manager = builder.get_package_manager();
144
145         package_manager.append_package_path(cwd);
146         package_manager.append_package_path(cwd/"..");
147         package_manager.append_binary_package_path(FS::get_sys_data_dir(argv[0], "builder"));
148
149         package_manager.set_no_externals(no_externals);
150
151         builder.set_architecture(arch);
152
153         list<FS::Path> start_files;
154         start_files.push_back(FS::get_sys_data_dir(argv[0], "builder")/"builderrc");
155         start_files.push_back(FS::get_user_data_dir("builder")/"rc");
156         for(list<FS::Path>::const_iterator i=start_files.begin(); i!=start_files.end(); ++i)
157                 if(FS::exists(*i))
158                         builder.load_build_file(*i);
159
160         if(!prefix.empty())
161                 builder.set_prefix(cwd/prefix);
162
163         if(!tempdir.empty())
164                 builder.set_temp_directory(tempdir);
165
166         if(!build_type.empty())
167                 builder.set_build_type(build_type);
168
169         builder.add_default_tools();
170
171         const Toolchain &toolchain = builder.get_toolchain();
172         for(Config::InputOptions::iterator i=cmdline_options.begin(); i!=cmdline_options.end(); )
173         {
174                 if(toolchain.has_tool(i->first))
175                 {
176                         toolchain.get_tool(i->first).set_command(i->second);
177                         cmdline_options.erase(i++);
178                 }
179                 else
180                         ++i;
181         }
182 }
183
184 BuilderCLI::~BuilderCLI()
185 {
186         delete analyzer;
187 }
188
189 int BuilderCLI::main()
190 {
191         FS::Path main_file = cwd/build_file;
192         if(FS::exists(main_file))
193                 builder.load_build_file(main_file, &cmdline_options, conf_all);
194         else if(!help)
195         {
196                 IO::print(IO::cerr, "The file %s does not exist.\n", main_file);
197                 return 1;
198         }
199
200         if(help)
201         {
202                 IO::print("Builder 1.0\n"
203                         "Copyright © 2006-2013  Mikkosoft Productions, Mikko Rasa\n"
204                         "Licensed under the GPL\n\n"
205                         "%s", helpmsg);
206                 package_help();
207                 return 0;
208         }
209
210         if(!prepare_build())
211                 return 1;
212
213         if(conf_only)
214                 return 0;
215
216         const Architecture &native_arch = builder.get_native_arch();
217         const Architecture &current_arch = builder.get_current_arch();
218         logger.log("environment", format("Building on %s, for %s%s", native_arch.get_name(),
219                 current_arch.get_name(), (current_arch.is_native() ? " (native)" : "")));
220         logger.log("environment", format("Prefix is %s", builder.get_prefix()));
221         const FS::Path &tempdir = builder.get_temp_directory();
222         if(tempdir.is_absolute())
223                 logger.log("environment", format("Temporary directory is %s", tempdir));
224         else
225                 logger.log("environment", format("Using per-package temporary directory %s", tempdir));
226         const BuildType &build_type = builder.get_build_type();
227         logger.log("environment", format("Build type is %s", build_type.get_name()));
228
229         BuildGraph &build_graph = builder.get_build_graph();
230         PackageManager &package_manager = builder.get_package_manager();
231         const PackageManager::PackageMap &packages = package_manager.get_packages();
232         list<string> package_details;
233         for(PackageManager::PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
234         {
235                 if(!i->second->is_prepared())
236                         continue;
237
238                 string line = i->second->get_name();
239                 if(dynamic_cast<SourcePackage *>(i->second))
240                 {
241                         line += '*';
242
243                         unsigned count = 0;
244                         unsigned to_be_built = 0;
245                         const BuildGraph::TargetMap &targets = build_graph.get_targets();
246                         for(BuildGraph::TargetMap::const_iterator j=targets.begin(); j!=targets.end(); ++j)
247                                 if(j->second->get_package()==i->second)
248                                 {
249                                         ++count;
250                                         if(j->second->needs_rebuild())
251                                                 ++to_be_built;
252                                 }
253                         if(count)
254                         {
255                                 line += format(" (%d targets", count);
256                                 if(to_be_built)
257                                         line += format(", %d to be built", to_be_built);
258                                 line += ')';
259                         }
260                 }
261
262                 package_details.push_back(line);
263         }
264
265         logger.log("summary", format("%d active packages, %d targets", package_details.size(), build_graph.get_targets().size()));
266         for(list<string>::const_iterator i=package_details.begin(); i!=package_details.end(); ++i)
267                 logger.log("packages", *i);
268
269         if(analyzer)
270                 analyzer->analyze();
271
272         if(build_graph.get_goals().is_broken())
273         {
274                 list<string> problems = builder.collect_problems();
275                 IO::print(IO::cerr, "The following problems were detected:\n");
276                 for(list<string>::const_iterator i=problems.begin(); i!=problems.end(); ++i)
277                         IO::print(IO::cerr, "  %s\n", *i);
278                 if(!analyzer)
279                         IO::print(IO::cerr, "Please fix them and try again.\n");
280                 return 1;
281         }
282
283         if(clean)
284                 exit_code = builder.clean(clean>=2, dry_run);
285         if(build)
286                 exit_code = builder.build(jobs, dry_run, show_progress);
287
288         return exit_code;
289 }
290
291 bool BuilderCLI::prepare_build()
292 {
293         /* XXX This is ugly; using the Builder class should not be this convoluted.
294         But the command line targets and what ifs need to be set at certain points
295         during preparation. */
296         BuildGraph &build_graph = builder.get_build_graph();
297         PackageManager &package_manager = builder.get_package_manager();
298
299         package_manager.get_main_package().prepare();
300
301         // Add targets from command line as goals
302         for(NameList::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
303         {
304                 Target *tgt = resolve_target(*i);
305                 if(!tgt)
306                 {
307                         IO::print("I don't know anything about %s\n", *i);
308                         return false;
309                 }
310
311                 build_graph.add_goal(*tgt);
312         }
313
314         build_graph.prepare();
315
316         // Apply what-ifs
317         for(NameList::iterator i=what_if.begin(); i!=what_if.end(); ++i)
318         {
319                 FileTarget *tgt = dynamic_cast<FileTarget *>(resolve_target(*i));
320                 if(!tgt)
321                 {
322                         IO::print(IO::cerr, "Unknown what-if target %s\n", *i);
323                         return false;
324                 }
325                 tgt->touch();
326         }
327
328         if(build_all)
329                 build_graph.force_full_rebuild();
330
331         if(!dry_run)
332                 package_manager.save_all_caches();
333
334         return true;
335 }
336
337 Target *BuilderCLI::resolve_target(const string &name)
338 {
339         Target *tgt = builder.get_build_graph().get_target(name);
340         if(!tgt)
341                 tgt = builder.get_vfs().get_target(cwd/name);
342         return tgt;
343 }
344
345 void BuilderCLI::package_help()
346 {
347         PackageManager &package_manager = builder.get_package_manager();
348         if(package_manager.get_packages().empty())
349                 return;
350
351         SourcePackage &main_pkg = dynamic_cast<SourcePackage &>(package_manager.get_main_package());
352         const Config &config = main_pkg.get_config();
353         const Config::OptionMap &options = config.get_options();
354
355         IO::print("\nRequired packages:\n  ");
356         const Package::Requirements &requires = main_pkg.get_required_packages();
357         for(Package::Requirements::const_iterator i=requires.begin(); i!=requires.end(); ++i)
358         {
359                 if(i!=requires.begin())
360                         IO::print(", ");
361                 IO::print((*i)->get_name());
362         }
363         IO::print("\n");
364
365         if(!options.empty())
366         {
367                 IO::print("\nPackage configuration:\n");
368                 for(Config::OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
369                 {
370                         const Config::Option &opt = i->second;
371                         string line = format("  %s: %s (%s)", opt.name, opt.description, opt.value);
372                         if(!opt.choices.empty())
373                         {
374                                 line += " {";
375                                 for(list<string>::const_iterator j=opt.choices.begin(); j!=opt.choices.end(); ++j)
376                                 {
377                                         if(j!=opt.choices.begin())
378                                                 line += ' ';
379                                         line += *j;
380                                 }
381                                 line += '}';
382                         }
383                         else if(opt.value!=opt.default_value)
384                                 line += format(" [%s]", opt.default_value);
385                         IO::print("%s\n", line);
386                 }
387         }
388 }