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