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