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