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