]> git.tdb.fi Git - builder.git/blob - source/builder.cpp
Include the environment channel in verbose level 2
[builder.git] / source / builder.cpp
1 #include <set>
2 #include <cstdlib>
3 #include <msp/core/getopt.h>
4 #include <msp/datafile/parser.h>
5 #include <msp/fs/dir.h>
6 #include <msp/fs/stat.h>
7 #include <msp/fs/utils.h>
8 #include <msp/io/buffered.h>
9 #include <msp/io/file.h>
10 #include <msp/io/print.h>
11 #include <msp/strings/format.h>
12 #include <msp/strings/regex.h>
13 #include <msp/strings/utils.h>
14 #include <msp/time/units.h>
15 #include <msp/time/utils.h>
16 #include "analyzer.h"
17 #include "binarypackage.h"
18 #include "builder.h"
19 #include "copy.h"
20 #include "gnuarchiver.h"
21 #include "gnuccompiler.h"
22 #include "gnucxxcompiler.h"
23 #include "gnulinker.h"
24 #include "installedfile.h"
25 #include "package.h"
26 #include "pkgconfiggenerator.h"
27 #include "sharedlibrary.h"
28 #include "sourcepackage.h"
29 #include "tar.h"
30 #include "task.h"
31 #include "virtualtarget.h"
32
33 using namespace std;
34 using namespace Msp;
35
36 Builder::Builder(int argc, char **argv):
37         package_manager(*this),
38         main_pkg(0),
39         native_arch(*this, string()),
40         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 {
54         string analyze_mode;
55         string work_dir;
56         bool full_paths = false;
57         unsigned max_depth = 5;
58         StringList cmdline_warn;
59         string prfx;
60         string arch;
61         bool no_externals = false;
62         unsigned verbose = 1;
63         bool silent = false;
64         list<string> log_channels;
65
66         GetOpt getopt;
67         getopt.add_option('a', "analyze",    analyze_mode,  GetOpt::REQUIRED_ARG).set_help("Perform analysis.  MODE can be deps, alldeps or rebuild.", "MODE");
68         getopt.add_option('b', "build",      build,         GetOpt::NO_ARG).set_help("Perform build even if doing analysis.");
69         getopt.add_option('c', "clean",      clean,         GetOpt::NO_ARG).set_help("Clean buildable targets.");
70         getopt.add_option('f', "file",       build_file,    GetOpt::REQUIRED_ARG).set_help("Read info from FILE instead of Build.", "FILE");
71         getopt.add_option('h', "help",       help,          GetOpt::NO_ARG).set_help("Print this message.");
72         getopt.add_option('j', "jobs",       jobs,          GetOpt::REQUIRED_ARG).set_help("Run NUM commands at once, whenever possible.", "NUM");
73         getopt.add_option('l', "log",        log_channels,  GetOpt::REQUIRED_ARG).set_help("Set log channels to be displayed.", "LIST");
74         getopt.add_option('n', "dry-run",    dry_run,       GetOpt::NO_ARG).set_help("Don't actually do anything, only show what would be done.");
75         getopt.add_option('s', "silent",     silent,        GetOpt::NO_ARG).set_help("Don't print any messages other than errors.");
76         getopt.add_option('v', "verbose",    verbose,       GetOpt::NO_ARG).set_help("Print more information about what's going on.");
77         getopt.add_option('x', "no-externals",  no_externals, GetOpt::NO_ARG).set_help("Do not load external source packages.");
78         getopt.add_option('A', "conf-all",   conf_all,      GetOpt::NO_ARG).set_help("Apply configuration to all packages.");
79         getopt.add_option('B', "build-all",  build_all,     GetOpt::NO_ARG).set_help("Build all targets unconditionally.");
80         getopt.add_option('C', "chdir",      work_dir,      GetOpt::REQUIRED_ARG).set_help("Change to DIR before doing anything else.", "DIR");
81         getopt.add_option('P', "progress",   show_progress, GetOpt::NO_ARG).set_help("Display progress while building.");
82         getopt.add_option('W', "what-if",    what_if,       GetOpt::REQUIRED_ARG).set_help("Pretend that FILE has changed.", "FILE");
83         getopt.add_option(     "arch",       arch,          GetOpt::REQUIRED_ARG).set_help("Architecture to build for.", "ARCH");
84         getopt.add_option(     "conf-only",  conf_only,     GetOpt::NO_ARG).set_help("Stop after configuring packages.");
85         getopt.add_option(     "full-paths", full_paths,    GetOpt::NO_ARG).set_help("Output full paths in analysis.");
86         getopt.add_option(     "max-depth",  max_depth,     GetOpt::REQUIRED_ARG).set_help("Maximum depth to show in analysis.", "NUM");
87         getopt.add_option(     "prefix",     prfx,          GetOpt::REQUIRED_ARG).set_help("Directory to install things to.", "DIR");
88         getopt.add_option(     "warnings",   cmdline_warn,  GetOpt::REQUIRED_ARG).set_help("Compiler warnings to use.", "LIST");
89         usagemsg = getopt.generate_usage(argv[0])+" [<target> ...]";
90         helpmsg = getopt.generate_help();
91         getopt(argc, argv);
92
93         if(silent)
94                 --verbose;
95         if(verbose>=1)
96         {
97                 logger.enable_channel("summary");
98                 logger.enable_channel("tasks");
99         }
100         if(verbose>=2)
101         {
102                 logger.enable_channel("environment");
103                 logger.enable_channel("packages");
104                 logger.enable_channel("commands");
105         }
106         if(verbose>=3)
107         {
108                 logger.enable_channel("packagemgr");
109                 logger.enable_channel("configure");
110         }
111         if(verbose>=4)
112         {
113                 logger.enable_channel("files");
114                 logger.enable_channel("auxcommands");
115         }
116         if(verbose>=5)
117         {
118                 logger.enable_channel("tools");
119                 logger.enable_channel("vfs");
120         }
121         for(list<string>::const_iterator i=log_channels.begin(); i!=log_channels.end(); ++i)
122         {
123                 vector<string> parts = split(*i, ',');
124                 for(vector<string>::const_iterator j=parts.begin(); j!=parts.end(); ++j)
125                         logger.enable_channel(*j);
126         }
127
128         if(!analyze_mode.empty())
129         {
130                 analyzer = new Analyzer(*this);
131
132                 if(analyze_mode=="deps")
133                         analyzer->set_mode(Analyzer::DEPS);
134                 else if(analyze_mode=="alldeps")
135                         analyzer->set_mode(Analyzer::ALLDEPS);
136                 else if(analyze_mode=="rebuild")
137                         analyzer->set_mode(Analyzer::REBUILD);
138                 else if(analyze_mode=="rdeps")
139                         analyzer->set_mode(Analyzer::RDEPS);
140                 else
141                         throw usage_error("Invalid analyze mode");
142
143                 analyzer->set_max_depth(max_depth);
144                 analyzer->set_full_paths(full_paths);
145         }
146         else if(!clean && !create_makefile)
147                 build = true;
148
149         const vector<string> &args = getopt.get_args();
150         for(vector<string>::const_iterator i=args.begin(); i!=args.end(); ++i)
151         {
152                 string::size_type equal = i->find('=');
153                 if(equal!=string::npos)
154                         cmdline_options.insert(StringMap::value_type(i->substr(0, equal), i->substr(equal+1)));
155                 else
156                         cmdline_targets.push_back(*i);
157         }
158
159         if(cmdline_targets.empty())
160                 cmdline_targets.push_back("default");
161
162         if(!work_dir.empty())
163                 FS::chdir(work_dir);
164
165         cwd = FS::getcwd();
166
167         package_manager.set_no_externals(no_externals);
168
169         if(arch.empty())
170                 current_arch = &native_arch;
171         else
172                 current_arch = new Architecture(*this, arch);
173
174         load_build_file((FS::get_sys_data_dir(argv[0], "builder")/"builderrc").str());
175         load_build_file((FS::get_user_data_dir("builder")/"rc").str());
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 = FS::getcwd()/prfx;
186
187         warnings.push_back("all");
188         warnings.push_back("extra");
189         warnings.push_back("shadow");
190         warnings.push_back("pointer-arith");
191         warnings.push_back("error");
192         for(StringList::iterator i=cmdline_warn.begin(); i!=cmdline_warn.end(); ++i)
193         {
194                 vector<string> warns = split(*i, ',');
195                 warnings.insert(warnings.end(), warns.begin(), warns.end());
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 }
206
207 Builder::~Builder()
208 {
209         for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
210                 delete i->second;
211         delete analyzer;
212 }
213
214 int Builder::main()
215 {
216         if(prefix.str()!="/usr")
217         {
218                 FS::Path pcdir = prefix/"lib"/"pkgconfig";
219                 if(const char *pcp = getenv("PKG_CONFIG_PATH"))
220                 {
221                         vector<string> path = split(pcp, ':');
222                         bool found = false;
223                         for(vector<string>::const_iterator i=path.begin(); (!found && i!=path.end()); ++i)
224                                 found = (*i==pcdir.str());
225                         if(!found)
226                         {
227                                 path.push_back(pcdir.str());
228                                 setenv("PKG_CONFIG_PATH", join(path.begin(), path.end(), ":").c_str(), true);
229                         }
230                 }
231                 else
232                         setenv("PKG_CONFIG_PATH", pcdir.str().c_str(), true);
233         }
234
235         if(load_build_file(cwd/build_file))
236         {
237                 if(help)
238                 {
239                         usage(0, "builder", false);
240                         return 0;
241                 }
242                 else
243                 {
244                         IO::print(IO::cerr, "No build info here.\n");
245                         return 1;
246                 }
247         }
248
249         main_pkg->configure(cmdline_options, conf_all?2:1);
250
251         if(help)
252         {
253                 usage(0, "builder", false);
254                 IO::print("\n");
255                 package_help();
256                 return 0;
257         }
258
259         if(conf_only)
260                 return 0;
261
262         if(create_targets())
263                 return 1;
264
265         logger.log("environment", format("Building on %s, for %s%s", native_arch.get_name(),
266                 current_arch->get_name(), (current_arch->is_native() ? " (native)" : "")));
267         logger.log("environment", format("Prefix is %s", prefix));
268
269         const PackageManager::PackageMap &packages = package_manager.get_packages();
270         list<string> package_details;
271         for(PackageManager::PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
272         {
273                 if(!i->second || !i->second->is_configured())
274                         continue;
275
276                 string line = i->second->get_name();
277                 if(dynamic_cast<SourcePackage *>(i->second))
278                 {
279                         line += '*';
280
281                         unsigned count = 0;
282                         unsigned to_be_built = 0;
283                         for(TargetMap::iterator j=targets.begin(); j!=targets.end(); ++j)
284                                 if(j->second->get_package()==i->second)
285                                 {
286                                         ++count;
287                                         if(j->second->needs_rebuild())
288                                                 ++to_be_built;
289                                 }
290                         if(count)
291                         {
292                                 line += format(" (%d targets", count);
293                                 if(to_be_built)
294                                         line += format(", %d to be built", to_be_built);
295                                 line += ')';
296                         }
297                 }
298
299                 package_details.push_back(line);
300         }
301
302         logger.log("summary", format("%d active packages, %d targets", package_details.size(), targets.size()));
303         for(list<string>::const_iterator i=package_details.begin(); i!=package_details.end(); ++i)
304                 logger.log("packages", *i);
305
306         if(analyzer)
307                 analyzer->analyze();
308
309         if(!problems.empty())
310         {
311                 IO::print(IO::cerr, "The following problems were detected:\n");
312                 for(ProblemList::iterator i=problems.begin(); i!=problems.end(); ++i)
313                         IO::print(IO::cerr, "  %s: %s\n", i->package, i->descr);
314                 if(!analyzer)
315                         IO::print(IO::cerr, "Please fix them and try again.\n");
316                 return 1;
317         }
318
319         if(clean)
320                 exit_code = do_clean();
321         else if(build)
322                 exit_code = do_build();
323
324         return exit_code;
325 }
326
327 Target *Builder::get_target(const string &n) const
328 {
329         TargetMap::const_iterator i = targets.find(n);
330         if(i!=targets.end())
331                 return i->second;
332         return 0;
333 }
334
335 void Builder::apply_profile_template(Config &config, const string &pt) const
336 {
337         vector<string> parts = split(pt, '-');
338
339         for(vector<string>::iterator i=parts.begin(); i!=parts.end(); ++i)
340         {
341                 ProfileTemplateMap::const_iterator j = profile_tmpl.find(*i);
342                 if(j==profile_tmpl.end())
343                         continue;
344
345                 config.update(j->second);
346         }
347 }
348
349 void Builder::problem(const string &p, const string &d)
350 {
351         problems.push_back(Problem(p, d));
352 }
353
354 void Builder::add_target(Target *t)
355 {
356         targets.insert(TargetMap::value_type(t->get_name(), t));
357 }
358
359 void Builder::usage(const char *reason, const char *argv0, bool brief)
360 {
361         if(reason)
362                 IO::print(IO::cerr, "%s\n", reason);
363
364         if(brief)
365                 IO::print(IO::cerr, "Usage: %s\n", usagemsg);
366         else
367         {
368                 IO::print(IO::cerr, "Builder 1.0\n\n");
369                 IO::print(IO::cerr, "Usage: %s [options] [<target> ...]\n\n", argv0);
370                 IO::print(IO::cerr, "Options:\n");
371                 IO::print(IO::cerr, helpmsg);
372         }
373 }
374
375 int Builder::load_build_file(const FS::Path &fn)
376 {
377         if(!FS::exists(fn))
378                 return -1;
379
380         IO::BufferedFile in(fn.str());
381
382         logger.log("files", format("Reading %s", fn));
383
384         DataFile::Parser parser(in, fn.str());
385         Loader loader(*this, fn.subpath(0, fn.size()-1));
386         loader.load(parser);
387
388         return 0;
389 }
390
391 int Builder::create_targets()
392 {
393         Target *world = new VirtualTarget(*this, "world");
394
395         Target *def_tgt = new VirtualTarget(*this, "default");
396         world->add_depend(*def_tgt);
397
398         Target *install = new VirtualTarget(*this, "install");
399         world->add_depend(*install);
400
401         Target *tarballs = new VirtualTarget(*this, "tarballs");
402         world->add_depend(*tarballs);
403
404         const PackageManager::PackageMap &packages = package_manager.get_packages();
405         for(PackageManager::PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
406                 if(i->second && i->second->is_configured())
407                         i->second->create_targets();
408
409         // Make the cmdline target depend on all targets mentioned on the command line
410         Target *cmdline = new VirtualTarget(*this, "cmdline");
411         for(list<string>::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
412         {
413                 Target *tgt = get_target(*i);
414                 if(!tgt)
415                         tgt = vfs.get_target(*i);
416                 if(!tgt)
417                         tgt = vfs.get_target(cwd/ *i);
418                 if(!tgt)
419                 {
420                         IO::print("I don't know anything about %s\n", *i);
421                         return -1;
422                 }
423
424                 cmdline->add_depend(*tgt);
425         }
426
427         cmdline->prepare();
428
429         // Apply what-ifs
430         for(StringList::iterator i=what_if.begin(); i!=what_if.end(); ++i)
431         {
432                 FileTarget *tgt = vfs.get_target(cwd/ *i);
433                 if(!tgt)
434                 {
435                         IO::print(IO::cerr, "Unknown what-if target %s\n", *i);
436                         return -1;
437                 }
438                 tgt->touch();
439         }
440
441         if(build_all)
442         {
443                 for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
444                         if(i->second->is_buildable() && !i->second->needs_rebuild())
445                                 i->second->force_rebuild();
446         }
447
448         if(!dry_run)
449         {
450                 for(PackageManager::PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
451                         i->second->save_caches();
452         }
453
454         return 0;
455 }
456
457 int Builder::do_build()
458 {
459         Target *cmdline = get_target("cmdline");
460
461         unsigned total = 0;
462         for(map<string, Target *>::const_iterator i=targets.begin(); i!=targets.end(); ++i)
463                 if(i->second->is_buildable() && i->second->needs_rebuild())
464                         ++total;
465
466         if(!total)
467         {
468                 logger.log("summary", "Already up to date");
469                 return 0;
470         }
471         logger.log("summary", format("Will build %d target%s", total, (total!=1 ? "s" : "")));
472
473         vector<Task *> tasks;
474
475         unsigned count = 0;
476
477         bool fail = false;
478         bool finish = false;
479
480         while(!finish)
481         {
482                 if(tasks.size()<jobs && !fail)
483                 {
484                         Target *tgt = cmdline->get_buildable_target();
485                         if(tgt)
486                         {
487                                 if(tgt->get_tool())
488                                         logger.log("tasks", format("%-4s  %s", tgt->get_tool()->get_tag(), tgt->get_name()));
489                                 Task *task = tgt->build();
490                                 if(task)
491                                 {
492                                         logger.log("commands", format("%s", task->get_command()));
493                                         if(dry_run)
494                                         {
495                                                 task->signal_finished.emit(true);
496                                                 delete task;
497                                         }
498                                         else
499                                         {
500                                                 task->start();
501                                                 tasks.push_back(task);
502                                         }
503                                 }
504
505                                 if(show_progress)
506                                         IO::print("%d of %d target%s built\033[1G", count, total, (total!=1 ? "s" : ""));
507                         }
508                         else if(tasks.empty())
509                                 finish = true;
510                 }
511                 else
512                         Time::sleep(10*Time::msec);
513
514                 for(unsigned i=0; i<tasks.size();)
515                 {
516                         Task::Status status = tasks[i]->check();
517                         if(status!=Task::RUNNING)
518                         {
519                                 ++count;
520
521                                 delete tasks[i];
522                                 tasks.erase(tasks.begin()+i);
523                                 if(status==Task::ERROR)
524                                         fail = true;
525                                 if(tasks.empty() && fail)
526                                         finish = true;
527                         }
528                         else
529                                 ++i;
530                 }
531         }
532
533         if(show_progress)
534                 IO::print("\033[K");
535         if(fail)
536                 logger.log("summary", "Build failed");
537         else if(show_progress)
538                 logger.log("summary", "Build complete");
539
540         return fail;
541 }
542
543 int Builder::do_clean()
544 {
545         // Cleaning doesn't care about ordering, so a simpler method can be used
546
547         set<Target *> clean_tgts;
548         list<Target *> queue;
549         queue.push_back(get_target("cmdline"));
550
551         while(!queue.empty())
552         {
553                 Target *tgt = queue.front();
554                 queue.erase(queue.begin());
555
556                 if(tgt->is_buildable() && (tgt->get_package()==main_pkg || clean>=2))
557                         clean_tgts.insert(tgt);
558
559                 const Target::Dependencies &deps = tgt->get_depends();
560                 for(list<Target *>::const_iterator i=deps.begin(); i!=deps.end(); ++i)
561                         if(!clean_tgts.count(*i))
562                                 queue.push_back(*i);
563         }
564
565         for(set<Target *>::iterator i=clean_tgts.begin(); i!=clean_tgts.end(); ++i)
566                 if(FileTarget *ft = dynamic_cast<FileTarget *>(*i))
567                         if(ft->get_mtime())
568                                 FS::unlink(ft->get_path());
569
570         return 0;
571 }
572
573 void Builder::package_help()
574 {
575         const Config &config = main_pkg->get_config();
576         const Config::OptionMap &options = config.get_options();
577
578         IO::print("Required packages:\n  ");
579         const PackageList &requires = main_pkg->get_requires();
580         for(PackageList::const_iterator i=requires.begin(); i!=requires.end(); ++i)
581         {
582                 if(i!=requires.begin())
583                         IO::print(", ");
584                 IO::print((*i)->get_name());
585         }
586         IO::print("\n\nPackage configuration:\n");
587         for(Config::OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
588         {
589                 const Config::Option &opt = i->second;
590                 IO::print("  %s: %s (%s)", opt.name, opt.descr, opt.value);
591                 if(opt.value!=opt.defv)
592                         IO::print(" [%s]", opt.defv);
593                 IO::print("\n");
594         }
595 }
596
597 string Builder::usagemsg;
598 string Builder::helpmsg;
599
600
601 Builder::Loader::Loader(Builder &b, const FS::Path &s):
602         DataFile::ObjectLoader<Builder>(b),
603         src(s)
604 {
605         add("architecture", &Loader::architecture);
606         add("binary_package", &Loader::binpkg);
607         add("profile", &Loader::profile);
608         add("package", &Loader::package);
609 }
610
611 void Builder::Loader::architecture(const string &n)
612 {
613         if(obj.current_arch->match_name(n))
614                 load_sub(*obj.current_arch);
615 }
616
617 void Builder::Loader::binpkg(const string &n)
618 {
619         BinaryPackage *pkg = new BinaryPackage(obj, n);
620         load_sub(*pkg);
621 }
622
623 void Builder::Loader::profile(const string &n)
624 {
625         StringMap prf;
626         ProfileLoader ldr(prf);
627         load_sub_with(ldr);
628         obj.profile_tmpl.insert(ProfileTemplateMap::value_type(n, prf));
629 }
630
631 void Builder::Loader::package(const string &n)
632 {
633         SourcePackage *pkg = new SourcePackage(obj, n, src);
634         if(!obj.main_pkg)
635                 obj.main_pkg = pkg;
636
637         load_sub(*pkg);
638 }
639
640
641 Builder::ProfileLoader::ProfileLoader(StringMap &p):
642         profile(p)
643 {
644         add("option", &ProfileLoader::option);
645 }
646
647 void Builder::ProfileLoader::option(const string &o, const string &v)
648 {
649         profile.insert(StringMap::value_type(o, v));
650 }