]> git.tdb.fi Git - builder.git/blob - source/builder.cpp
Move package management to a separate class
[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         new_tgts.push_back(t);
336 }
337
338 void Builder::usage(const char *reason, const char *argv0, bool brief)
339 {
340         if(reason)
341                 IO::print(IO::cerr, "%s\n", reason);
342
343         if(brief)
344                 IO::print(IO::cerr, "Usage: %s\n", usagemsg);
345         else
346         {
347                 IO::print(IO::cerr, "Builder 1.0\n\n");
348                 IO::print(IO::cerr, "Usage: %s [options] [<target> ...]\n\n", argv0);
349                 IO::print(IO::cerr, "Options:\n");
350                 IO::print(IO::cerr, helpmsg);
351         }
352 }
353
354 int Builder::load_build_file(const FS::Path &fn)
355 {
356         if(!FS::exists(fn))
357                 return -1;
358
359         IO::BufferedFile in(fn.str());
360
361         if(verbose>=3)
362                 IO::print("Reading %s\n", fn);
363
364         DataFile::Parser parser(in, fn.str());
365         Loader loader(*this, fn.subpath(0, fn.size()-1));
366         loader.load(parser);
367
368         return 0;
369 }
370
371 int Builder::create_targets()
372 {
373         Target *world = new VirtualTarget(*this, "world");
374
375         Target *def_tgt = new VirtualTarget(*this, "default");
376         world->add_depend(def_tgt);
377
378         Target *install = new VirtualTarget(*this, "install");
379         world->add_depend(install);
380
381         Target *tarballs = new VirtualTarget(*this, "tarballs");
382         world->add_depend(tarballs);
383
384         const PackageManager::PackageMap &packages = package_manager.get_packages();
385         for(PackageManager::PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
386                 if(i->second && i->second->is_configured())
387                         i->second->create_targets();
388
389         // Make the cmdline target depend on all targets mentioned on the command line
390         Target *cmdline = new VirtualTarget(*this, "cmdline");
391         for(list<string>::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
392         {
393                 Target *tgt = get_target(*i);
394                 if(!tgt)
395                         tgt = vfs.get_target(*i);
396                 if(!tgt)
397                         tgt = vfs.get_target(cwd/ *i);
398                 if(!tgt)
399                 {
400                         IO::print("I don't know anything about %s\n", *i);
401                         return -1;
402                 }
403
404                 cmdline->add_depend(tgt);
405         }
406
407         cmdline->prepare();
408
409         // Apply what-ifs
410         for(StringList::iterator i=what_if.begin(); i!=what_if.end(); ++i)
411         {
412                 FileTarget *tgt = vfs.get_target(cwd/ *i);
413                 if(!tgt)
414                 {
415                         IO::print(IO::cerr, "Unknown what-if target %s\n", *i);
416                         return -1;
417                 }
418                 tgt->touch();
419         }
420
421         if(build_all)
422         {
423                 for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
424                         if(i->second->is_buildable() && !i->second->needs_rebuild())
425                                 i->second->force_rebuild();
426         }
427
428         for(PackageManager::PackageMap::const_iterator i=packages.begin(); i!=packages.end(); ++i)
429                 if(SourcePackage *spkg = dynamic_cast<SourcePackage *>(i->second))
430                         spkg->get_deps_cache().save();
431
432         return 0;
433 }
434
435 int Builder::do_build()
436 {
437         Target *cmdline = get_target("cmdline");
438
439         unsigned total = 0;
440         for(map<string, Target *>::const_iterator i=targets.begin(); i!=targets.end(); ++i)
441                 if(i->second->is_buildable() && i->second->needs_rebuild())
442                         ++total;
443
444         if(!total)
445         {
446                 IO::print("Already up to date\n");
447                 return 0;
448         }
449         if(verbose>=1)
450                 IO::print("Will build %d target%s\n", total, (total!=1 ? "s" : ""));
451
452         vector<Task *> tasks;
453
454         unsigned count = 0;
455
456         bool fail = false;
457         bool finish = false;
458
459         while(!finish)
460         {
461                 if(tasks.size()<jobs && !fail)
462                 {
463                         Target *tgt = cmdline->get_buildable_target();
464                         if(tgt)
465                         {
466                                 if(tgt->get_tool())
467                                         IO::print("%-4s  %s\n", tgt->get_tool()->get_tag(), tgt->get_name());
468                                 Task *task = tgt->build();
469                                 if(task)
470                                 {
471                                         if(verbose>=2)
472                                                 IO::print("%s\n", task->get_command());
473                                         if(dry_run)
474                                         {
475                                                 task->signal_finished.emit(true);
476                                                 delete task;
477                                         }
478                                         else
479                                         {
480                                                 task->start();
481                                                 tasks.push_back(task);
482                                         }
483                                 }
484
485                                 if(show_progress)
486                                         IO::print("%d of %d target%s built\033[1G", count, total, (total!=1 ? "s" : ""));
487                         }
488                         else if(tasks.empty())
489                                 finish = true;
490                 }
491                 else
492                         Time::sleep(10*Time::msec);
493
494                 for(unsigned i=0; i<tasks.size();)
495                 {
496                         Task::Status status = tasks[i]->check();
497                         if(status!=Task::RUNNING)
498                         {
499                                 ++count;
500
501                                 delete tasks[i];
502                                 tasks.erase(tasks.begin()+i);
503                                 if(status==Task::ERROR)
504                                         fail = true;
505                                 if(tasks.empty() && fail)
506                                         finish = true;
507                         }
508                         else
509                                 ++i;
510                 }
511         }
512
513         if(show_progress)
514                 IO::print("\033[K");
515         if(fail)
516                 IO::print("Build failed\n");
517         else if(show_progress)
518                 IO::print("Build complete\n");
519
520         return fail;
521 }
522
523 int Builder::do_clean()
524 {
525         // Cleaning doesn't care about ordering, so a simpler method can be used
526
527         set<Target *> clean_tgts;
528         list<Target *> queue;
529         queue.push_back(get_target("cmdline"));
530
531         while(!queue.empty())
532         {
533                 Target *tgt = queue.front();
534                 queue.erase(queue.begin());
535
536                 if(tgt->is_buildable() && (tgt->get_package()==main_pkg || clean>=2))
537                         clean_tgts.insert(tgt);
538
539                 const Target::Dependencies &deps = tgt->get_depends();
540                 for(list<Target *>::const_iterator i=deps.begin(); i!=deps.end(); ++i)
541                         if(!clean_tgts.count(*i))
542                                 queue.push_back(*i);
543         }
544
545         for(set<Target *>::iterator i=clean_tgts.begin(); i!=clean_tgts.end(); ++i)
546                 if(FileTarget *ft = dynamic_cast<FileTarget *>(*i))
547                         if(ft->get_mtime())
548                                 FS::unlink(ft->get_path());
549
550         return 0;
551 }
552
553 void Builder::package_help()
554 {
555         const Config &config = main_pkg->get_config();
556         const Config::OptionMap &options = config.get_options();
557
558         IO::print("Required packages:\n  ");
559         const PackageList &requires = main_pkg->get_requires();
560         for(PackageList::const_iterator i=requires.begin(); i!=requires.end(); ++i)
561         {
562                 if(i!=requires.begin())
563                         IO::print(", ");
564                 IO::print((*i)->get_name());
565         }
566         IO::print("\n\nPackage configuration:\n");
567         for(Config::OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
568         {
569                 const Config::Option &opt = i->second;
570                 IO::print("  %s: %s (%s)", opt.name, opt.descr, opt.value);
571                 if(opt.value!=opt.defv)
572                         IO::print(" [%s]", opt.defv);
573                 IO::print("\n");
574         }
575 }
576
577 string Builder::usagemsg;
578 string Builder::helpmsg;
579
580
581 Builder::Loader::Loader(Builder &b, const FS::Path &s):
582         bld(b),
583         src(s)
584 {
585         add("binary_package", &Loader::binpkg);
586         add("cross_prefix", &Loader::cross_prefix);
587         add("profile", &Loader::profile);
588         add("package", &Loader::package);
589 }
590
591 void Builder::Loader::binpkg(const string &n)
592 {
593         BinaryPackage *pkg = new BinaryPackage(bld, n);
594         load_sub(*pkg);
595 }
596
597 void Builder::Loader::cross_prefix(const string &a, const string &p)
598 {
599         bld.cross_prefixes[a] = p;
600 }
601
602 void Builder::Loader::profile(const string &n)
603 {
604         StringMap prf;
605         ProfileLoader ldr(prf);
606         load_sub_with(ldr);
607         bld.profile_tmpl.insert(ProfileTemplateMap::value_type(n, prf));
608 }
609
610 void Builder::Loader::package(const string &n)
611 {
612         SourcePackage *pkg = new SourcePackage(bld, n, src);
613         if(!bld.main_pkg)
614                 bld.main_pkg = pkg;
615
616         load_sub(*pkg);
617 }
618
619
620 Builder::ProfileLoader::ProfileLoader(StringMap &p):
621         profile(p)
622 {
623         add("option", &ProfileLoader::option);
624 }
625
626 void Builder::ProfileLoader::option(const string &o, const string &v)
627 {
628         profile.insert(StringMap::value_type(o, v));
629 }