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