]> git.tdb.fi Git - builder.git/blob - source/builder.cpp
Pass the option map through load_build_file and to Loader
[builder.git] / source / builder.cpp
1 #include <set>
2 #include <msp/core/getopt.h>
3 #include <msp/datafile/parser.h>
4 #include <msp/fs/dir.h>
5 #include <msp/fs/stat.h>
6 #include <msp/fs/utils.h>
7 #include <msp/io/buffered.h>
8 #include <msp/io/file.h>
9 #include <msp/io/print.h>
10 #include <msp/strings/format.h>
11 #include <msp/strings/regex.h>
12 #include <msp/strings/utils.h>
13 #include <msp/time/units.h>
14 #include <msp/time/utils.h>
15 #include "analyzer.h"
16 #include "binarypackage.h"
17 #include "builder.h"
18 #include "copy.h"
19 #include "datatool.h"
20 #include "gnuarchiver.h"
21 #include "gnuccompiler.h"
22 #include "gnucxxcompiler.h"
23 #include "gnulinker.h"
24 #include "installedfile.h"
25 #include "mingwdlltool.h"
26 #include "package.h"
27 #include "pkgconfiggenerator.h"
28 #include "sharedlibrary.h"
29 #include "sourcepackage.h"
30 #include "tar.h"
31 #include "task.h"
32 #include "virtualtarget.h"
33
34 using namespace std;
35 using namespace Msp;
36
37 Builder::Builder(int argc, char **argv):
38         package_manager(*this),
39         native_arch(*this, string()),
40         build_type(0),
41         vfs(*this),
42         build_graph(*this),
43         analyzer(0),
44         build(false),
45         clean(0),
46         dry_run(false),
47         help(false),
48         show_progress(false),
49         build_file("Build"),
50         jobs(1),
51         conf_all(false),
52         conf_only(false),
53         build_all(false),
54         create_makefile(false),
55         tempdir("temp"),
56         top_loader(0)
57 {
58         string analyze_mode;
59         string work_dir;
60         bool full_paths = false;
61         unsigned max_depth = 4;
62         string prfx;
63         string temp_str;
64         string arch;
65         bool no_externals = false;
66         unsigned verbose = 1;
67         bool silent = false;
68         list<string> log_channels;
69         string build_type_name;
70
71         GetOpt getopt;
72         getopt.add_option('a', "analyze",    analyze_mode,  GetOpt::REQUIRED_ARG).set_help("Perform dependency analysis.", "MODE");
73         getopt.add_option('b', "build",      build,         GetOpt::NO_ARG).set_help("Perform build even if also doing something else.");
74         getopt.add_option('c', "clean",      clean,         GetOpt::NO_ARG).set_help("Clean buildable targets.");
75         getopt.add_option('f', "file",       build_file,    GetOpt::REQUIRED_ARG).set_help("Read build instructions from FILE.", "FILE");
76         getopt.add_option('h', "help",       help,          GetOpt::NO_ARG).set_help("Print this message.");
77         getopt.add_option('j', "jobs",       jobs,          GetOpt::REQUIRED_ARG).set_help("Run up to NUM tasks in parallel.", "NUM");
78         getopt.add_option('l', "log",        log_channels,  GetOpt::REQUIRED_ARG).set_help("Enable listed log channels.", "LIST");
79         getopt.add_option('n', "dry-run",    dry_run,       GetOpt::NO_ARG).set_help("Show what would be done without actually doing it.");
80         getopt.add_option('s', "silent",     silent,        GetOpt::NO_ARG).set_help("Don't print any messages other than errors.");
81         getopt.add_option('t', "build-type", build_type_name, GetOpt::REQUIRED_ARG).set_help("Set build type.", "TYPE");
82         getopt.add_option('v', "verbose",    verbose,       GetOpt::NO_ARG).set_help("Print more information about what's going on.");
83         getopt.add_option('x', "no-externals",  no_externals, GetOpt::NO_ARG).set_help("Do not load external source packages.");
84         getopt.add_option('A', "conf-all",   conf_all,      GetOpt::NO_ARG).set_help("Apply configuration to all packages.");
85         getopt.add_option('B', "build-all",  build_all,     GetOpt::NO_ARG).set_help("Build all targets unconditionally.");
86         getopt.add_option('C', "chdir",      work_dir,      GetOpt::REQUIRED_ARG).set_help("Change to DIR before doing anything else.", "DIR");
87         getopt.add_option('P', "progress",   show_progress, GetOpt::NO_ARG).set_help("Display progress while building.");
88         getopt.add_option('W', "what-if",    what_if,       GetOpt::REQUIRED_ARG).set_help("Pretend that FILE has changed.", "FILE");
89         getopt.add_option(     "arch",       arch,          GetOpt::REQUIRED_ARG).set_help("Build for architecture ARCH.", "ARCH");
90         getopt.add_option(     "conf-only",  conf_only,     GetOpt::NO_ARG).set_help("Stop after configuring packages.");
91         getopt.add_option(     "full-paths", full_paths,    GetOpt::NO_ARG).set_help("Output full paths in analysis.");
92         getopt.add_option(     "max-depth",  max_depth,     GetOpt::REQUIRED_ARG).set_help("Show up to NUM levels in analysis.", "NUM");
93         getopt.add_option(     "prefix",     prfx,          GetOpt::REQUIRED_ARG).set_help("Install things to DIR.", "DIR");
94         getopt.add_option(     "tempdir",    temp_str,      GetOpt::REQUIRED_ARG).set_help("Store temporary files in DIR.", "DIR");
95         usagemsg = getopt.generate_usage(argv[0])+" [<target> ...]";
96         helpmsg = getopt.generate_help();
97         getopt(argc, argv);
98
99         if(silent)
100                 --verbose;
101         if(verbose>=1)
102         {
103                 logger.enable_channel("summary");
104                 logger.enable_channel("tasks");
105         }
106         if(verbose>=2)
107         {
108                 logger.enable_channel("environment");
109                 logger.enable_channel("packages");
110                 logger.enable_channel("commands");
111         }
112         if(verbose>=3)
113         {
114                 logger.enable_channel("files");
115                 logger.enable_channel("auxcommands");
116         }
117         for(list<string>::const_iterator i=log_channels.begin(); i!=log_channels.end(); ++i)
118         {
119                 vector<string> parts = split(*i, ',');
120                 for(vector<string>::const_iterator j=parts.begin(); j!=parts.end(); ++j)
121                         logger.enable_channel(*j);
122         }
123
124         if(!analyze_mode.empty())
125         {
126                 analyzer = new Analyzer(*this);
127
128                 if(analyze_mode=="deps")
129                         analyzer->set_mode(Analyzer::DEPS);
130                 else if(analyze_mode=="alldeps")
131                         analyzer->set_mode(Analyzer::ALLDEPS);
132                 else if(analyze_mode=="rebuild")
133                         analyzer->set_mode(Analyzer::REBUILD);
134                 else if(analyze_mode=="rdeps")
135                         analyzer->set_mode(Analyzer::RDEPS);
136                 else
137                         throw usage_error("Invalid analyze mode");
138
139                 analyzer->set_max_depth(max_depth);
140                 analyzer->set_full_paths(full_paths);
141         }
142         else if(!clean && !create_makefile)
143                 build = true;
144
145         const vector<string> &args = getopt.get_args();
146         for(vector<string>::const_iterator i=args.begin(); i!=args.end(); ++i)
147         {
148                 string::size_type equal = i->find('=');
149                 if(equal!=string::npos)
150                         cmdline_options.insert(Config::InputOptions::value_type(i->substr(0, equal), i->substr(equal+1)));
151                 else
152                         cmdline_targets.push_back(*i);
153         }
154
155         if(!work_dir.empty())
156                 FS::chdir(work_dir);
157
158         cwd = FS::getcwd();
159
160         package_manager.append_package_path(cwd);
161         package_manager.append_package_path(cwd/"..");
162         package_manager.append_binary_package_path(FS::get_sys_data_dir(argv[0], "builder"));
163
164         package_manager.set_no_externals(no_externals);
165
166         if(arch.empty())
167                 current_arch = &native_arch;
168         else
169                 current_arch = new Architecture(*this, arch);
170
171         list<FS::Path> start_files;
172         start_files.push_back(FS::get_sys_data_dir(argv[0], "builder")/"builderrc");
173         start_files.push_back(FS::get_user_data_dir("builder")/"rc");
174         for(list<FS::Path>::const_iterator i=start_files.begin(); i!=start_files.end(); ++i)
175                 if(FS::exists(*i))
176                         load_build_file(*i);
177
178         if(prfx.empty())
179         {
180                 if(current_arch->is_native())
181                         prefix = (FS::get_home_dir()/"local").str();
182                 else
183                         prefix = (FS::get_home_dir()/"local"/current_arch->get_name()).str();
184         }
185         else
186                 prefix = cwd/prfx;
187
188         if(!temp_str.empty())
189                 tempdir = temp_str;
190
191         if(!build_type_name.empty())
192         {
193                 BuildTypeMap::iterator i = build_types.find(build_type_name);
194                 if(i==build_types.end())
195                         throw usage_error("Unknown build type");
196                 build_type = &i->second;
197         }
198
199         toolchain.add_tool(new GnuCCompiler(*this, *current_arch));
200         toolchain.add_tool(new GnuCxxCompiler(*this, *current_arch));
201         toolchain.add_tool(new GnuLinker(*this, *current_arch));
202         toolchain.add_tool(new GnuArchiver(*this, *current_arch));
203         toolchain.add_tool(new Copy(*this));
204         toolchain.add_tool(new Tar(*this));
205         toolchain.add_tool(new PkgConfigGenerator(*this));
206         if(current_arch->get_system()=="windows")
207                 toolchain.add_tool(new MingwDllTool(*this, *current_arch));
208         toolchain.add_tool(new DataTool(*this));
209 }
210
211 Builder::~Builder()
212 {
213         delete analyzer;
214 }
215
216 int Builder::main()
217 {
218         FS::Path main_file = cwd/build_file;
219         if(!FS::exists(main_file))
220         {
221                 if(help)
222                 {
223                         usage(0, "builder", false);
224                         return 0;
225                 }
226                 else
227                 {
228                         IO::print(IO::cerr, "The file %s does not exist.\n", main_file);
229                         return 1;
230                 }
231         }
232
233         load_build_file(main_file, &cmdline_options, conf_all);
234
235         if(help)
236         {
237                 usage(0, "builder", false);
238                 IO::print("\n");
239                 package_help();
240                 return 0;
241         }
242
243         if(!prepare_build())
244                 return 1;
245
246         if(conf_only)
247                 return 0;
248
249         logger.log("environment", format("Building on %s, for %s%s", native_arch.get_name(),
250                 current_arch->get_name(), (current_arch->is_native() ? " (native)" : "")));
251         logger.log("environment", format("Prefix is %s", prefix));
252         if(tempdir.is_absolute())
253                 logger.log("environment", format("Temporary directory is %s", tempdir));
254         else
255                 logger.log("environment", format("Using per-package temporary directory %s", tempdir));
256         if(build_type)
257                 logger.log("environment", format("Build type is %s", build_type->get_name()));
258
259         const PackageManager::PackageMap &packages = package_manager.get_packages();
260         list<string> package_details;
261         for(PackageManager::PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
262         {
263                 if(!i->second->is_prepared())
264                         continue;
265
266                 string line = i->second->get_name();
267                 if(dynamic_cast<SourcePackage *>(i->second))
268                 {
269                         line += '*';
270
271                         unsigned count = 0;
272                         unsigned to_be_built = 0;
273                         const BuildGraph::TargetMap &targets = build_graph.get_targets();
274                         for(BuildGraph::TargetMap::const_iterator j=targets.begin(); j!=targets.end(); ++j)
275                                 if(j->second->get_package()==i->second)
276                                 {
277                                         ++count;
278                                         if(j->second->needs_rebuild())
279                                                 ++to_be_built;
280                                 }
281                         if(count)
282                         {
283                                 line += format(" (%d targets", count);
284                                 if(to_be_built)
285                                         line += format(", %d to be built", to_be_built);
286                                 line += ')';
287                         }
288                 }
289
290                 package_details.push_back(line);
291         }
292
293         logger.log("summary", format("%d active packages, %d targets", package_details.size(), build_graph.get_targets().size()));
294         for(list<string>::const_iterator i=package_details.begin(); i!=package_details.end(); ++i)
295                 logger.log("packages", *i);
296
297         if(analyzer)
298                 analyzer->analyze();
299
300         if(!problems.empty())
301         {
302                 IO::print(IO::cerr, "The following problems were detected:\n");
303                 for(ProblemList::iterator i=problems.begin(); i!=problems.end(); ++i)
304                         IO::print(IO::cerr, "  %s: %s\n", i->package, i->descr);
305                 if(!analyzer)
306                         IO::print(IO::cerr, "Please fix them and try again.\n");
307                 return 1;
308         }
309
310         if(clean)
311                 exit_code = do_clean();
312         if(build)
313                 exit_code = do_build();
314
315         return exit_code;
316 }
317
318 void Builder::problem(const string &p, const string &d)
319 {
320         problems.push_back(Problem(p, d));
321 }
322
323 void Builder::usage(const char *reason, const char *argv0, bool brief)
324 {
325         if(reason)
326                 IO::print(IO::cerr, "%s\n", reason);
327
328         if(brief)
329                 IO::print(IO::cerr, "Usage: %s\n", usagemsg);
330         else
331         {
332                 IO::print(IO::cerr, "Builder 1.0\n\n");
333                 IO::print(IO::cerr, "Usage: %s [options] [<target> ...]\n\n", argv0);
334                 IO::print(IO::cerr, "Options:\n");
335                 IO::print(IO::cerr, helpmsg);
336         }
337 }
338
339 void Builder::load_build_file(const FS::Path &fn, const Config::InputOptions *opts, bool all)
340 {
341         IO::BufferedFile in(fn.str());
342
343         logger.log("files", format("Reading %s", fn));
344
345         DataFile::Parser parser(in, fn.str());
346         Loader loader(*this, opts, all);
347         loader.load(parser);
348 }
349
350 bool Builder::prepare_build()
351 {
352         package_manager.get_main_package().prepare();
353
354         // Add targets from command line as goals
355         for(NameList::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
356         {
357                 Target *tgt = build_graph.get_target(*i);
358                 if(!tgt)
359                         tgt = vfs.get_target(*i);
360                 if(!tgt)
361                         tgt = vfs.get_target(cwd/ *i);
362                 if(!tgt)
363                 {
364                         IO::print("I don't know anything about %s\n", *i);
365                         return false;
366                 }
367
368                 build_graph.add_goal(*tgt);
369         }
370
371         build_graph.prepare();
372
373         // Apply what-ifs
374         for(NameList::iterator i=what_if.begin(); i!=what_if.end(); ++i)
375         {
376                 FileTarget *tgt = vfs.get_target(cwd/ *i);
377                 if(!tgt)
378                 {
379                         IO::print(IO::cerr, "Unknown what-if target %s\n", *i);
380                         return false;
381                 }
382                 tgt->touch();
383         }
384
385         if(build_all)
386                 build_graph.force_full_rebuild();
387
388         if(!dry_run)
389         {
390                 const PackageManager::PackageMap &packages = package_manager.get_packages();
391                 for(PackageManager::PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
392                         i->second->save_caches();
393         }
394
395         return true;
396 }
397
398 int Builder::do_build()
399 {
400         unsigned total = build_graph.count_rebuild_targets();
401
402         if(!total)
403         {
404                 logger.log("summary", "Already up to date");
405                 return 0;
406         }
407         logger.log("summary", format("Will build %d target%s", total, (total!=1 ? "s" : "")));
408
409         vector<Task *> tasks;
410
411         unsigned count = 0;
412
413         bool fail = false;
414         bool finish = false;
415         bool starved = false;
416
417         while(!finish)
418         {
419                 if(tasks.size()<jobs && !fail && !starved)
420                 {
421                         Target *tgt = build_graph.get_buildable_target();
422                         if(tgt)
423                         {
424                                 if(tgt->get_tool())
425                                         logger.log("tasks", format("%-4s  %s", tgt->get_tool()->get_tag(), tgt->get_name()));
426                                 Task *task = tgt->build();
427                                 if(task)
428                                 {
429                                         logger.log("commands", format("%s", task->get_command()));
430                                         if(dry_run)
431                                         {
432                                                 task->signal_finished.emit(true);
433                                                 delete task;
434                                         }
435                                         else
436                                         {
437                                                 task->start();
438                                                 tasks.push_back(task);
439                                         }
440                                 }
441
442                                 if(show_progress)
443                                         IO::print("%d of %d target%s built\033[1G", count, total, (total!=1 ? "s" : ""));
444                         }
445                         else if(tasks.empty())
446                                 finish = true;
447                         else
448                                 starved = true;
449                 }
450                 else
451                         Time::sleep(10*Time::msec);
452
453                 for(unsigned i=0; i<tasks.size();)
454                 {
455                         Task::Status status;
456                         if(jobs==1 || (tasks.size()==1 && starved))
457                                 status = tasks[i]->wait();
458                         else
459                                 status = tasks[i]->check();
460
461                         if(status!=Task::RUNNING)
462                         {
463                                 ++count;
464
465                                 delete tasks[i];
466                                 tasks.erase(tasks.begin()+i);
467                                 if(status==Task::ERROR)
468                                         fail = true;
469                                 if(tasks.empty() && fail)
470                                         finish = true;
471                                 starved = false;
472                         }
473                         else
474                                 ++i;
475                 }
476         }
477
478         if(show_progress)
479                 IO::print("\033[K");
480         if(fail)
481                 logger.log("summary", "Build failed");
482         else if(show_progress)
483                 logger.log("summary", "Build complete");
484
485         if(!dry_run)
486         {
487                 const PackageManager::PackageMap &packages = package_manager.get_packages();
488                 for(PackageManager::PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
489                         i->second->save_caches();
490         }
491
492         return fail;
493 }
494
495 int Builder::do_clean()
496 {
497         // Cleaning doesn't care about ordering, so a simpler method can be used
498
499         set<Target *> clean_tgts;
500         list<Target *> queue;
501         queue.push_back(build_graph.get_target("cmdline"));
502
503         while(!queue.empty())
504         {
505                 Target *tgt = queue.front();
506                 queue.erase(queue.begin());
507
508                 if(tgt->is_buildable() && (tgt->get_package()==&package_manager.get_main_package() || clean>=2))
509                         clean_tgts.insert(tgt);
510
511                 const Target::Dependencies &deps = tgt->get_dependencies();
512                 for(list<Target *>::const_iterator i=deps.begin(); i!=deps.end(); ++i)
513                         if(!clean_tgts.count(*i))
514                                 queue.push_back(*i);
515         }
516
517         for(set<Target *>::iterator i=clean_tgts.begin(); i!=clean_tgts.end(); ++i)
518         {
519                 logger.log("tasks", format("RM    %s", (*i)->get_name()));
520                 if(!dry_run)
521                         (*i)->clean();
522         }
523
524         return 0;
525 }
526
527 void Builder::package_help()
528 {
529         SourcePackage &main_pkg = dynamic_cast<SourcePackage &>(package_manager.get_main_package());
530         const Config &config = main_pkg.get_config();
531         const Config::OptionMap &options = config.get_options();
532
533         IO::print("Required packages:\n  ");
534         const Package::Requirements &requires = main_pkg.get_required_packages();
535         for(Package::Requirements::const_iterator i=requires.begin(); i!=requires.end(); ++i)
536         {
537                 if(i!=requires.begin())
538                         IO::print(", ");
539                 IO::print((*i)->get_name());
540         }
541         IO::print("\n\nPackage configuration:\n");
542         for(Config::OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
543         {
544                 const Config::Option &opt = i->second;
545                 IO::print("  %s: %s (%s)", opt.name, opt.description, opt.value);
546                 if(opt.value!=opt.default_value)
547                         IO::print(" [%s]", opt.default_value);
548                 IO::print("\n");
549         }
550 }
551
552 string Builder::usagemsg;
553 string Builder::helpmsg;
554
555
556 Builder::Loader::Loader(Builder &b, const Config::InputOptions *o, bool a):
557         DataFile::ObjectLoader<Builder>(b),
558         options(o),
559         conf_all(a)
560 {
561         add("architecture", &Loader::architecture);
562         add("binary_package", &Loader::binpkg);
563         add("build_type", &Loader::build_type);
564         add("profile", &Loader::profile);
565         add("package", &Loader::package);
566
567         if(!obj.top_loader)
568                 obj.top_loader = this;
569         else if(!options && obj.top_loader!=this && obj.top_loader->conf_all)
570                 options = obj.top_loader->options;
571 }
572
573 Builder::Loader::~Loader()
574 {
575         if(obj.top_loader==this)
576                 obj.top_loader = 0;
577 }
578
579 void Builder::Loader::architecture(const string &n)
580 {
581         if(obj.current_arch->match_name(n))
582                 load_sub(*obj.current_arch);
583 }
584
585 void Builder::Loader::binpkg(const string &n)
586 {
587         BinaryPackage *pkg = new BinaryPackage(obj, n);
588         load_sub(*pkg);
589 }
590
591 void Builder::Loader::build_type(const string &n)
592 {
593         BuildType btype(n);
594         load_sub(btype);
595         BuildTypeMap::iterator i = obj.build_types.insert(BuildTypeMap::value_type(n, btype)).first;
596         if(!obj.build_type)
597                 obj.build_type = &i->second;
598 }
599
600 void Builder::Loader::profile(const string &)
601 {
602         IO::print("Profiles are deprecated\n");
603 }
604
605 void Builder::Loader::package(const string &n)
606 {
607         SourcePackage *pkg = new SourcePackage(obj, n, get_source());
608
609         if(options)
610                 load_sub(*pkg, *options);
611         else
612                 load_sub(*pkg);
613
614         if(obj.build_type)
615                 pkg->set_build_type(*obj.build_type);
616 }