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