]> git.tdb.fi Git - builder.git/blob - source/builder.cpp
3838ae5c0ba14813cb0c3ae795ad7c1f40649d60
[builder.git] / source / builder.cpp
1 /* $Id$
2
3 This file is part of builder
4 Copyright © 2006-2009  Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
6 */
7
8 #include <iostream>
9 #include <set>
10 #include <sys/utsname.h>
11 #include <msp/core/except.h>
12 #include <msp/core/getopt.h>
13 #include <msp/datafile/parser.h>
14 #include <msp/fs/dir.h>
15 #include <msp/fs/stat.h>
16 #include <msp/fs/utils.h>
17 #include <msp/io/buffered.h>
18 #include <msp/io/except.h>
19 #include <msp/io/file.h>
20 #include <msp/strings/formatter.h>
21 #include <msp/strings/regex.h>
22 #include <msp/strings/utils.h>
23 #include <msp/time/units.h>
24 #include <msp/time/utils.h>
25 #include "action.h"
26 #include "analyzer.h"
27 #include "binarypackage.h"
28 #include "builder.h"
29 #include "header.h"
30 #include "install.h"
31 #include "misc.h"
32 #include "package.h"
33 #include "pkgconfig.h"
34 #include "sharedlibrary.h"
35 #include "sourcepackage.h"
36 #include "systemlibrary.h"
37 #include "tarball.h"
38 #include "unlink.h"
39 #include "virtualtarget.h"
40
41 using namespace std;
42 using namespace Msp;
43
44 namespace {
45
46 void update_hash(string &hash, const string &value)
47 {
48         for(unsigned i=0; i<value.size(); ++i)
49                 hash[i%hash.size()]^=value[i];
50 }
51
52 }
53
54
55 Builder::Builder(int argc, char **argv):
56         main_pkg(0),
57         analyzer(0),
58         build(false),
59         clean(0),
60         dry_run(false),
61         help(false),
62         verbose(1),
63         show_progress(false),
64         build_file("Build"),
65         jobs(1),
66         conf_all(false),
67         conf_only(false),
68         build_all(false),
69         create_makefile(false)
70 {
71         string analyze_mode;
72         string work_dir;
73         bool full_paths=false;
74         unsigned max_depth=5;
75         StringList cmdline_warn;
76         string prfx;
77         string arch;
78
79         GetOpt getopt;
80         getopt.add_option('a', "analyze",    analyze_mode, GetOpt::REQUIRED_ARG);
81         getopt.add_option('b', "build",      build,        GetOpt::NO_ARG);
82         getopt.add_option('c', "clean",      clean,        GetOpt::NO_ARG);
83         getopt.add_option('f', "file",       build_file,   GetOpt::REQUIRED_ARG);
84         getopt.add_option('h', "help",       help,         GetOpt::NO_ARG);
85         getopt.add_option('j', "jobs",       jobs,         GetOpt::REQUIRED_ARG);
86         getopt.add_option('n', "dry-run",    dry_run,      GetOpt::NO_ARG);
87         getopt.add_option('v', "verbose",    verbose,      GetOpt::NO_ARG);
88         getopt.add_option('A', "conf-all",   conf_all,     GetOpt::NO_ARG);
89         getopt.add_option('B', "build-all",  build_all,    GetOpt::NO_ARG);
90         getopt.add_option('C', "chdir",      work_dir,     GetOpt::REQUIRED_ARG);
91         getopt.add_option('P', "progress",   show_progress, GetOpt::NO_ARG);
92         getopt.add_option('W', "what-if",    what_if,      GetOpt::REQUIRED_ARG);
93         getopt.add_option(     "arch",       arch,         GetOpt::REQUIRED_ARG);
94         getopt.add_option(     "conf-only",  conf_only,    GetOpt::NO_ARG);
95         getopt.add_option(     "full-paths", full_paths,   GetOpt::NO_ARG);
96         //getopt.add_option(     "makefile",   create_makefile, GetOpt::NO_ARG);
97         getopt.add_option(     "max-depth",  max_depth,    GetOpt::REQUIRED_ARG);
98         getopt.add_option(     "prefix",     prfx,         GetOpt::REQUIRED_ARG);
99         getopt.add_option(     "warnings",   cmdline_warn, GetOpt::REQUIRED_ARG);
100         getopt(argc, argv);
101
102         if(!analyze_mode.empty())
103         {
104                 analyzer=new Analyzer(*this);
105
106                 if(analyze_mode=="deps")
107                         analyzer->set_mode(Analyzer::DEPS);
108                 else if(analyze_mode=="alldeps")
109                         analyzer->set_mode(Analyzer::ALLDEPS);
110                 else if(analyze_mode=="rebuild")
111                         analyzer->set_mode(Analyzer::REBUILD);
112                 else if(analyze_mode=="rdeps")
113                         analyzer->set_mode(Analyzer::RDEPS);
114                 else
115                         throw UsageError("Invalid analyze mode");
116
117                 analyzer->set_max_depth(max_depth);
118                 analyzer->set_full_paths(full_paths);
119         }
120         else if(!clean && !create_makefile)
121                 build=true;
122
123         const vector<string> &args=getopt.get_args();
124         for(vector<string>::const_iterator i=args.begin(); i!=args.end(); ++i)
125         {
126                 unsigned equal=i->find('=');
127                 if(equal!=string::npos)
128                         cmdline_options.insert(StringMap::value_type(i->substr(0, equal), i->substr(equal+1)));
129                 else
130                         cmdline_targets.push_back(*i);
131         }
132
133         if(cmdline_targets.empty())
134                 cmdline_targets.push_back("default");
135
136         if(!work_dir.empty())
137                 chdir(work_dir.c_str());
138
139         cwd=FS::getcwd();
140
141         utsname un;
142         string sysname="native";
143         if(uname(&un)==0)
144                 sysname=tolower(un.sysname);
145
146         native_arch=&archs.insert(ArchMap::value_type(sysname, Architecture(*this, sysname, true))).first->second;
147         native_arch->set_tool("CC",  "gcc");
148         native_arch->set_tool("CXX", "g++");
149         native_arch->set_tool("LD",  "gcc");
150         native_arch->set_tool("LXX", "g++");
151         native_arch->set_tool("AR",  "ar");
152
153         load_build_file((FS::get_sys_data_dir(argv[0], "builder")/"builderrc").str());
154         load_build_file((FS::get_home_dir()/".builderrc").str());
155
156         if(arch.empty())
157                 current_arch=native_arch;
158         else
159                 current_arch=&get_architecture(arch);
160
161         if(prfx.empty())
162         {
163                 if(current_arch->is_native())
164                         prefix=(FS::get_home_dir()/"local").str();
165                 else
166                         prefix=(FS::get_home_dir()/"local"/current_arch->get_name()).str();
167         }
168         else
169                 prefix=FS::getcwd()/prfx;
170
171         warnings.push_back("all");
172         warnings.push_back("extra");
173         warnings.push_back("shadow");
174         warnings.push_back("pointer-arith");
175         warnings.push_back("error");
176         for(StringList::iterator i=cmdline_warn.begin(); i!=cmdline_warn.end(); ++i)
177         {
178                 vector<string> warns=split(*i, ',');
179                 warnings.insert(warnings.end(), warns.begin(), warns.end());
180         }
181
182         pkg_path.push_back(cwd/".");
183         pkg_path.push_back(cwd/"..");
184 }
185
186 Builder::~Builder()
187 {
188         for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
189                 delete i->second;
190         for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
191                 delete i->second;
192         delete analyzer;
193 }
194
195 int Builder::main()
196 {
197         if(load_build_file(cwd/build_file))
198         {
199                 cerr<<"No build info here.\n";
200                 return 1;
201         }
202
203         main_pkg->configure(cmdline_options, conf_all?2:1);
204
205         if(help)
206         {
207                 usage(0, "builder", false);
208                 cout<<'\n';
209                 package_help();
210                 return 0;
211         }
212
213         if(!conf_only && create_targets())
214                 return 1;
215
216         PackageList all_reqs=main_pkg->collect_requires();
217
218         if(conf_only)
219                 return 0;
220
221         if(verbose>=2)
222                 cout<<"Building on "<<native_arch->get_name()<<", for "<<current_arch->get_name()<<'\n';
223         if(verbose>=1)
224                 cout<<all_reqs.size()<<" active packages, "<<targets.size()<<" targets\n";
225         if(verbose>=2)
226         {
227                 for(PackageList::const_iterator i=all_reqs.begin(); i!=all_reqs.end(); ++i)
228                 {
229                         cout<<' '<<(*i)->get_name();
230                         if(dynamic_cast<SourcePackage *>(*i))
231                                 cout<<'*';
232                         unsigned count=0;
233                         unsigned ood_count=0;
234                         for(TargetMap::iterator j=targets.begin(); j!=targets.end(); ++j)
235                                 if(j->second->get_package()==*i)
236                                 {
237                                         ++count;
238                                         if(j->second->get_rebuild())
239                                                 ++ood_count;
240                                 }
241                         if(count)
242                         {
243                                 cout<<" ("<<count<<" targets";
244                                 if(ood_count)
245                                         cout<<", "<<ood_count<<" out-of-date";
246                                 cout<<')';
247                         }
248                         cout<<'\n';
249                 }
250         }
251
252         if(analyzer)
253                 analyzer->analyze();
254
255         if(!problems.empty())
256         {
257                 cerr<<"The following problems were detected:\n";
258                 for(ProblemList::iterator i=problems.begin(); i!=problems.end(); ++i)
259                         cerr<<"  "<<i->package<<": "<<i->descr<<'\n';
260                 cerr<<"Please fix them and try again.\n";
261                 return 1;
262         }
263
264         //if(create_makefile
265
266         if(clean)
267                 exit_code=do_clean();
268         else if(build)
269                 exit_code=do_build();
270
271         return exit_code;
272 }
273
274 Package *Builder::get_package(const string &name)
275 {
276         PackageMap::iterator i=packages.find(format("%s/%s", name, current_arch->get_name()));
277         if(i==packages.end())
278                 i=packages.find(name);
279         if(i!=packages.end())
280                 return i->second;
281
282         FS::Path path=get_package_location(name);
283         if(!path.empty() && !load_build_file(path/"Build"))
284         {
285                 i=packages.find(name);
286                 if(i!=packages.end())
287                         return i->second;
288         }
289
290         // Package source not found - create a binary package
291         Package *pkg=BinaryPackage::from_pkgconfig(*this, name);
292
293         packages.insert(PackageMap::value_type(name, pkg));
294
295         if(!pkg)
296                 problem(name, "not found");
297
298         return pkg;
299 }
300
301 Target *Builder::get_target(const string &n) const
302 {
303         TargetMap::const_iterator i=targets.find(n);
304         if(i!=targets.end())
305                 return i->second;
306         return 0;
307 }
308
309 Target *Builder::get_header(const string &include, const string &from, const list<string> &path)
310 {
311         string hash(8, 0);
312         if(include[0]=='\"')
313                 update_hash(hash, from);
314         for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
315                 update_hash(hash, *i);
316
317         string id=hash+include;
318         TargetMap::iterator i=includes.find(id);
319         if(i!=includes.end())
320                 return i->second;
321
322         static string cxx_ver;
323         if(cxx_ver.empty())
324         {
325                 StringList argv;
326                 argv.push_back(current_arch->get_tool("CXX"));
327                 argv.push_back("--version");
328                 cxx_ver=Regex("[0-9]\\.[0-9.]+").match(run_command(argv))[0].str;
329                 while(!cxx_ver.empty() && !FS::is_dir(FS::Path("/usr/include/c++")/cxx_ver))
330                 {
331                         unsigned dot=cxx_ver.rfind('.');
332                         if(dot==string::npos)
333                                 break;
334                         cxx_ver.erase(dot);
335                 }
336                 if(verbose>=5)
337                         cout<<"C++ version is "<<cxx_ver<<'\n';
338         }
339
340         string fn=include.substr(1);
341         if(verbose>=5)
342                 cout<<"Looking for include "<<fn<<" with path "<<join(path.begin(), path.end())<<'\n';
343
344         StringList syspath;
345         if(current_arch->is_native())
346                 syspath.push_back("/usr/include");
347         else
348                 syspath.push_back("/usr/"+current_arch->get_prefix()+"/include");
349         syspath.push_back((FS::Path("/usr/include/c++/")/cxx_ver).str());
350
351         Target *tgt=0;
352         if(include[0]=='\"')
353                 tgt=get_header(FS::Path(from)/fn);
354         for(list<string>::const_iterator j=path.begin(); (!tgt && j!=path.end()); ++j)
355                 tgt=get_header(cwd/ *j/fn);
356         for(list<string>::const_iterator j=syspath.begin(); (!tgt && j!=syspath.end()); ++j)
357                 tgt=get_header(FS::Path(*j)/fn);
358
359         includes.insert(TargetMap::value_type(id, tgt));
360
361         return tgt;
362 }
363
364 Target *Builder::get_library(const string &lib, const list<string> &path, LibMode mode)
365 {
366         string hash(8, 0);
367         for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
368                 update_hash(hash, *i);
369
370         string id=hash+string(1, mode)+lib;
371         TargetMap::iterator i=libraries.find(id);
372         if(i!=libraries.end())
373                 return i->second;
374
375         StringList syspath;
376         if(current_arch->is_native())
377         {
378                 syspath.push_back("/lib");
379                 syspath.push_back("/usr/lib");
380         }
381         else
382                 syspath.push_back("/usr/"+current_arch->get_prefix()+"/lib");
383
384         if(verbose>=5)
385                 cout<<"Looking for library "<<lib<<" with path "<<join(path.begin(), path.end())<<'\n';
386
387         Target *tgt=0;
388         for(StringList::const_iterator j=path.begin(); (!tgt && j!=path.end()); ++j)
389                 tgt=get_library(lib, cwd/ *j, mode);
390         for(StringList::iterator j=syspath.begin(); (!tgt && j!=syspath.end()); ++j)
391                 tgt=get_library(lib, *j, mode);
392
393         libraries.insert(TargetMap::value_type(id, tgt));
394
395         return tgt;
396 }
397
398 const Architecture &Builder::get_architecture(const string &arch) const
399 {
400         ArchMap::const_iterator i=archs.find(arch);
401         if(i==archs.end())
402                 throw KeyError("Unknown architecture", arch);
403
404         return i->second;
405 }
406
407 void Builder::apply_profile_template(Config &config, const string &pt) const
408 {
409         vector<string> parts=split(pt, '-');
410
411         for(vector<string>::iterator i=parts.begin(); i!=parts.end(); ++i)
412         {
413                 ProfileTemplateMap::const_iterator j=profile_tmpl.find(*i);
414                 if(j==profile_tmpl.end())
415                         continue;
416
417                 config.update(j->second);
418         }
419 }
420
421 void Builder::problem(const string &p, const string &d)
422 {
423         problems.push_back(Problem(p, d));
424 }
425
426 void Builder::add_target(Target *t)
427 {
428         targets.insert(TargetMap::value_type(t->get_name(), t));
429         new_tgts.push_back(t);
430 }
431
432 void Builder::usage(const char *reason, const char *argv0, bool brief)
433 {
434         if(reason)
435                 cerr<<reason<<'\n';
436
437         if(brief)
438                 cerr<<"Usage: "<<argv0<<" [-a|--analyze MODE] [-b|--build] [-c|--clean] [-f|--file FILE] [-h|--help] [-j|--jobs NUM] [-n||--dry-run] [-v|--verbose] [-A|--conf-all] [-B|--build-all] [-C|--chdir DIRECTORY] [-W|--what-if FILE] [--chrome] [--conf-only] [--full-paths] [--max-depth NUM] [<target> ...]\n";
439         else
440         {
441                 cerr<<
442                         "Usage: "<<argv0<<" [options] [<target> ...]\n"
443                         "\n"
444                         "Options:\n"
445                         "  -a, --analyze MODE  Perform analysis.  MODE can be deps, alldeps or rebuild.\n"
446                         "  -b, --build         Perform build even if doing analysis.\n"
447                         "  -c, --clean         Clean buildable targets.\n"
448                         "  -f, --file FILE     Read info from FILE instead of Build.\n"
449                         "  -h, --help          Print this message.\n"
450                         "  -j, --jobs NUM      Run NUM commands at once, whenever possible.\n"
451                         "  -n, --dry-run       Don't actually do anything, only show what would be done.\n"
452                         "  -v, --verbose       Print more information about what's going on.\n"
453                         "  -A, --conf-all      Apply configuration to all packages.\n"
454                         "  -B, --build-all     Build all targets unconditionally.\n"
455                         "  -C, --chdir DIR     Change to DIR before doing anything else.\n"
456                         "  -P, --progress      Display progress while building.\n"
457                         "  -W, --what-if FILE  Pretend that FILE has changed.\n"
458                         "  --arch ARCH         Architecture to build for.\n"
459                         "  --conf-only         Stop after configuring packages.\n"
460                         "  --full-paths        Output full paths in analysis.\n"
461                         //"  --makefile          Create a makefile for this package.\n"
462                         "  --max-depth NUM     Maximum depth to show in analysis.\n"
463                         "  --prefix DIR        Directory to install things to.\n"
464                         "  --warnings LIST     Compiler warnings to use.\n";
465         }
466 }
467
468 FS::Path Builder::get_package_location(const string &name)
469 {
470         if(verbose>=3)
471                 cout<<"Looking for package "<<name<<'\n';
472
473         // Try to get source directory with pkgconfig
474         list<string> argv;
475         argv.push_back("pkg-config");
476         argv.push_back("--variable=source");
477         argv.push_back(name);
478         if(verbose>=4)
479                 cout<<"Running "<<join(argv.begin(), argv.end())<<'\n';
480         string srcdir=strip(run_command(argv));
481         if(!srcdir.empty())
482                 return srcdir;
483
484         if(pkg_dirs.empty())
485         {
486                 for(list<FS::Path>::const_iterator i=pkg_path.begin(); i!=pkg_path.end(); ++i)
487                 {
488                         list<string> files=list_files(*i);
489                         for(list<string>::const_iterator j=files.begin(); j!=files.end(); ++j)
490                         {
491                                 FS::Path full=*i / *j;
492                                 if(FS::exists(full/"Build"))
493                                         pkg_dirs.push_back(full);
494                         }
495                 }
496                 if(verbose>=3)
497                         cout<<pkg_dirs.size()<<" packages found in path\n";
498         }
499
500         bool msp=!name.compare(0, 3, "msp");
501         for(list<FS::Path>::const_iterator i=pkg_dirs.begin(); i!=pkg_dirs.end(); ++i)
502         {
503                 string base=basename(*i);
504                 unsigned dash=base.rfind('-');
505
506                 if(!base.compare(0, dash, name))
507                         return *i;
508                 else if(msp && !base.compare(0, dash-3, name, 3, string::npos))
509                         return *i;
510         }
511
512         return FS::Path();
513 }
514
515 int Builder::load_build_file(const FS::Path &fn)
516 {
517         try
518         {
519                 IO::BufferedFile in(fn.str());
520
521                 if(verbose>=3)
522                         cout<<"Reading "<<fn<<'\n';
523
524                 DataFile::Parser parser(in, fn.str());
525                 Loader loader(*this, fn.subpath(0, fn.size()-1));
526                 loader.load(parser);
527         }
528         catch(const IO::FileNotFound &)
529         {
530                 return -1;
531         }
532
533         return 0;
534 }
535
536 int Builder::create_targets()
537 {
538         Target *world=new VirtualTarget(*this, "world");
539
540         Target *def_tgt=new VirtualTarget(*this, "default");
541         world->add_depend(def_tgt);
542
543         Target *install=new VirtualTarget(*this, "install");
544         world->add_depend(install);
545
546         Target *tarballs=new VirtualTarget(*this, "tarballs");
547         world->add_depend(tarballs);
548
549         PackageList all_reqs=main_pkg->collect_requires();
550         for(PackageList::iterator i=all_reqs.begin(); i!=all_reqs.end(); ++i)
551         {
552                 SourcePackage *spkg=dynamic_cast<SourcePackage *>(*i);
553                 if(!spkg)
554                         continue;
555
556                 const ComponentList &components=spkg->get_components();
557                 for(ComponentList::const_iterator j=components.begin(); j!=components.end(); ++j)
558                         j->create_targets();
559
560                 if(spkg->get_install_flags()&(SourcePackage::LIB|SourcePackage::INCLUDE))
561                 {
562                         PkgConfig *pc=new PkgConfig(*this, *spkg);
563                         install->add_depend(new Install(*this, *spkg, *pc));
564                 }
565
566                 tarballs->add_depend(new TarBall(*this, *spkg));
567         }
568
569         // Find dependencies until no new targets are created
570         while(!new_tgts.empty())
571         {
572                 Target *tgt=new_tgts.front();
573                 new_tgts.erase(new_tgts.begin());
574                 tgt->find_depends();
575                 if(!tgt->get_depends_ready())
576                         new_tgts.push_back(tgt);
577         }
578
579         // Apply what-ifs
580         for(StringList::iterator i=what_if.begin(); i!=what_if.end(); ++i)
581         {
582                 Target *tgt=get_target((cwd/ *i).str());
583                 if(!tgt)
584                 {
585                         cerr<<"Unknown what-if target "<<*i<<'\n';
586                         return -1;
587                 }
588                 tgt->touch();
589         }
590
591         // Make the cmdline target depend on all targets mentioned on the command line
592         Target *cmdline=new VirtualTarget(*this, "cmdline");
593         bool build_world=false;
594         for(list<string>::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
595         {
596                 Target *tgt=get_target(*i);
597                 if(!tgt)
598                         tgt=get_target((cwd/ *i).str());
599                 if(!tgt)
600                 {
601                         cerr<<"I don't know anything about "<<*i<<'\n';
602                         return -1;
603                 }
604                 if(tgt==world)
605                         build_world=true;
606                 cmdline->add_depend(tgt);
607         }
608
609         /* If world is to be built, prepare cmdline.  If not, add cmdline to world
610         and prepare world.  I don't really like this, but it keeps the graph
611         acyclic.
612         
613         XXX Could we skip preparing targets we are not interested in? */
614         if(build_world)
615                 cmdline->prepare();
616         else
617         {
618                 world->add_depend(cmdline);
619                 world->prepare();
620         }
621
622         for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
623                 if(SourcePackage *spkg=dynamic_cast<SourcePackage *>(i->second))
624                         spkg->get_deps_cache().save();
625
626         return 0;
627 }
628
629 Target *Builder::get_header(const Msp::FS::Path &fn)
630 {
631         Target *tgt=get_target(fn.str());
632         if(tgt) return tgt;
633
634         if(FS::is_reg(fn))
635         {
636                 tgt=new SystemHeader(*this, fn.str());
637                 return tgt;
638         }
639         return 0;
640 }
641
642 Target *Builder::get_library(const string &lib, const FS::Path &path, LibMode mode)
643 {
644         // Populate a list of candidate filenames
645         StringList candidates;
646
647         if(mode!=ALL_STATIC)
648         {
649                 if(current_arch->get_name()=="win32")
650                 {
651                         candidates.push_back("lib"+lib+".dll");
652                         candidates.push_back(lib+".dll");
653                 }
654                 else
655                         candidates.push_back("lib"+lib+".so");
656         }
657
658         /* Static libraries are always considered, since sometimes shared versions
659         may not be available */
660         candidates.push_back("lib"+lib+".a");
661         if(current_arch->get_name()=="win32")
662                 candidates.push_back("lib"+lib+".dll.a");
663
664         for(StringList::iterator i=candidates.begin(); i!=candidates.end(); ++i)
665         {
666                 string full=(path/ *i).str();
667                 Target *tgt=get_target(full);
668
669                 if(tgt)
670                 {
671                         Target *real_tgt=tgt;
672                         if(dynamic_cast<Install *>(tgt))
673                                 real_tgt=real_tgt->get_depends().front();
674
675                         /* Ignore dynamic libraries from local packages unless library mode is
676                         DYNAMIC */
677                         if(dynamic_cast<SharedLibrary *>(real_tgt) && mode!=DYNAMIC)
678                                 continue;
679                         else if(tgt)
680                                 return tgt;
681                 }
682                 else if(FS::is_reg(full))
683                 {
684                         tgt=new SystemLibrary(*this, full);
685                         return tgt;
686                 }
687         }
688
689         return 0;
690 }
691
692 int Builder::do_build()
693 {
694         Target *cmdline=get_target("cmdline");
695
696         unsigned total=cmdline->count_rebuild();
697         if(!total)
698         {
699                 cout<<"Already up to date\n";
700                 return 0;
701         }
702         if(verbose>=1)
703                 cout<<"Will build "<<total<<" target(s)\n";
704
705         vector<Action *> actions;
706
707         unsigned count=0;
708
709         bool fail=false;
710         bool finish=false;
711
712         while(!finish)
713         {
714                 if(actions.size()<jobs && !fail)
715                 {
716                         Target *tgt=cmdline->get_buildable_target();
717                         if(tgt)
718                         {
719                                 Action *action=tgt->build();
720                                 if(action)
721                                         actions.push_back(action);
722
723                                 if(show_progress)
724                                 {
725                                         cout<<count<<" of "<<total<<" targets built\033[1G";
726                                         cout.flush();
727                                 }
728                         }
729                         else if(actions.empty())
730                                 finish=true;
731                 }
732                 else
733                         Time::sleep(10*Time::msec);
734
735                 for(unsigned i=0; i<actions.size();)
736                 {
737                         int status=actions[i]->check();
738                         if(status>=0)
739                         {
740                                 ++count;
741
742                                 delete actions[i];
743                                 actions.erase(actions.begin()+i);
744                                 if(status>0)
745                                         fail=true;
746                                 if(actions.empty() && fail)
747                                         finish=true;
748                         }
749                         else
750                                 ++i;
751                 }
752         }
753
754         if(show_progress)
755                 cout<<"\033[K";
756         if(fail)
757                 cout<<"Build failed\n";
758         else if(show_progress)
759                 cout<<"Build complete\n";
760
761         return fail?1:0;
762 }
763
764 int Builder::do_clean()
765 {
766         // Cleaning doesn't care about ordering, so a simpler method can be used
767
768         set<Target *> clean_tgts;
769         TargetList queue;
770         queue.push_back(get_target("cmdline"));
771
772         while(!queue.empty())
773         {
774                 Target *tgt=queue.front();
775                 queue.erase(queue.begin());
776
777                 if(tgt->get_buildable() && (tgt->get_package()==main_pkg || clean>=2))
778                         clean_tgts.insert(tgt);
779
780                 const TargetList &deps=tgt->get_depends();
781                 for(TargetList::const_iterator i=deps.begin(); i!=deps.end(); ++i)
782                         if(!clean_tgts.count(*i))
783                                 queue.push_back(*i);
784         }
785
786         for(set<Target *>::iterator i=clean_tgts.begin(); i!=clean_tgts.end(); ++i)
787         {
788                 Action *action=new Unlink(*this, **i);
789                 while(action->check()<0) ;
790                 delete action;
791         }
792
793         return 0;
794 }
795
796 void Builder::package_help()
797 {
798         const Config &config=main_pkg->get_config();
799         const Config::OptionMap &options=config.get_options();
800
801         cout<<"Required packages:\n  ";
802         const PackageList &requires=main_pkg->get_requires();
803         for(PackageList::const_iterator i=requires.begin(); i!=requires.end(); ++i)
804         {
805                 if(i!=requires.begin())
806                         cout<<", ";
807                 cout<<(*i)->get_name();
808         }
809         cout<<"\n\n";
810         cout<<"Package configuration:\n";
811         for(Config::OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
812         {
813                 const Config::Option &opt=i->second;
814                 cout<<"  "<<opt.name<<": "<<opt.descr<<" ("<<opt.value<<") ["<<opt.defv<<"]\n";
815         }
816 }
817
818 Application::RegApp<Builder> Builder::reg;
819
820
821 Builder::Loader::Loader(Builder &b, const FS::Path &s):
822         bld(b),
823         src(s)
824 {
825         add("architecture", &Loader::architecture);
826         add("binary_package", &Loader::binpkg);
827         add("profile", &Loader::profile);
828         add("package", &Loader::package);
829 }
830
831 void Builder::Loader::architecture(const string &n)
832 {
833         Architecture arch(bld, n);
834         load_sub(arch);
835         bld.archs.insert(ArchMap::value_type(n, arch));
836 }
837
838 void Builder::Loader::binpkg(const string &n)
839 {
840         BinaryPackage *pkg=new BinaryPackage(bld, n);
841         load_sub(*pkg);
842         bld.packages.insert(PackageMap::value_type(n, pkg));
843 }
844
845 void Builder::Loader::profile(const string &n)
846 {
847         StringMap prf;
848         ProfileLoader ldr(prf);
849         load_sub_with(ldr);
850         bld.profile_tmpl.insert(ProfileTemplateMap::value_type(n, prf));
851 }
852
853 void Builder::Loader::package(const string &n)
854 {
855         SourcePackage *pkg=new SourcePackage(bld, n, src);
856         if(!bld.main_pkg)
857                 bld.main_pkg=pkg;
858
859         load_sub(*pkg);
860         bld.packages.insert(PackageMap::value_type(n, pkg));
861 }
862
863
864 Builder::ProfileLoader::ProfileLoader(StringMap &p):
865         profile(p)
866 {
867         add("option", &ProfileLoader::option);
868 }
869
870 void Builder::ProfileLoader::option(const string &o, const string &v)
871 {
872         profile.insert(StringMap::value_type(o, v));
873 }