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