]> git.tdb.fi Git - builder.git/blob - source/builder.cpp
Replace the overly generic configuration profiles with something more purposeful
[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         build_type(0),
41         vfs(*this),
42         analyzer(0),
43         build(false),
44         clean(0),
45         dry_run(false),
46         help(false),
47         show_progress(false),
48         build_file("Build"),
49         jobs(1),
50         conf_all(false),
51         conf_only(false),
52         build_all(false),
53         create_makefile(false)
54 {
55         string analyze_mode;
56         string work_dir;
57         bool full_paths = false;
58         unsigned max_depth = 5;
59         StringList cmdline_warn;
60         string prfx;
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 analysis.  MODE can be deps, alldeps or rebuild.", "MODE");
70         getopt.add_option('b', "build",      build,         GetOpt::NO_ARG).set_help("Perform build even if doing analysis.");
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 info from FILE instead of Build.", "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 NUM commands at once, whenever possible.", "NUM");
75         getopt.add_option('l', "log",        log_channels,  GetOpt::REQUIRED_ARG).set_help("Set log channels to be displayed.", "LIST");
76         getopt.add_option('n', "dry-run",    dry_run,       GetOpt::NO_ARG).set_help("Don't actually do anything, only show what would be done.");
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("Architecture to build for.", "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("Maximum depth to show in analysis.", "NUM");
90         getopt.add_option(     "prefix",     prfx,          GetOpt::REQUIRED_ARG).set_help("Directory to install things to.", "DIR");
91         getopt.add_option(     "warnings",   cmdline_warn,  GetOpt::REQUIRED_ARG).set_help("Compiler warnings to use.", "LIST");
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("packagemgr");
112                 logger.enable_channel("configure");
113         }
114         if(verbose>=4)
115         {
116                 logger.enable_channel("files");
117                 logger.enable_channel("auxcommands");
118         }
119         if(verbose>=5)
120         {
121                 logger.enable_channel("tools");
122                 logger.enable_channel("vfs");
123         }
124         for(list<string>::const_iterator i=log_channels.begin(); i!=log_channels.end(); ++i)
125         {
126                 vector<string> parts = split(*i, ',');
127                 for(vector<string>::const_iterator j=parts.begin(); j!=parts.end(); ++j)
128                         logger.enable_channel(*j);
129         }
130
131         if(!analyze_mode.empty())
132         {
133                 analyzer = new Analyzer(*this);
134
135                 if(analyze_mode=="deps")
136                         analyzer->set_mode(Analyzer::DEPS);
137                 else if(analyze_mode=="alldeps")
138                         analyzer->set_mode(Analyzer::ALLDEPS);
139                 else if(analyze_mode=="rebuild")
140                         analyzer->set_mode(Analyzer::REBUILD);
141                 else if(analyze_mode=="rdeps")
142                         analyzer->set_mode(Analyzer::RDEPS);
143                 else
144                         throw usage_error("Invalid analyze mode");
145
146                 analyzer->set_max_depth(max_depth);
147                 analyzer->set_full_paths(full_paths);
148         }
149         else if(!clean && !create_makefile)
150                 build = true;
151
152         const vector<string> &args = getopt.get_args();
153         for(vector<string>::const_iterator i=args.begin(); i!=args.end(); ++i)
154         {
155                 string::size_type equal = i->find('=');
156                 if(equal!=string::npos)
157                         cmdline_options.insert(StringMap::value_type(i->substr(0, equal), i->substr(equal+1)));
158                 else
159                         cmdline_targets.push_back(*i);
160         }
161
162         if(cmdline_targets.empty())
163                 cmdline_targets.push_back("default");
164
165         if(!work_dir.empty())
166                 FS::chdir(work_dir);
167
168         cwd = FS::getcwd();
169
170         package_manager.set_no_externals(no_externals);
171
172         if(arch.empty())
173                 current_arch = &native_arch;
174         else
175                 current_arch = new Architecture(*this, arch);
176
177         load_build_file((FS::get_sys_data_dir(argv[0], "builder")/"builderrc").str());
178         load_build_file((FS::get_user_data_dir("builder")/"rc").str());
179
180         if(prfx.empty())
181         {
182                 if(current_arch->is_native())
183                         prefix = (FS::get_home_dir()/"local").str();
184                 else
185                         prefix = (FS::get_home_dir()/"local"/current_arch->get_name()).str();
186         }
187         else
188                 prefix = FS::getcwd()/prfx;
189
190         if(!build_type_name.empty())
191         {
192                 BuildTypeMap::iterator i = build_types.find(build_type_name);
193                 if(i==build_types.end())
194                         throw usage_error("Unknown build type");
195                 build_type = &i->second;
196         }
197
198         warnings.push_back("all");
199         warnings.push_back("extra");
200         warnings.push_back("shadow");
201         warnings.push_back("pointer-arith");
202         warnings.push_back("error");
203         for(StringList::iterator i=cmdline_warn.begin(); i!=cmdline_warn.end(); ++i)
204         {
205                 vector<string> warns = split(*i, ',');
206                 warnings.insert(warnings.end(), warns.begin(), warns.end());
207         }
208
209         toolchain.add_tool(new GnuCCompiler(*this, *current_arch));
210         toolchain.add_tool(new GnuCxxCompiler(*this, *current_arch));
211         toolchain.add_tool(new GnuLinker(*this, *current_arch));
212         toolchain.add_tool(new GnuArchiver(*this, *current_arch));
213         toolchain.add_tool(new Copy(*this));
214         toolchain.add_tool(new Tar(*this));
215         toolchain.add_tool(new PkgConfigGenerator(*this));
216 }
217
218 Builder::~Builder()
219 {
220         for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
221                 delete i->second;
222         delete analyzer;
223 }
224
225 int Builder::main()
226 {
227         if(prefix.str()!="/usr")
228         {
229                 FS::Path pcdir = prefix/"lib"/"pkgconfig";
230                 if(const char *pcp = getenv("PKG_CONFIG_PATH"))
231                 {
232                         vector<string> path = split(pcp, ':');
233                         bool found = false;
234                         for(vector<string>::const_iterator i=path.begin(); (!found && i!=path.end()); ++i)
235                                 found = (*i==pcdir.str());
236                         if(!found)
237                         {
238                                 path.push_back(pcdir.str());
239                                 setenv("PKG_CONFIG_PATH", join(path.begin(), path.end(), ":").c_str(), true);
240                         }
241                 }
242                 else
243                         setenv("PKG_CONFIG_PATH", pcdir.str().c_str(), true);
244         }
245
246         if(load_build_file(cwd/build_file))
247         {
248                 if(help)
249                 {
250                         usage(0, "builder", false);
251                         return 0;
252                 }
253                 else
254                 {
255                         IO::print(IO::cerr, "No build info here.\n");
256                         return 1;
257                 }
258         }
259
260         main_pkg->configure(cmdline_options, conf_all?2:1);
261
262         if(help)
263         {
264                 usage(0, "builder", false);
265                 IO::print("\n");
266                 package_help();
267                 return 0;
268         }
269
270         if(conf_only)
271                 return 0;
272
273         if(create_targets())
274                 return 1;
275
276         logger.log("environment", format("Building on %s, for %s%s", native_arch.get_name(),
277                 current_arch->get_name(), (current_arch->is_native() ? " (native)" : "")));
278         logger.log("environment", format("Prefix is %s", prefix));
279         if(build_type)
280                 logger.log("environment", format("Build type is %s", build_type->get_name()));
281
282         const PackageManager::PackageMap &packages = package_manager.get_packages();
283         list<string> package_details;
284         for(PackageManager::PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
285         {
286                 if(!i->second || !i->second->is_configured())
287                         continue;
288
289                 string line = i->second->get_name();
290                 if(dynamic_cast<SourcePackage *>(i->second))
291                 {
292                         line += '*';
293
294                         unsigned count = 0;
295                         unsigned to_be_built = 0;
296                         for(TargetMap::iterator j=targets.begin(); j!=targets.end(); ++j)
297                                 if(j->second->get_package()==i->second)
298                                 {
299                                         ++count;
300                                         if(j->second->needs_rebuild())
301                                                 ++to_be_built;
302                                 }
303                         if(count)
304                         {
305                                 line += format(" (%d targets", count);
306                                 if(to_be_built)
307                                         line += format(", %d to be built", to_be_built);
308                                 line += ')';
309                         }
310                 }
311
312                 package_details.push_back(line);
313         }
314
315         logger.log("summary", format("%d active packages, %d targets", package_details.size(), targets.size()));
316         for(list<string>::const_iterator i=package_details.begin(); i!=package_details.end(); ++i)
317                 logger.log("packages", *i);
318
319         if(analyzer)
320                 analyzer->analyze();
321
322         if(!problems.empty())
323         {
324                 IO::print(IO::cerr, "The following problems were detected:\n");
325                 for(ProblemList::iterator i=problems.begin(); i!=problems.end(); ++i)
326                         IO::print(IO::cerr, "  %s: %s\n", i->package, i->descr);
327                 if(!analyzer)
328                         IO::print(IO::cerr, "Please fix them and try again.\n");
329                 return 1;
330         }
331
332         if(clean)
333                 exit_code = do_clean();
334         else if(build)
335                 exit_code = do_build();
336
337         return exit_code;
338 }
339
340 Target *Builder::get_target(const string &n) const
341 {
342         TargetMap::const_iterator i = targets.find(n);
343         if(i!=targets.end())
344                 return i->second;
345         return 0;
346 }
347
348 void Builder::problem(const string &p, const string &d)
349 {
350         problems.push_back(Problem(p, d));
351 }
352
353 void Builder::add_target(Target *t)
354 {
355         targets.insert(TargetMap::value_type(t->get_name(), t));
356 }
357
358 void Builder::usage(const char *reason, const char *argv0, bool brief)
359 {
360         if(reason)
361                 IO::print(IO::cerr, "%s\n", reason);
362
363         if(brief)
364                 IO::print(IO::cerr, "Usage: %s\n", usagemsg);
365         else
366         {
367                 IO::print(IO::cerr, "Builder 1.0\n\n");
368                 IO::print(IO::cerr, "Usage: %s [options] [<target> ...]\n\n", argv0);
369                 IO::print(IO::cerr, "Options:\n");
370                 IO::print(IO::cerr, helpmsg);
371         }
372 }
373
374 int Builder::load_build_file(const FS::Path &fn)
375 {
376         if(!FS::exists(fn))
377                 return -1;
378
379         IO::BufferedFile in(fn.str());
380
381         logger.log("files", format("Reading %s", fn));
382
383         DataFile::Parser parser(in, fn.str());
384         Loader loader(*this, fn.subpath(0, fn.size()-1));
385         loader.load(parser);
386
387         return 0;
388 }
389
390 int Builder::create_targets()
391 {
392         Target *world = new VirtualTarget(*this, "world");
393
394         Target *def_tgt = new VirtualTarget(*this, "default");
395         world->add_depend(*def_tgt);
396
397         Target *install = new VirtualTarget(*this, "install");
398         world->add_depend(*install);
399
400         Target *tarballs = new VirtualTarget(*this, "tarballs");
401         world->add_depend(*tarballs);
402
403         const PackageManager::PackageMap &packages = package_manager.get_packages();
404         for(PackageManager::PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
405                 if(i->second && i->second->is_configured())
406                         i->second->create_targets();
407
408         // Make the cmdline target depend on all targets mentioned on the command line
409         Target *cmdline = new VirtualTarget(*this, "cmdline");
410         for(list<string>::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
411         {
412                 Target *tgt = get_target(*i);
413                 if(!tgt)
414                         tgt = vfs.get_target(*i);
415                 if(!tgt)
416                         tgt = vfs.get_target(cwd/ *i);
417                 if(!tgt)
418                 {
419                         IO::print("I don't know anything about %s\n", *i);
420                         return -1;
421                 }
422
423                 cmdline->add_depend(*tgt);
424         }
425
426         cmdline->prepare();
427
428         // Apply what-ifs
429         for(StringList::iterator i=what_if.begin(); i!=what_if.end(); ++i)
430         {
431                 FileTarget *tgt = vfs.get_target(cwd/ *i);
432                 if(!tgt)
433                 {
434                         IO::print(IO::cerr, "Unknown what-if target %s\n", *i);
435                         return -1;
436                 }
437                 tgt->touch();
438         }
439
440         if(build_all)
441         {
442                 for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
443                         if(i->second->is_buildable() && !i->second->needs_rebuild())
444                                 i->second->force_rebuild();
445         }
446
447         if(!dry_run)
448         {
449                 for(PackageManager::PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
450                         i->second->save_caches();
451         }
452
453         return 0;
454 }
455
456 int Builder::do_build()
457 {
458         Target *cmdline = get_target("cmdline");
459
460         unsigned total = 0;
461         for(map<string, Target *>::const_iterator i=targets.begin(); i!=targets.end(); ++i)
462                 if(i->second->is_buildable() && i->second->needs_rebuild())
463                         ++total;
464
465         if(!total)
466         {
467                 logger.log("summary", "Already up to date");
468                 return 0;
469         }
470         logger.log("summary", format("Will build %d target%s", total, (total!=1 ? "s" : "")));
471
472         vector<Task *> tasks;
473
474         unsigned count = 0;
475
476         bool fail = false;
477         bool finish = false;
478
479         while(!finish)
480         {
481                 if(tasks.size()<jobs && !fail)
482                 {
483                         Target *tgt = cmdline->get_buildable_target();
484                         if(tgt)
485                         {
486                                 if(tgt->get_tool())
487                                         logger.log("tasks", format("%-4s  %s", tgt->get_tool()->get_tag(), tgt->get_name()));
488                                 Task *task = tgt->build();
489                                 if(task)
490                                 {
491                                         logger.log("commands", format("%s", task->get_command()));
492                                         if(dry_run)
493                                         {
494                                                 task->signal_finished.emit(true);
495                                                 delete task;
496                                         }
497                                         else
498                                         {
499                                                 task->start();
500                                                 tasks.push_back(task);
501                                         }
502                                 }
503
504                                 if(show_progress)
505                                         IO::print("%d of %d target%s built\033[1G", count, total, (total!=1 ? "s" : ""));
506                         }
507                         else if(tasks.empty())
508                                 finish = true;
509                 }
510                 else
511                         Time::sleep(10*Time::msec);
512
513                 for(unsigned i=0; i<tasks.size();)
514                 {
515                         Task::Status status = tasks[i]->check();
516                         if(status!=Task::RUNNING)
517                         {
518                                 ++count;
519
520                                 delete tasks[i];
521                                 tasks.erase(tasks.begin()+i);
522                                 if(status==Task::ERROR)
523                                         fail = true;
524                                 if(tasks.empty() && fail)
525                                         finish = true;
526                         }
527                         else
528                                 ++i;
529                 }
530         }
531
532         if(show_progress)
533                 IO::print("\033[K");
534         if(fail)
535                 logger.log("summary", "Build failed");
536         else if(show_progress)
537                 logger.log("summary", "Build complete");
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_depends();
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                 if(FileTarget *ft = dynamic_cast<FileTarget *>(*i))
566                         if(ft->get_mtime())
567                                 FS::unlink(ft->get_path());
568
569         return 0;
570 }
571
572 void Builder::package_help()
573 {
574         const Config &config = main_pkg->get_config();
575         const Config::OptionMap &options = config.get_options();
576
577         IO::print("Required packages:\n  ");
578         const PackageList &requires = main_pkg->get_requires();
579         for(PackageList::const_iterator i=requires.begin(); i!=requires.end(); ++i)
580         {
581                 if(i!=requires.begin())
582                         IO::print(", ");
583                 IO::print((*i)->get_name());
584         }
585         IO::print("\n\nPackage configuration:\n");
586         for(Config::OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
587         {
588                 const Config::Option &opt = i->second;
589                 IO::print("  %s: %s (%s)", opt.name, opt.descr, opt.value);
590                 if(opt.value!=opt.defv)
591                         IO::print(" [%s]", opt.defv);
592                 IO::print("\n");
593         }
594 }
595
596 string Builder::usagemsg;
597 string Builder::helpmsg;
598
599
600 Builder::Loader::Loader(Builder &b, const FS::Path &s):
601         DataFile::ObjectLoader<Builder>(b),
602         src(s)
603 {
604         add("architecture", &Loader::architecture);
605         add("binary_package", &Loader::binpkg);
606         add("build_type", &Loader::build_type);
607         add("profile", &Loader::profile);
608         add("package", &Loader::package);
609 }
610
611 void Builder::Loader::architecture(const string &n)
612 {
613         if(obj.current_arch->match_name(n))
614                 load_sub(*obj.current_arch);
615 }
616
617 void Builder::Loader::binpkg(const string &n)
618 {
619         BinaryPackage *pkg = new BinaryPackage(obj, n);
620         load_sub(*pkg);
621 }
622
623 void Builder::Loader::build_type(const string &n)
624 {
625         BuildType btype(n);
626         load_sub(btype);
627         BuildTypeMap::iterator i = obj.build_types.insert(BuildTypeMap::value_type(n, btype)).first;
628         if(!obj.build_type)
629                 obj.build_type = &i->second;
630 }
631
632 void Builder::Loader::profile(const string &)
633 {
634         IO::print("Profiles are deprecated\n");
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         if(obj.build_type)
645                 pkg->set_build_type(*obj.build_type);
646 }