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