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