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