]> git.tdb.fi Git - builder.git/blob - source/builder.cpp
Some fixes to library and header searching
[builder.git] / source / builder.cpp
1 /* $Id$
2
3 This file is part of builder
4 Copyright © 2006-2007 Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
6 */
7
8 #include <fstream>
9 #include <iostream>
10 #include <set>
11 #include <msp/core/except.h>
12 #include <msp/core/getopt.h>
13 #include <msp/datafile/parser.h>
14 #include <msp/path/utils.h>
15 #include <msp/strings/formatter.h>
16 #include <msp/strings/regex.h>
17 #include <msp/strings/utils.h>
18 #include <msp/time/units.h>
19 #include <msp/time/utils.h>
20 #include "action.h"
21 #include "analyzer.h"
22 #include "binarypackage.h"
23 #include "builder.h"
24 #include "header.h"
25 #include "install.h"
26 #include "misc.h"
27 #include "package.h"
28 #include "pkgconfig.h"
29 #include "sharedlibrary.h"
30 #include "sourcepackage.h"
31 #include "systemlibrary.h"
32 #include "tarball.h"
33 #include "unlink.h"
34 #include "virtualtarget.h"
35
36 using namespace std;
37 using namespace Msp;
38
39 Builder::Builder(int argc, char **argv):
40         main_pkg(0),
41         analyzer(0),
42         build(false),
43         clean(0),
44         dry_run(false),
45         help(false),
46         verbose(1),
47         show_progress(false),
48         build_file("Build"),
49         jobs(1),
50         conf_all(false),
51         conf_only(false),
52         build_all(false),
53         create_makefile(false)
54 {
55         string   analyze_mode;
56         string   work_dir;
57         bool     full_paths=false;
58         unsigned max_depth=5;
59
60         GetOpt getopt;
61         getopt.add_option('a', "analyze",    analyze_mode, GetOpt::REQUIRED_ARG);
62         getopt.add_option('b', "build",      build,        GetOpt::NO_ARG);
63         getopt.add_option('c', "clean",      clean,        GetOpt::NO_ARG);
64         getopt.add_option('f', "file",       build_file,   GetOpt::REQUIRED_ARG);
65         getopt.add_option('h', "help",       help,         GetOpt::NO_ARG);
66         getopt.add_option('j', "jobs",       jobs,         GetOpt::REQUIRED_ARG);
67         getopt.add_option('n', "dry-run",    dry_run,      GetOpt::NO_ARG);
68         getopt.add_option('v', "verbose",    verbose,      GetOpt::NO_ARG);
69         getopt.add_option('A', "conf-all",   conf_all,     GetOpt::NO_ARG);
70         getopt.add_option('B', "build-all",  build_all,    GetOpt::NO_ARG);
71         getopt.add_option('C', "chdir",      work_dir,     GetOpt::REQUIRED_ARG);
72         getopt.add_option('P', "progress",   show_progress, GetOpt::NO_ARG);
73         getopt.add_option('W', "what-if",    what_if,      GetOpt::REQUIRED_ARG);
74         getopt.add_option(     "conf-only",  conf_only,    GetOpt::NO_ARG);
75         getopt.add_option(     "full-paths", full_paths,   GetOpt::NO_ARG);
76         //getopt.add_option(     "makefile",   create_makefile, GetOpt::NO_ARG);
77         getopt.add_option(     "max-depth",  max_depth,    GetOpt::REQUIRED_ARG);
78         getopt(argc, argv);
79
80         if(!analyze_mode.empty())
81         {
82                 analyzer=new Analyzer(*this);
83
84                 if(analyze_mode=="deps")
85                         analyzer->set_mode(Analyzer::DEPS);
86                 else if(analyze_mode=="alldeps")
87                         analyzer->set_mode(Analyzer::ALLDEPS);
88                 else if(analyze_mode=="rebuild")
89                         analyzer->set_mode(Analyzer::REBUILD);
90                 else if(analyze_mode=="rdeps")
91                         analyzer->set_mode(Analyzer::RDEPS);
92                 else
93                         throw UsageError("Invalid analyze mode");
94
95                 analyzer->set_max_depth(max_depth);
96                 analyzer->set_full_paths(full_paths);
97         }
98         else if(!clean && !create_makefile)
99                 build=true;
100
101         const vector<string> &args=getopt.get_args();
102         for(vector<string>::const_iterator i=args.begin(); i!=args.end(); ++i)
103         {
104                 unsigned equal=i->find('=');
105                 if(equal!=string::npos)
106                         cmdline_options.insert(StringMap::value_type(i->substr(0, equal), i->substr(equal+1)));
107                 else
108                         cmdline_targets.push_back(*i);
109         }
110
111         if(cmdline_targets.empty())
112                 cmdline_targets.push_back("default");
113
114         if(!work_dir.empty())
115                 chdir(work_dir.c_str());
116
117         cwd=getcwd();
118
119         Architecture &native_arch=archs.insert(ArchMap::value_type("native", Architecture(*this, "native"))).first->second;
120         native_arch.set_tool("CC",  "gcc");
121         native_arch.set_tool("CXX", "g++");
122         native_arch.set_tool("LD",  "gcc");
123         native_arch.set_tool("LXX", "g++");
124         native_arch.set_tool("AR",  "ar");
125
126         const char *home=getenv("HOME");
127         if(home)
128                 load_build_file((Path(home)/".builderrc").str());
129 }
130
131 /**
132 Gets a package with the specified name, possibly creating it.
133
134 @param   n  Package name
135
136 @return  Pointer to the package, or 0 if the package could not be located
137 */
138 Package *Builder::get_package(const string &n)
139 {
140         PackageMap::iterator i=packages.find(n);
141         if(i!=packages.end())
142                 return i->second;
143
144         // Try to get source directory with pkgconfig
145         list<string> argv;
146         argv.push_back("pkg-config");
147         argv.push_back("--variable=source");
148         argv.push_back(n);
149         if(verbose>=4)
150                 cout<<"Running "<<join(argv.begin(), argv.end())<<'\n';
151         string srcdir=strip(run_command(argv));
152
153         PathList dirs;
154         if(!srcdir.empty())
155                 dirs.push_back(srcdir);
156
157         // Make some other guesses about the source directory
158         string dirname=n;
159         if(!dirname.compare(0, 3, "msp"))
160                 dirname.erase(0, 3);
161         dirs.push_back(cwd/dirname);
162         dirs.push_back(cwd/".."/dirname);
163
164         // Go through the candidate directories and look for a Build file
165         for(PathList::iterator j=dirs.begin(); j!=dirs.end(); ++j)
166                 if(!load_build_file(*j/"Build"))
167                 {
168                         i=packages.find(n);
169                         if(i!=packages.end())
170                                 return i->second;
171                         break;
172                 }
173
174         // Package source not found - create a binary package
175         Package *pkg=BinaryPackage::from_pkgconfig(*this, n);
176
177         packages.insert(PackageMap::value_type(n, pkg));
178
179         if(!pkg)
180                 problem(n, "not found");
181
182         return pkg;
183 }
184
185 /**
186 Returns the target with the given name, or 0 if no such target exists.
187 */
188 Target *Builder::get_target(const string &n) const
189 {
190         TargetMap::const_iterator i=targets.find(n);
191         if(i!=targets.end())
192                 return i->second;
193         return 0;
194 }
195
196 /**
197 Tries to locate a header included from a given location and with a given include
198 path.  Considers known targets as well as existing files.  If a matching target
199 is not found but a file exists, a new SystemHeader target will be created and
200 returned.
201 */
202 Target *Builder::get_header(const string &include, const string &arch, const string &from, const list<string> &path)
203 {
204         string hash(8, 0);
205         update_hash(hash, from);
206         for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
207                 update_hash(hash, *i);
208
209         string id=hash+include;
210         TargetMap::iterator i=includes.find(id);
211         if(i!=includes.end())
212                 return i->second;
213
214         static string cxx_ver;
215         if(cxx_ver.empty())
216         {
217                 StringList argv;
218                 argv.push_back(get_architecture(arch).get_tool("CXX"));
219                 argv.push_back("--version");
220                 cxx_ver=Regex("[0-9]\\.[0-9.]+").match(run_command(argv))[0].str;
221                 while(!cxx_ver.empty() && !exists(Path("/usr/include/c++")/cxx_ver))
222                 {
223                         unsigned dot=cxx_ver.rfind('.');
224                         if(dot==string::npos)
225                                 break;
226                         cxx_ver.erase(dot);
227                 }
228                 if(verbose>=5)
229                         cout<<"C++ version is "<<cxx_ver<<'\n';
230         }
231
232         string fn=include.substr(1);
233         if(verbose>=5)
234                 cout<<"Looking for include "<<fn<<" with path "<<join(path.begin(), path.end())<<'\n';
235
236         StringList syspath;
237         if(arch=="native")
238                 syspath.push_back("/usr/include");
239         else
240                 syspath.push_back("/usr/"+get_architecture(arch).get_prefix()+"/include");
241         syspath.push_back((Path("/usr/include/c++/")/cxx_ver/fn).str());
242
243         Target *tgt=0;
244         if(include[0]=='\"')
245                 tgt=get_header(Path(from)/fn);
246         for(list<string>::const_iterator j=path.begin(); (!tgt && j!=path.end()); ++j)
247                 tgt=get_header(cwd/ *j/fn);
248         for(list<string>::const_iterator j=syspath.begin(); (!tgt && j!=syspath.end()); ++j)
249                 tgt=get_header(Path(*j)/fn);
250
251         includes.insert(TargetMap::value_type(id, tgt));
252
253         return tgt;
254 }
255
256 /**
257 Tries to locate a library with the given library path.  Considers known targets
258 as well as existing files.  If a matching target is not found but a file exists,
259 a new SystemLibrary target will be created and returned.
260
261 @param   lib   Name of the library to get (without "lib" prefix or extension)
262 @param   path  List of paths to search for the library
263 @param   mode  Shared / static mode
264
265 @return  Some kind of library target, if a match was found
266 */
267 Target *Builder::get_library(const string &lib, const string &arch, const list<string> &path, LibMode mode)
268 {
269         string hash(8, 0);
270         for(list<string>::const_iterator i=path.begin(); i!=path.end(); ++i)
271                 update_hash(hash, *i);
272
273         //XXX Incorporate mode into id
274         string id=hash+lib;
275         TargetMap::iterator i=libraries.find(id);
276         if(i!=libraries.end())
277                 return i->second;
278
279         StringList syspath;
280         if(arch=="native")
281         {
282                 syspath.push_back("/lib");
283                 syspath.push_back("/usr/lib");
284         }
285         else
286                 syspath.push_back("/usr/"+get_architecture(arch).get_prefix()+"/lib");
287
288         if(verbose>=5)
289                 cout<<"Looking for library "<<lib<<" with path "<<join(path.begin(), path.end())<<'\n';
290
291         Target *tgt=0;
292         for(StringList::const_iterator j=path.begin(); (!tgt && j!=path.end()); ++j)
293                 tgt=get_library(lib, arch, cwd/ *j, mode);
294         for(StringList::iterator j=syspath.begin(); (!tgt && j!=syspath.end()); ++j)
295                 tgt=get_library(lib, arch, *j, mode);
296
297         libraries.insert(TargetMap::value_type(id, tgt));
298
299         return tgt;
300 }
301
302 const Architecture &Builder::get_architecture(const string &arch) const
303 {
304         ArchMap::const_iterator i=archs.find(arch);
305         if(i==archs.end())
306                 throw InvalidParameterValue("Unknown architecture");
307
308         return i->second;
309 }
310
311 void Builder::apply_profile_template(Config &config, const string &pt) const
312 {
313         vector<string> parts=split(pt, '-');
314
315         for(vector<string>::iterator i=parts.begin(); i!=parts.end(); ++i)
316         {
317                 ProfileTemplateMap::const_iterator j=profile_tmpl.find(*i);
318                 if(j==profile_tmpl.end())
319                         continue;
320
321                 config.update(j->second);
322         }
323 }
324
325 void Builder::problem(const string &p, const string &d)
326 {
327         problems.push_back(Problem(p, d));
328 }
329
330 /**
331 Adds a target to both the target map and the new target queue.  Called from
332 Target constructor.
333 */
334 void Builder::add_target(Target *t)
335 {
336         targets.insert(TargetMap::value_type(t->get_name(), t));
337         new_tgts.push_back(t);
338 }
339
340 int Builder::main()
341 {
342         if(load_build_file(cwd/build_file))
343         {
344                 cerr<<"No build info here.\n";
345                 return 1;
346         }
347
348         main_pkg->configure(cmdline_options, conf_all?2:1);
349
350         if(help)
351         {
352                 usage(0, "builder", false);
353                 cout<<'\n';
354                 package_help();
355                 return 0;
356         }
357
358         if(!conf_only && create_targets())
359                 return 1;
360
361         PackageList all_reqs=main_pkg->collect_requires();
362
363         for(PackageList::const_iterator i=all_reqs.begin(); i!=all_reqs.end(); ++i)
364         {
365                 SourcePackage *spkg=dynamic_cast<SourcePackage *>(*i);
366                 string prob;
367                 if(spkg && spkg->get_arch()!=main_pkg->get_arch())
368                         problem(spkg->get_name(), format("wrong architecture (%s)", spkg->get_arch()));
369         }
370
371         if(conf_only)
372                 return 0;
373
374         cout<<all_reqs.size()<<" active packages, "<<targets.size()<<" targets\n";
375         if(verbose>=2)
376         {
377                 for(PackageList::const_iterator i=all_reqs.begin(); i!=all_reqs.end(); ++i)
378                 {
379                         cout<<' '<<(*i)->get_name();
380                         if(dynamic_cast<SourcePackage *>(*i))
381                                 cout<<'*';
382                         unsigned count=0;
383                         unsigned ood_count=0;
384                         for(TargetMap::iterator j=targets.begin(); j!=targets.end(); ++j)
385                                 if(j->second->get_package()==*i)
386                                 {
387                                         ++count;
388                                         if(j->second->get_rebuild())
389                                                 ++ood_count;
390                                 }
391                         if(count)
392                         {
393                                 cout<<" ("<<count<<" targets";
394                                 if(ood_count)
395                                         cout<<", "<<ood_count<<" out-of-date";
396                                 cout<<')';
397                         }
398                         cout<<'\n';
399                 }
400         }
401
402         if(analyzer)
403                 analyzer->analyze();
404
405         if(!problems.empty())
406         {
407                 cerr<<"The following problems were detected:\n";
408                 for(ProblemList::iterator i=problems.begin(); i!=problems.end(); ++i)
409                         cerr<<"  "<<i->package<<": "<<i->descr<<'\n';
410                 cerr<<"Please fix them and try again.\n";
411                 return 1;
412         }
413
414         //if(create_makefile
415
416         if(clean)
417                 exit_code=do_clean();
418         else if(build)
419                 exit_code=do_build();
420
421         return exit_code;
422 }
423
424 Builder::~Builder()
425 {
426         for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
427                 delete i->second;
428         for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
429                 delete i->second;
430         delete analyzer;
431 }
432
433 void Builder::usage(const char *reason, const char *argv0, bool brief)
434 {
435         if(reason)
436                 cerr<<reason<<'\n';
437
438         if(brief)
439                 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> ...]";
440         else
441         {
442                 cerr<<
443                         "Usage: "<<argv0<<" [options] [<target> ...]\n"
444                         "\n"
445                         "Options:\n"
446                         "  -a, --analyze MODE  Perform analysis.  MODE can be deps, alldeps or rebuild.\n"
447                         "  -b, --build         Perform build even if doing analysis.\n"
448                         "  -c, --clean         Clean buildable targets.\n"
449                         "  -f, --file FILE     Read info from FILE instead of Build.\n"
450                         "  -h, --help          Print this message.\n"
451                         "  -j, --jobs NUM      Run NUM commands at once, whenever possible.\n"
452                         "  -n, --dry-run       Don't actually do anything, only show what would be done.\n"
453                         "  -v, --verbose       Print more information about what's going on.\n"
454                         "  -A, --conf-all      Apply configuration to all packages.\n"
455                         "  -B, --build-all     Build all targets unconditionally.\n"
456                         "  -C, --chdir DIR     Change to DIR before doing anything else.\n"
457                         "  -P, --progress      Display progress while building.\n"
458                         "  -W, --what-if FILE  Pretend that FILE has changed.\n"
459                         "  --conf-only         Stop after configuring packages.\n"
460                         "  --full-paths        Output full paths in analysis.\n"
461                         //"  --makefile          Create a makefile for this package.\n"
462                         "  --max-depth NUM     Maximum depth to show in analysis.\n";
463         }
464 }
465
466 /**
467 Loads the given build file.
468
469 @param   fn  Path to the file
470
471 @return  0 on success, -1 if the file could not be opened
472 */
473 int Builder::load_build_file(const Path &fn)
474 {
475         ifstream in(fn.str().c_str());
476         if(!in)
477                 return -1;
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 }