]> git.tdb.fi Git - builder.git/blob - source/builder.cpp
Move some more functionality into BuildGraph
[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         native_arch(*this, string()),
39         build_type(0),
40         vfs(*this),
41         build_graph(*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(!work_dir.empty())
154                 FS::chdir(work_dir);
155
156         cwd = FS::getcwd();
157
158         package_manager.append_package_path(cwd);
159         package_manager.append_package_path(cwd/"..");
160         package_manager.append_binary_package_path(FS::get_sys_data_dir(argv[0], "builder"));
161
162         package_manager.set_no_externals(no_externals);
163
164         if(arch.empty())
165                 current_arch = &native_arch;
166         else
167                 current_arch = new Architecture(*this, arch);
168
169         list<FS::Path> start_files;
170         start_files.push_back(FS::get_sys_data_dir(argv[0], "builder")/"builderrc");
171         start_files.push_back(FS::get_user_data_dir("builder")/"rc");
172         for(list<FS::Path>::const_iterator i=start_files.begin(); i!=start_files.end(); ++i)
173                 if(FS::exists(*i))
174                         load_build_file(*i);
175
176         if(prfx.empty())
177         {
178                 if(current_arch->is_native())
179                         prefix = (FS::get_home_dir()/"local").str();
180                 else
181                         prefix = (FS::get_home_dir()/"local"/current_arch->get_name()).str();
182         }
183         else
184                 prefix = cwd/prfx;
185
186         if(!temp_str.empty())
187                 tempdir = temp_str;
188
189         if(!build_type_name.empty())
190         {
191                 BuildTypeMap::iterator i = build_types.find(build_type_name);
192                 if(i==build_types.end())
193                         throw usage_error("Unknown build type");
194                 build_type = &i->second;
195         }
196
197         toolchain.add_tool(new GnuCCompiler(*this, *current_arch));
198         toolchain.add_tool(new GnuCxxCompiler(*this, *current_arch));
199         toolchain.add_tool(new GnuLinker(*this, *current_arch));
200         toolchain.add_tool(new GnuArchiver(*this, *current_arch));
201         toolchain.add_tool(new Copy(*this));
202         toolchain.add_tool(new Tar(*this));
203         toolchain.add_tool(new PkgConfigGenerator(*this));
204         if(current_arch->get_system()=="windows")
205                 toolchain.add_tool(new MingwDllTool(*this, *current_arch));
206 }
207
208 Builder::~Builder()
209 {
210         delete analyzer;
211 }
212
213 int Builder::main()
214 {
215         FS::Path main_file = cwd/build_file;
216         if(!FS::exists(main_file))
217         {
218                 if(help)
219                 {
220                         usage(0, "builder", false);
221                         return 0;
222                 }
223                 else
224                 {
225                         IO::print(IO::cerr, "The file %s does not exist.\n", main_file);
226                         return 1;
227                 }
228         }
229
230         load_build_file(main_file);
231
232         if(help)
233         {
234                 usage(0, "builder", false);
235                 IO::print("\n");
236                 package_help();
237                 return 0;
238         }
239
240         if(!prepare_build())
241                 return 1;
242
243         if(conf_only)
244                 return 0;
245
246         logger.log("environment", format("Building on %s, for %s%s", native_arch.get_name(),
247                 current_arch->get_name(), (current_arch->is_native() ? " (native)" : "")));
248         logger.log("environment", format("Prefix is %s", prefix));
249         if(tempdir.is_absolute())
250                 logger.log("environment", format("Temporary directory is %s", tempdir));
251         else
252                 logger.log("environment", format("Using per-package temporary directory %s", tempdir));
253         if(build_type)
254                 logger.log("environment", format("Build type is %s", build_type->get_name()));
255
256         const PackageManager::PackageMap &packages = package_manager.get_packages();
257         list<string> package_details;
258         for(PackageManager::PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
259         {
260                 if(!i->second->is_prepared())
261                         continue;
262
263                 string line = i->second->get_name();
264                 if(dynamic_cast<SourcePackage *>(i->second))
265                 {
266                         line += '*';
267
268                         unsigned count = 0;
269                         unsigned to_be_built = 0;
270                         const BuildGraph::TargetMap &targets = build_graph.get_targets();
271                         for(BuildGraph::TargetMap::const_iterator j=targets.begin(); j!=targets.end(); ++j)
272                                 if(j->second->get_package()==i->second)
273                                 {
274                                         ++count;
275                                         if(j->second->needs_rebuild())
276                                                 ++to_be_built;
277                                 }
278                         if(count)
279                         {
280                                 line += format(" (%d targets", count);
281                                 if(to_be_built)
282                                         line += format(", %d to be built", to_be_built);
283                                 line += ')';
284                         }
285                 }
286
287                 package_details.push_back(line);
288         }
289
290         logger.log("summary", format("%d active packages, %d targets", package_details.size(), build_graph.get_targets().size()));
291         for(list<string>::const_iterator i=package_details.begin(); i!=package_details.end(); ++i)
292                 logger.log("packages", *i);
293
294         if(analyzer)
295                 analyzer->analyze();
296
297         if(!problems.empty())
298         {
299                 IO::print(IO::cerr, "The following problems were detected:\n");
300                 for(ProblemList::iterator i=problems.begin(); i!=problems.end(); ++i)
301                         IO::print(IO::cerr, "  %s: %s\n", i->package, i->descr);
302                 if(!analyzer)
303                         IO::print(IO::cerr, "Please fix them and try again.\n");
304                 return 1;
305         }
306
307         if(clean)
308                 exit_code = do_clean();
309         if(build)
310                 exit_code = do_build();
311
312         return exit_code;
313 }
314
315 void Builder::problem(const string &p, const string &d)
316 {
317         problems.push_back(Problem(p, d));
318 }
319
320 void Builder::usage(const char *reason, const char *argv0, bool brief)
321 {
322         if(reason)
323                 IO::print(IO::cerr, "%s\n", reason);
324
325         if(brief)
326                 IO::print(IO::cerr, "Usage: %s\n", usagemsg);
327         else
328         {
329                 IO::print(IO::cerr, "Builder 1.0\n\n");
330                 IO::print(IO::cerr, "Usage: %s [options] [<target> ...]\n\n", argv0);
331                 IO::print(IO::cerr, "Options:\n");
332                 IO::print(IO::cerr, helpmsg);
333         }
334 }
335
336 void Builder::load_build_file(const FS::Path &fn)
337 {
338         IO::BufferedFile in(fn.str());
339
340         logger.log("files", format("Reading %s", fn));
341
342         DataFile::Parser parser(in, fn.str());
343         Loader loader(*this);
344         loader.load(parser);
345 }
346
347 bool Builder::prepare_build()
348 {
349         package_manager.get_main_package().prepare();
350
351         // Add targets from command line as goals
352         for(NameList::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
353         {
354                 Target *tgt = build_graph.get_target(*i);
355                 if(!tgt)
356                         tgt = vfs.get_target(*i);
357                 if(!tgt)
358                         tgt = vfs.get_target(cwd/ *i);
359                 if(!tgt)
360                 {
361                         IO::print("I don't know anything about %s\n", *i);
362                         return false;
363                 }
364
365                 build_graph.add_goal(*tgt);
366         }
367
368         build_graph.prepare();
369
370         // Apply what-ifs
371         for(NameList::iterator i=what_if.begin(); i!=what_if.end(); ++i)
372         {
373                 FileTarget *tgt = vfs.get_target(cwd/ *i);
374                 if(!tgt)
375                 {
376                         IO::print(IO::cerr, "Unknown what-if target %s\n", *i);
377                         return false;
378                 }
379                 tgt->touch();
380         }
381
382         if(build_all)
383                 build_graph.force_full_rebuild();
384
385         if(!dry_run)
386         {
387                 const PackageManager::PackageMap &packages = package_manager.get_packages();
388                 for(PackageManager::PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
389                         i->second->save_caches();
390         }
391
392         return true;
393 }
394
395 int Builder::do_build()
396 {
397         unsigned total = build_graph.count_rebuild_targets();
398
399         if(!total)
400         {
401                 logger.log("summary", "Already up to date");
402                 return 0;
403         }
404         logger.log("summary", format("Will build %d target%s", total, (total!=1 ? "s" : "")));
405
406         vector<Task *> tasks;
407
408         unsigned count = 0;
409
410         bool fail = false;
411         bool finish = false;
412         bool starved = false;
413
414         while(!finish)
415         {
416                 if(tasks.size()<jobs && !fail && !starved)
417                 {
418                         Target *tgt = build_graph.get_buildable_target();
419                         if(tgt)
420                         {
421                                 if(tgt->get_tool())
422                                         logger.log("tasks", format("%-4s  %s", tgt->get_tool()->get_tag(), tgt->get_name()));
423                                 Task *task = tgt->build();
424                                 if(task)
425                                 {
426                                         logger.log("commands", format("%s", task->get_command()));
427                                         if(dry_run)
428                                         {
429                                                 task->signal_finished.emit(true);
430                                                 delete task;
431                                         }
432                                         else
433                                         {
434                                                 task->start();
435                                                 tasks.push_back(task);
436                                         }
437                                 }
438
439                                 if(show_progress)
440                                         IO::print("%d of %d target%s built\033[1G", count, total, (total!=1 ? "s" : ""));
441                         }
442                         else if(tasks.empty())
443                                 finish = true;
444                         else
445                                 starved = true;
446                 }
447                 else
448                         Time::sleep(10*Time::msec);
449
450                 for(unsigned i=0; i<tasks.size();)
451                 {
452                         Task::Status status;
453                         if(jobs==1 || (tasks.size()==1 && starved))
454                                 status = tasks[i]->wait();
455                         else
456                                 status = tasks[i]->check();
457
458                         if(status!=Task::RUNNING)
459                         {
460                                 ++count;
461
462                                 delete tasks[i];
463                                 tasks.erase(tasks.begin()+i);
464                                 if(status==Task::ERROR)
465                                         fail = true;
466                                 if(tasks.empty() && fail)
467                                         finish = true;
468                                 starved = false;
469                         }
470                         else
471                                 ++i;
472                 }
473         }
474
475         if(show_progress)
476                 IO::print("\033[K");
477         if(fail)
478                 logger.log("summary", "Build failed");
479         else if(show_progress)
480                 logger.log("summary", "Build complete");
481
482         if(!dry_run)
483         {
484                 const PackageManager::PackageMap &packages = package_manager.get_packages();
485                 for(PackageManager::PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
486                         i->second->save_caches();
487         }
488
489         return fail;
490 }
491
492 int Builder::do_clean()
493 {
494         // Cleaning doesn't care about ordering, so a simpler method can be used
495
496         set<Target *> clean_tgts;
497         list<Target *> queue;
498         queue.push_back(build_graph.get_target("cmdline"));
499
500         while(!queue.empty())
501         {
502                 Target *tgt = queue.front();
503                 queue.erase(queue.begin());
504
505                 if(tgt->is_buildable() && (tgt->get_package()==&package_manager.get_main_package() || clean>=2))
506                         clean_tgts.insert(tgt);
507
508                 const Target::Dependencies &deps = tgt->get_dependencies();
509                 for(list<Target *>::const_iterator i=deps.begin(); i!=deps.end(); ++i)
510                         if(!clean_tgts.count(*i))
511                                 queue.push_back(*i);
512         }
513
514         for(set<Target *>::iterator i=clean_tgts.begin(); i!=clean_tgts.end(); ++i)
515         {
516                 logger.log("tasks", format("RM    %s", (*i)->get_name()));
517                 if(!dry_run)
518                         (*i)->clean();
519         }
520
521         return 0;
522 }
523
524 void Builder::package_help()
525 {
526         SourcePackage &main_pkg = dynamic_cast<SourcePackage &>(package_manager.get_main_package());
527         const Config &config = main_pkg.get_config();
528         const Config::OptionMap &options = config.get_options();
529
530         IO::print("Required packages:\n  ");
531         const Package::Requirements &requires = main_pkg.get_required_packages();
532         for(Package::Requirements::const_iterator i=requires.begin(); i!=requires.end(); ++i)
533         {
534                 if(i!=requires.begin())
535                         IO::print(", ");
536                 IO::print((*i)->get_name());
537         }
538         IO::print("\n\nPackage configuration:\n");
539         for(Config::OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
540         {
541                 const Config::Option &opt = i->second;
542                 IO::print("  %s: %s (%s)", opt.name, opt.description, opt.value);
543                 if(opt.value!=opt.default_value)
544                         IO::print(" [%s]", opt.default_value);
545                 IO::print("\n");
546         }
547 }
548
549 string Builder::usagemsg;
550 string Builder::helpmsg;
551
552
553 Builder::Loader::Loader(Builder &b):
554         DataFile::ObjectLoader<Builder>(b)
555 {
556         add("architecture", &Loader::architecture);
557         add("binary_package", &Loader::binpkg);
558         add("build_type", &Loader::build_type);
559         add("profile", &Loader::profile);
560         add("package", &Loader::package);
561 }
562
563 void Builder::Loader::architecture(const string &n)
564 {
565         if(obj.current_arch->match_name(n))
566                 load_sub(*obj.current_arch);
567 }
568
569 void Builder::Loader::binpkg(const string &n)
570 {
571         BinaryPackage *pkg = new BinaryPackage(obj, n);
572         load_sub(*pkg);
573 }
574
575 void Builder::Loader::build_type(const string &n)
576 {
577         BuildType btype(n);
578         load_sub(btype);
579         BuildTypeMap::iterator i = obj.build_types.insert(BuildTypeMap::value_type(n, btype)).first;
580         if(!obj.build_type)
581                 obj.build_type = &i->second;
582 }
583
584 void Builder::Loader::profile(const string &)
585 {
586         IO::print("Profiles are deprecated\n");
587 }
588
589 void Builder::Loader::package(const string &n)
590 {
591         SourcePackage *pkg = new SourcePackage(obj, n, get_source());
592
593         if(obj.conf_all || pkg==&obj.package_manager.get_main_package())
594                 load_sub(*pkg, obj.cmdline_options);
595         else
596                 load_sub(*pkg);
597
598         if(obj.build_type)
599                 pkg->set_build_type(*obj.build_type);
600 }