]> git.tdb.fi Git - builder.git/blob - source/builder.cpp
Build and install import libraries on windows
[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 "mingwdlltool.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 = 4;
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(Config::InputOptions::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.append_package_path(cwd);
162         package_manager.append_package_path(cwd/"..");
163         package_manager.append_binary_package_path(FS::get_sys_data_dir(argv[0], "builder"));
164
165         package_manager.set_no_externals(no_externals);
166
167         if(arch.empty())
168                 current_arch = &native_arch;
169         else
170                 current_arch = new Architecture(*this, arch);
171
172         list<FS::Path> start_files;
173         start_files.push_back(FS::get_sys_data_dir(argv[0], "builder")/"builderrc");
174         start_files.push_back(FS::get_user_data_dir("builder")/"rc");
175         for(list<FS::Path>::const_iterator i=start_files.begin(); i!=start_files.end(); ++i)
176                 if(FS::exists(*i))
177                         load_build_file(*i);
178
179         if(prfx.empty())
180         {
181                 if(current_arch->is_native())
182                         prefix = (FS::get_home_dir()/"local").str();
183                 else
184                         prefix = (FS::get_home_dir()/"local"/current_arch->get_name()).str();
185         }
186         else
187                 prefix = cwd/prfx;
188
189         if(!temp_str.empty())
190                 tempdir = temp_str;
191
192         if(!build_type_name.empty())
193         {
194                 BuildTypeMap::iterator i = build_types.find(build_type_name);
195                 if(i==build_types.end())
196                         throw usage_error("Unknown build type");
197                 build_type = &i->second;
198         }
199
200         toolchain.add_tool(new GnuCCompiler(*this, *current_arch));
201         toolchain.add_tool(new GnuCxxCompiler(*this, *current_arch));
202         toolchain.add_tool(new GnuLinker(*this, *current_arch));
203         toolchain.add_tool(new GnuArchiver(*this, *current_arch));
204         toolchain.add_tool(new Copy(*this));
205         toolchain.add_tool(new Tar(*this));
206         toolchain.add_tool(new PkgConfigGenerator(*this));
207         if(current_arch->get_system()=="windows")
208                 toolchain.add_tool(new MingwDllTool(*this, *current_arch));
209 }
210
211 Builder::~Builder()
212 {
213         for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
214                 delete i->second;
215         delete analyzer;
216 }
217
218 int Builder::main()
219 {
220         FS::Path main_file = cwd/build_file;
221         if(!FS::exists(main_file))
222         {
223                 if(help)
224                 {
225                         usage(0, "builder", false);
226                         return 0;
227                 }
228                 else
229                 {
230                         IO::print(IO::cerr, "The file %s does not exist.\n", main_file);
231                         return 1;
232                 }
233         }
234
235         load_build_file(main_file);
236
237         if(help)
238         {
239                 usage(0, "builder", false);
240                 IO::print("\n");
241                 package_help();
242                 return 0;
243         }
244
245         if(!prepare_build())
246                 return 1;
247
248         if(conf_only)
249                 return 0;
250
251         logger.log("environment", format("Building on %s, for %s%s", native_arch.get_name(),
252                 current_arch->get_name(), (current_arch->is_native() ? " (native)" : "")));
253         logger.log("environment", format("Prefix is %s", prefix));
254         if(tempdir.is_absolute())
255                 logger.log("environment", format("Temporary directory is %s", tempdir));
256         else
257                 logger.log("environment", format("Using per-package temporary directory %s", tempdir));
258         if(build_type)
259                 logger.log("environment", format("Build type is %s", build_type->get_name()));
260
261         const PackageManager::PackageMap &packages = package_manager.get_packages();
262         list<string> package_details;
263         for(PackageManager::PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
264         {
265                 if(!i->second->is_prepared())
266                         continue;
267
268                 string line = i->second->get_name();
269                 if(dynamic_cast<SourcePackage *>(i->second))
270                 {
271                         line += '*';
272
273                         unsigned count = 0;
274                         unsigned to_be_built = 0;
275                         for(TargetMap::iterator j=targets.begin(); j!=targets.end(); ++j)
276                                 if(j->second->get_package()==i->second)
277                                 {
278                                         ++count;
279                                         if(j->second->needs_rebuild())
280                                                 ++to_be_built;
281                                 }
282                         if(count)
283                         {
284                                 line += format(" (%d targets", count);
285                                 if(to_be_built)
286                                         line += format(", %d to be built", to_be_built);
287                                 line += ')';
288                         }
289                 }
290
291                 package_details.push_back(line);
292         }
293
294         logger.log("summary", format("%d active packages, %d targets", package_details.size(), targets.size()));
295         for(list<string>::const_iterator i=package_details.begin(); i!=package_details.end(); ++i)
296                 logger.log("packages", *i);
297
298         if(analyzer)
299                 analyzer->analyze();
300
301         if(!problems.empty())
302         {
303                 IO::print(IO::cerr, "The following problems were detected:\n");
304                 for(ProblemList::iterator i=problems.begin(); i!=problems.end(); ++i)
305                         IO::print(IO::cerr, "  %s: %s\n", i->package, i->descr);
306                 if(!analyzer)
307                         IO::print(IO::cerr, "Please fix them and try again.\n");
308                 return 1;
309         }
310
311         if(clean)
312                 exit_code = do_clean();
313         if(build)
314                 exit_code = do_build();
315
316         return exit_code;
317 }
318
319 Target *Builder::get_target(const string &n) const
320 {
321         TargetMap::const_iterator i = targets.find(n);
322         if(i!=targets.end())
323                 return i->second;
324         return 0;
325 }
326
327 void Builder::problem(const string &p, const string &d)
328 {
329         problems.push_back(Problem(p, d));
330 }
331
332 void Builder::add_target(Target *t)
333 {
334         targets.insert(TargetMap::value_type(t->get_name(), t));
335 }
336
337 void Builder::add_primary_target(Target &t)
338 {
339         get_target("world")->add_dependency(t);
340
341         if(t.get_package()==main_pkg && t.get_component() && t.get_component()->is_default())
342                 get_target("default")->add_dependency(t);
343 }
344
345 void Builder::add_installed_target(Target &t)
346 {
347         Target *inst_tgt = 0;
348         if(const Tool *tool = t.get_tool())
349                 inst_tgt = tool->create_install(t);
350         if(!inst_tgt)
351                 inst_tgt = toolchain.get_tool("CP").create_target(t);
352         get_target("install")->add_dependency(*inst_tgt);
353 }
354
355 void Builder::usage(const char *reason, const char *argv0, bool brief)
356 {
357         if(reason)
358                 IO::print(IO::cerr, "%s\n", reason);
359
360         if(brief)
361                 IO::print(IO::cerr, "Usage: %s\n", usagemsg);
362         else
363         {
364                 IO::print(IO::cerr, "Builder 1.0\n\n");
365                 IO::print(IO::cerr, "Usage: %s [options] [<target> ...]\n\n", argv0);
366                 IO::print(IO::cerr, "Options:\n");
367                 IO::print(IO::cerr, helpmsg);
368         }
369 }
370
371 void Builder::load_build_file(const FS::Path &fn)
372 {
373         IO::BufferedFile in(fn.str());
374
375         logger.log("files", format("Reading %s", fn));
376
377         DataFile::Parser parser(in, fn.str());
378         Loader loader(*this);
379         loader.load(parser);
380 }
381
382 bool Builder::prepare_build()
383 {
384         Target *world = new VirtualTarget(*this, "world");
385
386         Target *def_tgt = new VirtualTarget(*this, "default");
387         world->add_dependency(*def_tgt);
388
389         Target *install = new VirtualTarget(*this, "install");
390         world->add_dependency(*install);
391
392         Target *tarballs = new VirtualTarget(*this, "tarballs");
393         world->add_dependency(*tarballs);
394
395         main_pkg->prepare();
396
397         // Make the cmdline target depend on all targets mentioned on the command line
398         Target *cmdline = new VirtualTarget(*this, "cmdline");
399         for(NameList::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
400         {
401                 Target *tgt = get_target(*i);
402                 if(!tgt)
403                         tgt = vfs.get_target(*i);
404                 if(!tgt)
405                         tgt = vfs.get_target(cwd/ *i);
406                 if(!tgt)
407                 {
408                         IO::print("I don't know anything about %s\n", *i);
409                         return false;
410                 }
411
412                 cmdline->add_dependency(*tgt);
413         }
414
415         cmdline->prepare();
416
417         // Apply what-ifs
418         for(NameList::iterator i=what_if.begin(); i!=what_if.end(); ++i)
419         {
420                 FileTarget *tgt = vfs.get_target(cwd/ *i);
421                 if(!tgt)
422                 {
423                         IO::print(IO::cerr, "Unknown what-if target %s\n", *i);
424                         return false;
425                 }
426                 tgt->touch();
427         }
428
429         if(build_all)
430         {
431                 for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
432                         if(i->second->is_buildable() && !i->second->needs_rebuild())
433                                 i->second->force_rebuild();
434         }
435
436         if(!dry_run)
437         {
438                 const PackageManager::PackageMap &packages = package_manager.get_packages();
439                 for(PackageManager::PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
440                         i->second->save_caches();
441         }
442
443         return true;
444 }
445
446 int Builder::do_build()
447 {
448         Target *cmdline = get_target("cmdline");
449
450         unsigned total = 0;
451         for(map<string, Target *>::const_iterator i=targets.begin(); i!=targets.end(); ++i)
452                 if(i->second->is_buildable() && i->second->needs_rebuild())
453                         ++total;
454
455         if(!total)
456         {
457                 logger.log("summary", "Already up to date");
458                 return 0;
459         }
460         logger.log("summary", format("Will build %d target%s", total, (total!=1 ? "s" : "")));
461
462         vector<Task *> tasks;
463
464         unsigned count = 0;
465
466         bool fail = false;
467         bool finish = false;
468         bool starved = false;
469
470         while(!finish)
471         {
472                 if(tasks.size()<jobs && !fail && !starved)
473                 {
474                         Target *tgt = cmdline->get_buildable_target();
475                         if(tgt)
476                         {
477                                 if(tgt->get_tool())
478                                         logger.log("tasks", format("%-4s  %s", tgt->get_tool()->get_tag(), tgt->get_name()));
479                                 Task *task = tgt->build();
480                                 if(task)
481                                 {
482                                         logger.log("commands", format("%s", task->get_command()));
483                                         if(dry_run)
484                                         {
485                                                 task->signal_finished.emit(true);
486                                                 delete task;
487                                         }
488                                         else
489                                         {
490                                                 task->start();
491                                                 tasks.push_back(task);
492                                         }
493                                 }
494
495                                 if(show_progress)
496                                         IO::print("%d of %d target%s built\033[1G", count, total, (total!=1 ? "s" : ""));
497                         }
498                         else if(tasks.empty())
499                                 finish = true;
500                         else
501                                 starved = true;
502                 }
503                 else
504                         Time::sleep(10*Time::msec);
505
506                 for(unsigned i=0; i<tasks.size();)
507                 {
508                         Task::Status status;
509                         if(jobs==1 || (tasks.size()==1 && starved))
510                                 status = tasks[i]->wait();
511                         else
512                                 status = tasks[i]->check();
513
514                         if(status!=Task::RUNNING)
515                         {
516                                 ++count;
517
518                                 delete tasks[i];
519                                 tasks.erase(tasks.begin()+i);
520                                 if(status==Task::ERROR)
521                                         fail = true;
522                                 if(tasks.empty() && fail)
523                                         finish = true;
524                                 starved = false;
525                         }
526                         else
527                                 ++i;
528                 }
529         }
530
531         if(show_progress)
532                 IO::print("\033[K");
533         if(fail)
534                 logger.log("summary", "Build failed");
535         else if(show_progress)
536                 logger.log("summary", "Build complete");
537
538         if(!dry_run)
539         {
540                 const PackageManager::PackageMap &packages = package_manager.get_packages();
541                 for(PackageManager::PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
542                         i->second->save_caches();
543         }
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_dependencies();
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         {
572                 logger.log("tasks", format("RM    %s", (*i)->get_name()));
573                 if(!dry_run)
574                         (*i)->clean();
575         }
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 Package::Requirements &requires = main_pkg->get_required_packages();
587         for(Package::Requirements::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.description, opt.value);
598                 if(opt.value!=opt.default_value)
599                         IO::print(" [%s]", opt.default_value);
600                 IO::print("\n");
601         }
602 }
603
604 string Builder::usagemsg;
605 string Builder::helpmsg;
606
607
608 Builder::Loader::Loader(Builder &b):
609         DataFile::ObjectLoader<Builder>(b)
610 {
611         add("architecture", &Loader::architecture);
612         add("binary_package", &Loader::binpkg);
613         add("build_type", &Loader::build_type);
614         add("profile", &Loader::profile);
615         add("package", &Loader::package);
616 }
617
618 void Builder::Loader::architecture(const string &n)
619 {
620         if(obj.current_arch->match_name(n))
621                 load_sub(*obj.current_arch);
622 }
623
624 void Builder::Loader::binpkg(const string &n)
625 {
626         BinaryPackage *pkg = new BinaryPackage(obj, n);
627         load_sub(*pkg);
628 }
629
630 void Builder::Loader::build_type(const string &n)
631 {
632         BuildType btype(n);
633         load_sub(btype);
634         BuildTypeMap::iterator i = obj.build_types.insert(BuildTypeMap::value_type(n, btype)).first;
635         if(!obj.build_type)
636                 obj.build_type = &i->second;
637 }
638
639 void Builder::Loader::profile(const string &)
640 {
641         IO::print("Profiles are deprecated\n");
642 }
643
644 void Builder::Loader::package(const string &n)
645 {
646         SourcePackage *pkg = new SourcePackage(obj, n, get_source());
647         if(!obj.main_pkg)
648                 obj.main_pkg = pkg;
649
650         if(obj.conf_all || pkg==obj.main_pkg)
651                 load_sub(*pkg, obj.cmdline_options);
652         else
653                 load_sub(*pkg);
654
655         if(obj.build_type)
656                 pkg->set_build_type(*obj.build_type);
657 }