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