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