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