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