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