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