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