]> git.tdb.fi Git - builder.git/blob - source/builder.cpp
Route InstalledFile target creation through Builder
[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 *install = get_target("install");
345         const Tool &copy = toolchain.get_tool("CP");
346         install->add_dependency(*copy.create_target(t));
347 }
348
349 void Builder::usage(const char *reason, const char *argv0, bool brief)
350 {
351         if(reason)
352                 IO::print(IO::cerr, "%s\n", reason);
353
354         if(brief)
355                 IO::print(IO::cerr, "Usage: %s\n", usagemsg);
356         else
357         {
358                 IO::print(IO::cerr, "Builder 1.0\n\n");
359                 IO::print(IO::cerr, "Usage: %s [options] [<target> ...]\n\n", argv0);
360                 IO::print(IO::cerr, "Options:\n");
361                 IO::print(IO::cerr, helpmsg);
362         }
363 }
364
365 void Builder::load_build_file(const FS::Path &fn)
366 {
367         IO::BufferedFile in(fn.str());
368
369         logger.log("files", format("Reading %s", fn));
370
371         DataFile::Parser parser(in, fn.str());
372         Loader loader(*this);
373         loader.load(parser);
374 }
375
376 bool Builder::prepare_build()
377 {
378         Target *world = new VirtualTarget(*this, "world");
379
380         Target *def_tgt = new VirtualTarget(*this, "default");
381         world->add_dependency(*def_tgt);
382
383         Target *install = new VirtualTarget(*this, "install");
384         world->add_dependency(*install);
385
386         Target *tarballs = new VirtualTarget(*this, "tarballs");
387         world->add_dependency(*tarballs);
388
389         main_pkg->prepare();
390
391         // Make the cmdline target depend on all targets mentioned on the command line
392         Target *cmdline = new VirtualTarget(*this, "cmdline");
393         for(NameList::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
394         {
395                 Target *tgt = get_target(*i);
396                 if(!tgt)
397                         tgt = vfs.get_target(*i);
398                 if(!tgt)
399                         tgt = vfs.get_target(cwd/ *i);
400                 if(!tgt)
401                 {
402                         IO::print("I don't know anything about %s\n", *i);
403                         return false;
404                 }
405
406                 cmdline->add_dependency(*tgt);
407         }
408
409         cmdline->prepare();
410
411         // Apply what-ifs
412         for(NameList::iterator i=what_if.begin(); i!=what_if.end(); ++i)
413         {
414                 FileTarget *tgt = vfs.get_target(cwd/ *i);
415                 if(!tgt)
416                 {
417                         IO::print(IO::cerr, "Unknown what-if target %s\n", *i);
418                         return false;
419                 }
420                 tgt->touch();
421         }
422
423         if(build_all)
424         {
425                 for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
426                         if(i->second->is_buildable() && !i->second->needs_rebuild())
427                                 i->second->force_rebuild();
428         }
429
430         if(!dry_run)
431         {
432                 const PackageManager::PackageMap &packages = package_manager.get_packages();
433                 for(PackageManager::PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
434                         i->second->save_caches();
435         }
436
437         return true;
438 }
439
440 int Builder::do_build()
441 {
442         Target *cmdline = get_target("cmdline");
443
444         unsigned total = 0;
445         for(map<string, Target *>::const_iterator i=targets.begin(); i!=targets.end(); ++i)
446                 if(i->second->is_buildable() && i->second->needs_rebuild())
447                         ++total;
448
449         if(!total)
450         {
451                 logger.log("summary", "Already up to date");
452                 return 0;
453         }
454         logger.log("summary", format("Will build %d target%s", total, (total!=1 ? "s" : "")));
455
456         vector<Task *> tasks;
457
458         unsigned count = 0;
459
460         bool fail = false;
461         bool finish = false;
462         bool starved = false;
463
464         while(!finish)
465         {
466                 if(tasks.size()<jobs && !fail && !starved)
467                 {
468                         Target *tgt = cmdline->get_buildable_target();
469                         if(tgt)
470                         {
471                                 if(tgt->get_tool())
472                                         logger.log("tasks", format("%-4s  %s", tgt->get_tool()->get_tag(), tgt->get_name()));
473                                 Task *task = tgt->build();
474                                 if(task)
475                                 {
476                                         logger.log("commands", format("%s", task->get_command()));
477                                         if(dry_run)
478                                         {
479                                                 task->signal_finished.emit(true);
480                                                 delete task;
481                                         }
482                                         else
483                                         {
484                                                 task->start();
485                                                 tasks.push_back(task);
486                                         }
487                                 }
488
489                                 if(show_progress)
490                                         IO::print("%d of %d target%s built\033[1G", count, total, (total!=1 ? "s" : ""));
491                         }
492                         else if(tasks.empty())
493                                 finish = true;
494                         else
495                                 starved = true;
496                 }
497                 else
498                         Time::sleep(10*Time::msec);
499
500                 for(unsigned i=0; i<tasks.size();)
501                 {
502                         Task::Status status;
503                         if(jobs==1 || (tasks.size()==1 && starved))
504                                 status = tasks[i]->wait();
505                         else
506                                 status = tasks[i]->check();
507
508                         if(status!=Task::RUNNING)
509                         {
510                                 ++count;
511
512                                 delete tasks[i];
513                                 tasks.erase(tasks.begin()+i);
514                                 if(status==Task::ERROR)
515                                         fail = true;
516                                 if(tasks.empty() && fail)
517                                         finish = true;
518                                 starved = false;
519                         }
520                         else
521                                 ++i;
522                 }
523         }
524
525         if(show_progress)
526                 IO::print("\033[K");
527         if(fail)
528                 logger.log("summary", "Build failed");
529         else if(show_progress)
530                 logger.log("summary", "Build complete");
531
532         if(!dry_run)
533         {
534                 const PackageManager::PackageMap &packages = package_manager.get_packages();
535                 for(PackageManager::PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
536                         i->second->save_caches();
537         }
538
539         return fail;
540 }
541
542 int Builder::do_clean()
543 {
544         // Cleaning doesn't care about ordering, so a simpler method can be used
545
546         set<Target *> clean_tgts;
547         list<Target *> queue;
548         queue.push_back(get_target("cmdline"));
549
550         while(!queue.empty())
551         {
552                 Target *tgt = queue.front();
553                 queue.erase(queue.begin());
554
555                 if(tgt->is_buildable() && (tgt->get_package()==main_pkg || clean>=2))
556                         clean_tgts.insert(tgt);
557
558                 const Target::Dependencies &deps = tgt->get_dependencies();
559                 for(list<Target *>::const_iterator i=deps.begin(); i!=deps.end(); ++i)
560                         if(!clean_tgts.count(*i))
561                                 queue.push_back(*i);
562         }
563
564         for(set<Target *>::iterator i=clean_tgts.begin(); i!=clean_tgts.end(); ++i)
565         {
566                 logger.log("tasks", format("RM    %s", (*i)->get_name()));
567                 if(!dry_run)
568                         (*i)->clean();
569         }
570
571         return 0;
572 }
573
574 void Builder::package_help()
575 {
576         const Config &config = main_pkg->get_config();
577         const Config::OptionMap &options = config.get_options();
578
579         IO::print("Required packages:\n  ");
580         const Package::Requirements &requires = main_pkg->get_required_packages();
581         for(Package::Requirements::const_iterator i=requires.begin(); i!=requires.end(); ++i)
582         {
583                 if(i!=requires.begin())
584                         IO::print(", ");
585                 IO::print((*i)->get_name());
586         }
587         IO::print("\n\nPackage configuration:\n");
588         for(Config::OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
589         {
590                 const Config::Option &opt = i->second;
591                 IO::print("  %s: %s (%s)", opt.name, opt.description, opt.value);
592                 if(opt.value!=opt.default_value)
593                         IO::print(" [%s]", opt.default_value);
594                 IO::print("\n");
595         }
596 }
597
598 string Builder::usagemsg;
599 string Builder::helpmsg;
600
601
602 Builder::Loader::Loader(Builder &b):
603         DataFile::ObjectLoader<Builder>(b)
604 {
605         add("architecture", &Loader::architecture);
606         add("binary_package", &Loader::binpkg);
607         add("build_type", &Loader::build_type);
608         add("profile", &Loader::profile);
609         add("package", &Loader::package);
610 }
611
612 void Builder::Loader::architecture(const string &n)
613 {
614         if(obj.current_arch->match_name(n))
615                 load_sub(*obj.current_arch);
616 }
617
618 void Builder::Loader::binpkg(const string &n)
619 {
620         BinaryPackage *pkg = new BinaryPackage(obj, n);
621         load_sub(*pkg);
622 }
623
624 void Builder::Loader::build_type(const string &n)
625 {
626         BuildType btype(n);
627         load_sub(btype);
628         BuildTypeMap::iterator i = obj.build_types.insert(BuildTypeMap::value_type(n, btype)).first;
629         if(!obj.build_type)
630                 obj.build_type = &i->second;
631 }
632
633 void Builder::Loader::profile(const string &)
634 {
635         IO::print("Profiles are deprecated\n");
636 }
637
638 void Builder::Loader::package(const string &n)
639 {
640         SourcePackage *pkg = new SourcePackage(obj, n, get_source());
641         if(!obj.main_pkg)
642                 obj.main_pkg = pkg;
643
644         if(obj.conf_all || pkg==obj.main_pkg)
645                 load_sub(*pkg, obj.cmdline_options);
646         else
647                 load_sub(*pkg);
648
649         if(obj.build_type)
650                 pkg->set_build_type(*obj.build_type);
651 }