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