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