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