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