]> git.tdb.fi Git - builder.git/blob - source/builder.cpp
aabfc00f3908213795ad2fd2a73fb67e6b4dbbb1
[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         //XXX Incorporate mode into id
289         string id=hash+lib;
290         TargetMap::iterator i=libraries.find(id);
291         if(i!=libraries.end())
292                 return i->second;
293
294         StringList syspath;
295         if(current_arch=="native")
296         {
297                 syspath.push_back("/lib");
298                 syspath.push_back("/usr/lib");
299         }
300         else
301                 syspath.push_back("/usr/"+get_current_arch().get_prefix()+"/lib");
302
303         if(verbose>=5)
304                 cout<<"Looking for library "<<lib<<" with path "<<join(path.begin(), path.end())<<'\n';
305
306         Target *tgt=0;
307         for(StringList::const_iterator j=path.begin(); (!tgt && j!=path.end()); ++j)
308                 tgt=get_library(lib, cwd/ *j, mode);
309         for(StringList::iterator j=syspath.begin(); (!tgt && j!=syspath.end()); ++j)
310                 tgt=get_library(lib, *j, mode);
311
312         libraries.insert(TargetMap::value_type(id, tgt));
313
314         return tgt;
315 }
316
317 const Architecture &Builder::get_architecture(const string &arch) const
318 {
319         ArchMap::const_iterator i=archs.find(arch);
320         if(i==archs.end())
321                 throw KeyError("Unknown architecture", arch);
322
323         return i->second;
324 }
325
326 const Architecture &Builder::get_current_arch() const
327 {
328         return get_architecture(current_arch);
329 }
330
331 void Builder::apply_profile_template(Config &config, const string &pt) const
332 {
333         vector<string> parts=split(pt, '-');
334
335         for(vector<string>::iterator i=parts.begin(); i!=parts.end(); ++i)
336         {
337                 ProfileTemplateMap::const_iterator j=profile_tmpl.find(*i);
338                 if(j==profile_tmpl.end())
339                         continue;
340
341                 config.update(j->second);
342         }
343 }
344
345 void Builder::problem(const string &p, const string &d)
346 {
347         problems.push_back(Problem(p, d));
348 }
349
350 /**
351 Adds a target to both the target map and the new target queue.  Called from
352 Target constructor.
353 */
354 void Builder::add_target(Target *t)
355 {
356         targets.insert(TargetMap::value_type(t->get_name(), t));
357         new_tgts.push_back(t);
358 }
359
360 int Builder::main()
361 {
362         if(load_build_file(cwd/build_file))
363         {
364                 cerr<<"No build info here.\n";
365                 return 1;
366         }
367
368         main_pkg->configure(cmdline_options, conf_all?2:1);
369
370         if(help)
371         {
372                 usage(0, "builder", false);
373                 cout<<'\n';
374                 package_help();
375                 return 0;
376         }
377
378         if(!conf_only && create_targets())
379                 return 1;
380
381         PackageList all_reqs=main_pkg->collect_requires();
382
383         if(conf_only)
384                 return 0;
385
386         cout<<all_reqs.size()<<" active packages, "<<targets.size()<<" targets\n";
387         if(verbose>=2)
388         {
389                 for(PackageList::const_iterator i=all_reqs.begin(); i!=all_reqs.end(); ++i)
390                 {
391                         cout<<' '<<(*i)->get_name();
392                         if(dynamic_cast<SourcePackage *>(*i))
393                                 cout<<'*';
394                         unsigned count=0;
395                         unsigned ood_count=0;
396                         for(TargetMap::iterator j=targets.begin(); j!=targets.end(); ++j)
397                                 if(j->second->get_package()==*i)
398                                 {
399                                         ++count;
400                                         if(j->second->get_rebuild())
401                                                 ++ood_count;
402                                 }
403                         if(count)
404                         {
405                                 cout<<" ("<<count<<" targets";
406                                 if(ood_count)
407                                         cout<<", "<<ood_count<<" out-of-date";
408                                 cout<<')';
409                         }
410                         cout<<'\n';
411                 }
412         }
413
414         if(analyzer)
415                 analyzer->analyze();
416
417         if(!problems.empty())
418         {
419                 cerr<<"The following problems were detected:\n";
420                 for(ProblemList::iterator i=problems.begin(); i!=problems.end(); ++i)
421                         cerr<<"  "<<i->package<<": "<<i->descr<<'\n';
422                 cerr<<"Please fix them and try again.\n";
423                 return 1;
424         }
425
426         //if(create_makefile
427
428         if(clean)
429                 exit_code=do_clean();
430         else if(build)
431                 exit_code=do_build();
432
433         return exit_code;
434 }
435
436 Builder::~Builder()
437 {
438         for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
439                 delete i->second;
440         for(TargetMap::iterator i=targets.begin(); i!=targets.end(); ++i)
441                 delete i->second;
442         delete analyzer;
443 }
444
445 void Builder::usage(const char *reason, const char *argv0, bool brief)
446 {
447         if(reason)
448                 cerr<<reason<<'\n';
449
450         if(brief)
451                 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> ...]";
452         else
453         {
454                 cerr<<
455                         "Usage: "<<argv0<<" [options] [<target> ...]\n"
456                         "\n"
457                         "Options:\n"
458                         "  -a, --analyze MODE  Perform analysis.  MODE can be deps, alldeps or rebuild.\n"
459                         "  -b, --build         Perform build even if doing analysis.\n"
460                         "  -c, --clean         Clean buildable targets.\n"
461                         "  -f, --file FILE     Read info from FILE instead of Build.\n"
462                         "  -h, --help          Print this message.\n"
463                         "  -j, --jobs NUM      Run NUM commands at once, whenever possible.\n"
464                         "  -n, --dry-run       Don't actually do anything, only show what would be done.\n"
465                         "  -v, --verbose       Print more information about what's going on.\n"
466                         "  -A, --conf-all      Apply configuration to all packages.\n"
467                         "  -B, --build-all     Build all targets unconditionally.\n"
468                         "  -C, --chdir DIR     Change to DIR before doing anything else.\n"
469                         "  -P, --progress      Display progress while building.\n"
470                         "  -W, --what-if FILE  Pretend that FILE has changed.\n"
471                         "  --conf-only         Stop after configuring packages.\n"
472                         "  --full-paths        Output full paths in analysis.\n"
473                         //"  --makefile          Create a makefile for this package.\n"
474                         "  --max-depth NUM     Maximum depth to show in analysis.\n";
475         }
476 }
477
478 /**
479 Loads the given build file.
480
481 @param   fn  Path to the file
482
483 @return  0 on success, -1 if the file could not be opened
484 */
485 int Builder::load_build_file(const Path &fn)
486 {
487         try
488         {
489                 IO::File inf(fn.str());
490                 IO::Buffered in(inf);
491
492                 if(verbose>=3)
493                         cout<<"Reading "<<fn<<'\n';
494
495                 DataFile::Parser parser(in, fn.str());
496                 Loader loader(*this, fn.subpath(0, fn.size()-1));
497                 loader.load(parser);
498         }
499         catch(const IO::FileNotFound &)
500         {
501                 return -1;
502         }
503
504         return 0;
505 }
506
507 /**
508 Creates targets for all packages and prepares them for building.
509
510 @return  0 if everything went ok, -1 if something bad happened and a build
511          shouldn't be attempted
512 */
513 int Builder::create_targets()
514 {
515         Target *world=new VirtualTarget(*this, "world");
516
517         Target *def_tgt=new VirtualTarget(*this, "default");
518         world->add_depend(def_tgt);
519
520         Target *install=new VirtualTarget(*this, "install");
521         world->add_depend(install);
522
523         Target *tarballs=new VirtualTarget(*this, "tarballs");
524         world->add_depend(tarballs);
525
526         PackageList all_reqs=main_pkg->collect_requires();
527         for(PackageList::iterator i=all_reqs.begin(); i!=all_reqs.end(); ++i)
528         {
529                 SourcePackage *spkg=dynamic_cast<SourcePackage *>(*i);
530                 if(!spkg)
531                         continue;
532
533                 const ComponentList &components=spkg->get_components();
534                 for(ComponentList::const_iterator j=components.begin(); j!=components.end(); ++j)
535                         j->create_targets();
536
537                 if(spkg->get_install_flags()&(SourcePackage::LIB|SourcePackage::INCLUDE))
538                 {
539                         PkgConfig *pc=new PkgConfig(*this, *spkg);
540                         install->add_depend(new Install(*this, *spkg, *pc));
541                 }
542
543                 tarballs->add_depend(new TarBall(*this, *spkg));
544         }
545
546         // Find dependencies until no new targets are created
547         while(!new_tgts.empty())
548         {
549                 Target *tgt=new_tgts.front();
550                 new_tgts.erase(new_tgts.begin());
551                 tgt->find_depends();
552                 if(!tgt->get_depends_ready())
553                         new_tgts.push_back(tgt);
554         }
555
556         // Apply what-ifs
557         for(StringList::iterator i=what_if.begin(); i!=what_if.end(); ++i)
558         {
559                 Target *tgt=get_target((cwd/ *i).str());
560                 if(!tgt)
561                 {
562                         cerr<<"Unknown what-if target "<<*i<<'\n';
563                         return -1;
564                 }
565                 tgt->touch();
566         }
567
568         // Make the cmdline target depend on all targets mentioned on the command line
569         Target *cmdline=new VirtualTarget(*this, "cmdline");
570         bool build_world=false;
571         for(list<string>::iterator i=cmdline_targets.begin(); i!=cmdline_targets.end(); ++i)
572         {
573                 Target *tgt=get_target(*i);
574                 if(!tgt)
575                         tgt=get_target((cwd/ *i).str());
576                 if(!tgt)
577                 {
578                         cerr<<"I don't know anything about "<<*i<<'\n';
579                         return -1;
580                 }
581                 if(tgt==world)
582                         build_world=true;
583                 cmdline->add_depend(tgt);
584         }
585
586         /* If world is to be built, prepare cmdline.  If not, add cmdline to world
587            and prepare world.  I don't really like this, but it keeps the graph
588            acyclic. */
589         if(build_world)
590                 cmdline->prepare();
591         else
592         {
593                 world->add_depend(cmdline);
594                 world->prepare();
595         }
596
597         for(PackageMap::iterator i=packages.begin(); i!=packages.end(); ++i)
598                 if(SourcePackage *spkg=dynamic_cast<SourcePackage *>(i->second))
599                         spkg->get_deps_cache().save();
600
601         return 0;
602 }
603
604 /**
605 Check if a header exists, either as a target or a file.  Either an existing
606 target or a new SystemHeader target will be returned.
607 */
608 Target *Builder::get_header(const Msp::Path &fn)
609 {
610         Target *tgt=get_target(fn.str());
611         if(tgt) return tgt;
612
613         if(exists(fn))
614         {
615                 tgt=new SystemHeader(*this, fn.str());
616                 return tgt;
617         }
618         return 0;
619 }
620
621 Target *Builder::get_library(const string &lib, const Path &path, LibMode mode)
622 {
623         // Populate a list of candidate filenames
624         StringList candidates;
625
626         if(mode!=ALL_STATIC)
627         {
628                 if(current_arch=="win32")
629                 {
630                         candidates.push_back("lib"+lib+".dll");
631                         candidates.push_back(lib+".dll");
632                 }
633                 else
634                         candidates.push_back("lib"+lib+".so");
635         }
636
637         /* Static libraries are always considered, since sometimes shared versions
638         may not be available */
639         candidates.push_back("lib"+lib+".a");
640         if(current_arch=="win32")
641                 candidates.push_back("lib"+lib+".dll.a");
642
643         for(StringList::iterator i=candidates.begin(); i!=candidates.end(); ++i)
644         {
645                 string full=(path/ *i).str();
646                 Target *tgt=get_target(full);
647
648                 if(tgt)
649                 {
650                         Target *real_tgt=tgt;
651                         if(dynamic_cast<Install *>(tgt))
652                                 real_tgt=real_tgt->get_depends().front();
653
654                         /* Ignore dynamic libraries from local packages unless library mode is
655                         DYNAMIC */
656                         if(dynamic_cast<SharedLibrary *>(real_tgt) && mode!=DYNAMIC)
657                                 continue;
658                         else if(tgt)
659                                 return tgt;
660                 }
661                 else if(exists(full))
662                 {
663                         tgt=new SystemLibrary(*this, full);
664                         return tgt;
665                 }
666         }
667
668         return 0;
669 }
670
671 /**
672 Updates a hash with a string.  This is used from get_header and get_library.
673 */
674 void Builder::update_hash(string &hash, const string &value)
675 {
676         for(unsigned i=0; i<value.size(); ++i)
677                 hash[i%hash.size()]^=value[i];
678 }
679
680 /**
681 This function supervises the build process, starting new actions when slots
682 become available.
683 */
684 int Builder::do_build()
685 {
686         Target *cmdline=get_target("cmdline");
687
688         unsigned total=cmdline->count_rebuild();
689         if(!total)
690         {
691                 cout<<"Already up to date\n";
692                 return 0;
693         }
694         cout<<"Will build "<<total<<" target(s)\n";
695
696         vector<Action *> actions;
697
698         unsigned count=0;
699
700         bool fail=false;
701         bool finish=false;
702
703         while(!finish)
704         {
705                 if(actions.size()<jobs && !fail)
706                 {
707                         Target *tgt=cmdline->get_buildable_target();
708                         if(tgt)
709                         {
710                                 Action *action=tgt->build();
711                                 if(action)
712                                         actions.push_back(action);
713
714                                 if(show_progress)
715                                 {
716                                         cout<<count<<" of "<<total<<" targets built\033[1G";
717                                         cout.flush();
718                                 }
719                         }
720                         else if(actions.empty())
721                                 finish=true;
722                 }
723                 else
724                         Time::sleep(10*Time::msec);
725
726                 for(unsigned i=0; i<actions.size();)
727                 {
728                         int status=actions[i]->check();
729                         if(status>=0)
730                         {
731                                 ++count;
732
733                                 delete actions[i];
734                                 actions.erase(actions.begin()+i);
735                                 if(status>0)
736                                         fail=true;
737                                 if(actions.empty() && fail)
738                                         finish=true;
739                         }
740                         else
741                                 ++i;
742                 }
743         }
744
745         if(show_progress)
746                 cout<<"\033[K";
747         if(fail)
748                 cout<<"Build failed\n";
749         else if(show_progress)
750                 cout<<"Build complete\n";
751
752         return fail?1:0;
753 }
754
755 /**
756 Cleans buildable targets.  If clean is 1, cleans only this package.  If
757 clean is 2 or greater, cleans all buildable packages.
758 */
759 int Builder::do_clean()
760 {
761         // Cleaning doesn't care about ordering, so a simpler method can be used
762
763         set<Target *> clean_tgts;
764         TargetList queue;
765         queue.push_back(get_target("cmdline"));
766
767         while(!queue.empty())
768         {
769                 Target *tgt=queue.front();
770                 queue.erase(queue.begin());
771
772                 if(tgt->get_buildable() && (tgt->get_package()==main_pkg || clean>=2))
773                         clean_tgts.insert(tgt);
774
775                 const TargetList &deps=tgt->get_depends();
776                 for(TargetList::const_iterator i=deps.begin(); i!=deps.end(); ++i)
777                         if(!clean_tgts.count(*i))
778                                 queue.push_back(*i);
779         }
780
781         for(set<Target *>::iterator i=clean_tgts.begin(); i!=clean_tgts.end(); ++i)
782         {
783                 Action *action=new Unlink(*this, **i);
784                 while(action->check()<0);
785                 delete action;
786         }
787
788         return 0;
789 }
790
791 /**
792 Prints out information about the default package.
793 */
794 void Builder::package_help()
795 {
796         const Config &config=main_pkg->get_config();
797         const Config::OptionMap &options=config.get_options();
798
799         cout<<"Required packages:\n  ";
800         const PackageList &requires=main_pkg->get_requires();
801         for(PackageList::const_iterator i=requires.begin(); i!=requires.end(); ++i)
802         {
803                 if(i!=requires.begin())
804                         cout<<", ";
805                 cout<<(*i)->get_name();
806         }
807         cout<<"\n\n";
808         cout<<"Package configuration:\n";
809         for(Config::OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
810         {
811                 const Config::Option &opt=i->second;
812                 cout<<"  "<<opt.name<<": "<<opt.descr<<" ("<<opt.value<<") ["<<opt.defv<<"]\n";
813         }
814 }
815
816 Application::RegApp<Builder> Builder::reg;
817
818
819 Builder::Loader::Loader(Builder &b, const Path &s):
820         bld(b),
821         src(s)
822 {
823         add("architecture", &Loader::architecture);
824         add("binary_package", &Loader::binpkg);
825         add("profile", &Loader::profile);
826         add("package", &Loader::package);
827 }
828
829 void Builder::Loader::architecture(const string &n)
830 {
831         Architecture arch(bld, n);
832         load_sub(arch);
833         bld.archs.insert(ArchMap::value_type(n, arch));
834 }
835
836 void Builder::Loader::binpkg(const string &n)
837 {
838         BinaryPackage *pkg=new BinaryPackage(bld, n);
839         load_sub(*pkg);
840         bld.packages.insert(PackageMap::value_type(n, pkg));
841 }
842
843 void Builder::Loader::profile(const string &n)
844 {
845         StringMap prf;
846         load_sub<ProfileLoader>(prf);
847         bld.profile_tmpl.insert(ProfileTemplateMap::value_type(n, prf));
848 }
849
850 void Builder::Loader::package(const string &n)
851 {
852         SourcePackage *pkg=new SourcePackage(bld, n, src);
853         if(!bld.main_pkg)
854                 bld.main_pkg=pkg;
855
856         load_sub(*pkg);
857         bld.packages.insert(PackageMap::value_type(n, pkg));
858 }
859
860
861 Builder::ProfileLoader::ProfileLoader(StringMap &p):
862         profile(p)
863 {
864         add("option", &ProfileLoader::option);
865 }
866
867 void Builder::ProfileLoader::option(const string &o, const string &v)
868 {
869         profile.insert(StringMap::value_type(o, v));
870 }