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